<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Queue extends Model
{
    protected $fillable = [
        'doctor_id', 'patient_id', 'appointment_id',
        'queue_date', 'queue_number', 'position', 'status',
        'arrived_at', 'called_at', 'started_at', 'completed_at',
        'estimated_wait_minutes',
    ];

    protected $casts = [
        'queue_date'   => 'date',
        'arrived_at'   => 'datetime',
        'called_at'    => 'datetime',
        'started_at'   => 'datetime',
        'completed_at' => 'datetime',
    ];

    // ===== العلاقات =====
    public function doctor(): BelongsTo { return $this->belongsTo(Doctor::class); }
    public function patient(): BelongsTo { return $this->belongsTo(Patient::class); }
    public function appointment(): BelongsTo { return $this->belongsTo(Appointment::class); }

    // ===== Scopes =====
    public function scopeToday($query) { return $query->whereDate('queue_date', today()); }
    public function scopeWaiting($query) { return $query->where('status', 'waiting'); }
    public function scopeActive($query)
    {
        return $query->whereIn('status', ['waiting', 'called', 'in_progress']);
    }

    // ===== Helpers =====

    /**
     * استدعاء المريض التالي في الطابور
     */
    public static function callNext(int $doctorId): ?self
    {
        $next = self::where('doctor_id', $doctorId)
            ->today()
            ->waiting()
            ->orderBy('position')
            ->first();

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

            // إرسال إشعار للمريض عبر WebSocket
            // broadcast(new PatientCalled($next))->toOthers();
        }

        return $next;
    }

    /**
     * حساب الوقت المتوقع للانتظار
     */
    public static function estimateWait(int $doctorId, int $position): int
    {
        $doctor = Doctor::find($doctorId);
        $avgDuration = $doctor?->appointment_duration ?? 15;
        return $position * $avgDuration;
    }
}
