<?php

namespace App\Http\Controllers\Doctor;

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

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

        $queue = Queue::with(['patient.user','patient'])
            ->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(),
        ];

        $currentPatient = $queue->where('status','in_progress')->first();

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

    // استدعاء التالي
    public function callNext()
    {
        $doctorId = session('doctor_id');

        // إنهاء الحالي أولاً
        Queue::where('doctor_id',$doctorId)->today()
             ->where('status','in_progress')
             ->update(['status'=>'completed','completed_at'=>now()]);

        $next = Queue::where('doctor_id',$doctorId)->today()
                     ->where('status','waiting')
                     ->orderBy('position')->first();

        if (!$next) {
            return back()->with('error','لا يوجد مرضى في الانتظار');
        }

        $next->update(['status'=>'called','called_at'=>now()]);

        return back()->with('success','تم استدعاء المريض: '.$next->patient->user->name.' رقم '.$next->queue_number);
    }

    // بدء الفحص
    public function startExam($id)
    {
        $q = Queue::where('doctor_id',session('doctor_id'))->findOrFail($id);
        $q->update(['status'=>'in_progress','started_at'=>now()]);
        return back()->with('success','بدأ فحص المريض '.$q->patient->user->name);
    }

    // إنهاء الفحص
    public function completeExam($id)
    {
        $q = Queue::where('doctor_id',session('doctor_id'))->findOrFail($id);
        $q->update(['status'=>'completed','completed_at'=>now()]);
        return back()->with('success','تم إنهاء فحص المريض '.$q->patient->user->name);
    }

    // تخطي
    public function skip($id)
    {
        $q = Queue::where('doctor_id',session('doctor_id'))->findOrFail($id);
        $pos = $q->position;
        $q->update(['status'=>'skipped']);
        Queue::where('doctor_id',$q->doctor_id)->today()->waiting()
             ->where('position','>',$pos)->decrement('position');
        return back()->with('success','تم تخطي المريض');
    }
}
