<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Queue;
use Illuminate\Http\Request;

class AppointmentController extends Controller
{
    public function index(Request $request)
    {
        $doctorId = session('doctor_id');

        $appointments = Appointment::with(['patient.user'])
            ->where('doctor_id',$doctorId)
            ->when($request->date,   fn($q) => $q->whereDate('appointment_date',$request->date))
            ->when($request->status, fn($q) => $q->where('status',$request->status))
            ->when(!$request->date && !$request->status, fn($q) =>
                $q->whereDate('appointment_date','>=',today())
            )
            ->orderBy('appointment_date')->orderBy('appointment_time')
            ->paginate(15)->withQueryString();

        return view('doctor.appointments.index', compact('appointments'));
    }

    public function confirm($id)
    {
        Appointment::where('doctor_id',session('doctor_id'))->findOrFail($id)
            ->update(['status'=>'confirmed','confirmed_at'=>now()]);
        return back()->with('success','تم تأكيد الموعد');
    }

    public function cancel($id)
    {
        Appointment::where('doctor_id',session('doctor_id'))->findOrFail($id)
            ->update(['status'=>'cancelled','cancelled_at'=>now()]);
        return back()->with('success','تم إلغاء الموعد');
    }

    public function toQueue($id)
    {
        $doctorId = session('doctor_id');
        $appt     = Appointment::where('doctor_id',$doctorId)->findOrFail($id);
        $doctor   = \App\Models\Doctor::find($doctorId);

        $exists = Queue::where('doctor_id',$doctorId)->where('patient_id',$appt->patient_id)
            ->today()->whereIn('status',['waiting','called','in_progress'])->exists();

        if ($exists) return back()->with('error','المريض موجود مسبقاً في الطابور');

        $lastNum = Queue::where('doctor_id',$doctorId)->today()->max('queue_number') ?? 0;
        $waitPos = Queue::where('doctor_id',$doctorId)->today()->whereIn('status',['waiting','called'])->count();

        Queue::create([
            'doctor_id'              => $doctorId,
            'patient_id'             => $appt->patient_id,
            'appointment_id'         => $appt->id,
            'queue_date'             => today(),
            'queue_number'           => $lastNum + 1,
            'position'               => $waitPos + 1,
            'status'                 => 'waiting',
            'arrived_at'             => now(),
            'estimated_wait_minutes' => ($waitPos+1) * ($doctor->appointment_duration ?? 15),
        ]);

        $appt->update(['status'=>'in_queue']);
        return back()->with('success','تمت إضافة المريض للطابور');
    }
}
