<?php

namespace App\Http\Controllers\Secretary;

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

class QueueController extends Controller
{
    public function index()
    {
        $doctorId = session('secretary_doctor_id');
        $queue = Queue::with(['patient.user'])
            ->where('doctor_id', $doctorId)->today()
            ->orderBy('position')->get();

        $stats = [
            'waiting'     => $queue->where('status','waiting')->count(),
            'in_progress' => $queue->whereIn('status',['in_progress','called'])->count(),
            'completed'   => $queue->where('status','completed')->count(),
            'total'       => $queue->count(),
        ];

        return view('secretary.queue.index', compact('queue','stats'));
    }

    public function addToQueue(Request $request, $patientId)
    {
        $doctorId = session('secretary_doctor_id');
        $doctor   = \App\Models\Doctor::findOrFail($doctorId);
        $patient  = Patient::findOrFail($patientId);

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

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

        $todayCount = Queue::where('doctor_id',$doctorId)->today()->count();
        if ($todayCount >= $doctor->max_daily_patients)
            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'             => $patientId,
            'appointment_id'         => $request->appointment_id ?? null,
            'queue_date'             => today(),
            'queue_number'           => $lastNum + 1,
            'position'               => $waitPos + 1,
            'status'                 => 'waiting',
            'arrived_at'             => now(),
            'estimated_wait_minutes' => ($waitPos + 1) * ($doctor->appointment_duration ?? 15),
        ]);

        if ($request->appointment_id)
            Appointment::find($request->appointment_id)?->update(['status'=>'in_queue']);

        return back()->with('success','تمت إضافة '.$patient->user->name.' إلى الطابور برقم '.($lastNum+1));
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate(['status'=>'required|in:called,in_progress,completed,skipped,left']);
        $q = Queue::where('doctor_id',session('secretary_doctor_id'))->findOrFail($id);
        $timestamps = ['called'=>['called_at'=>now()],'in_progress'=>['started_at'=>now()],'completed'=>['completed_at'=>now()]];
        $q->update(array_merge(['status'=>$request->status],$timestamps[$request->status]??[]));
        return back()->with('success','تم تحديث الحالة');
    }

    public function remove($id)
    {
        $q = Queue::where('doctor_id',session('secretary_doctor_id'))
                  ->whereIn('status',['waiting','called'])->findOrFail($id);
        $pos = $q->position;
        $q->update(['status'=>'left']);
        Queue::where('doctor_id',$q->doctor_id)->today()->waiting()->where('position','>',$pos)->decrement('position');
        return back()->with('success','تمت الإزالة من الطابور');
    }
}
