<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Patient;
use App\Models\Visit;
use App\Models\Chamber;
use Illuminate\Support\Carbon;

class BookingForm extends Component
{
    public $name = '';
    public $phone = '';
    public $gender = '';
    public $date_of_birth = '';
    public $chamber_id = '';
    public $visit_date = '';
    public $type = 'New';
    public $chief_complaints = '';

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'phone' => ['required', 'regex:/^([0-9\s\-\+\(\)]*)$/', 'min:10', 'max:20'],
            'gender' => 'nullable|in:Male,Female,Other',
            'date_of_birth' => 'nullable|date',
            'chamber_id' => 'required|exists:chambers,id',
            'visit_date' => 'required|date|after_or_equal:today',
            'type' => 'required|in:New,Follow Up',
            'chief_complaints' => 'nullable|string',
        ];
    }

    public function submit()
    {
        $this->validate();

        // Find or create patient
        $patient = Patient::firstOrCreate(
        ['phone' => $this->phone],
        [
            'name' => $this->name,
            'gender' => $this->gender ?: null,
            'date_of_birth' => $this->date_of_birth ?: null,
        ]
        );

        // Update patient details if newly provided but different
        if ($patient->name !== $this->name) {
            $patient->name = $this->name;
        }
        if ($this->gender && !$patient->gender) {
            $patient->gender = $this->gender;
        }
        if ($this->date_of_birth && !$patient->date_of_birth) {
            $patient->date_of_birth = $this->date_of_birth;
        }
        if ($patient->isDirty()) {
            $patient->save();
        }

        // Create visit
        Visit::create([
            'patient_id' => $patient->id,
            'chamber_id' => $this->chamber_id,
            'visit_date' => Carbon::parse($this->visit_date)->toDateTimeString(),
            'type' => $this->type,
            'chief_complaints' => $this->chief_complaints,
            'status' => 'Scheduled',
        ]);

        session()->flash('message', 'Thank you! Your appointment request has been scheduled. Our assistant will contact you shortly to confirm.');

        $this->reset(['name', 'phone', 'gender', 'date_of_birth', 'chamber_id', 'visit_date', 'type', 'chief_complaints']);
    }

    public function render()
    {
        return view('livewire.booking-form', [
            'chambers' => Chamber::all(),
        ]);
    }
}
