<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\Queue;
use App\Models\Appointment;
use App\Models\MedicalRecord;

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

        $stats = [
            'waiting'      => Queue::where('doctor_id',$doctorId)->today()->where('status','waiting')->count(),
            'in_progress'  => Queue::where('doctor_id',$doctorId)->today()->where('status','in_progress')->count(),
            'completed'    => Queue::where('doctor_id',$doctorId)->today()->where('status','completed')->count(),
            'appointments' => Appointment::where('doctor_id',$doctorId)->whereDate('appointment_date',today())
                                ->whereIn('status',['confirmed','pending'])->count(),
        ];

        // الطابور الحالي
        $queue = Queue::with(['patient.user','patient'])
            ->where('doctor_id',$doctorId)->today()
            ->whereIn('status',['waiting','called','in_progress'])
            ->orderBy('position')->get();

        // المريض الحالي (in_progress)
        $currentPatient = Queue::with(['patient.user','patient.medicalRecords' => fn($q) =>
                $q->where('doctor_id',$doctorId)->latest()->take(3)
            ])
            ->where('doctor_id',$doctorId)->today()
            ->where('status','in_progress')
            ->first();

        // مواعيد اليوم
        $todayAppointments = Appointment::with(['patient.user'])
            ->where('doctor_id',$doctorId)
            ->whereDate('appointment_date',today())
            ->whereIn('status',['confirmed','pending'])
            ->orderBy('appointment_time')->get();

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