<?php

namespace App\Models;

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

class Doctor extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'user_id', 'specialty', 'license_number', 'bio',
        'logo', 'signature', 'prescription_header', 'prescription_footer',
        'phone', 'website',
        'experience_years', 'consultation_fee',
        'clinic_name', 'clinic_address', 'latitude', 'longitude', 'city', 'country',
        'working_hours', 'max_daily_patients', 'appointment_duration',
        'accepts_walk_ins', 'rating', 'total_reviews', 'total_patients',
        'status', 'is_verified', 'verified_at',
    ];

    protected $casts = [
        'working_hours'   => 'array',
        'is_verified'     => 'boolean',
        'accepts_walk_ins'=> 'boolean',
        'latitude'        => 'decimal:7',
        'longitude'       => 'decimal:7',
        'verified_at'     => 'datetime',
    ];

    // ===== العلاقات =====

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function appointments(): HasMany
    {
        return $this->hasMany(Appointment::class);
    }

    public function queues(): HasMany
    {
        return $this->hasMany(Queue::class);
    }

    public function medicalRecords(): HasMany
    {
        return $this->hasMany(MedicalRecord::class);
    }

    public function media(): HasMany
    {
        return $this->hasMany(DoctorMedia::class)->orderBy('sort_order');
    }

    public function images(): HasMany
    {
        return $this->hasMany(DoctorMedia::class)->where('type', 'image');
    }

    public function videos(): HasMany
    {
        return $this->hasMany(DoctorMedia::class)->where('type', 'video');
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(Review::class);
    }

    public function medicines(): HasMany
    {
        return $this->hasMany(DoctorMedicine::class)->orderByDesc('usage_count');
    }

    public function tests(): HasMany
    {
        return $this->hasMany(DoctorTest::class)->orderByDesc('usage_count');
    }

    public function secretaries(): HasMany
    {
        return $this->hasMany(Secretary::class)->where('is_active', true);
    }

    public function subscriptions(): HasMany
    {
        return $this->hasMany(Subscription::class);
    }

    // ===== الاشتراك الحالي =====
    public function activeSubscription()
    {
        return $this->hasOne(Subscription::class)
            ->where('status', 'active')
            ->where('ends_at', '>', now())
            ->latest();
    }

    // ===== Scopes =====

    public function scopeActive($query)
    {
        return $query->where('status', 'active')->where('is_verified', true);
    }

    public function scopeBySpecialty($query, string $specialty)
    {
        return $query->where('specialty', $specialty);
    }

    public function scopeNearby($query, float $lat, float $lng, int $radiusKm = 10)
    {
        // البحث بالقرب الجغرافي (Haversine Formula)
        return $query->selectRaw("
            *,
            (6371 * acos(
                cos(radians(?)) * cos(radians(latitude))
                * cos(radians(longitude) - radians(?))
                + sin(radians(?)) * sin(radians(latitude))
            )) AS distance
        ", [$lat, $lng, $lat])
        ->having('distance', '<=', $radiusKm)
        ->orderBy('distance');
    }

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

    public function getTodayQueueCount(): int
    {
        return $this->queues()
            ->whereDate('queue_date', today())
            ->whereIn('status', ['waiting', 'called', 'in_progress'])
            ->count();
    }

    public function isAvailableToday(): bool
    {
        $day = strtolower(now()->format('l')); // monday, tuesday...
        $hours = $this->working_hours[$day] ?? null;
        return $hours && $this->getTodayQueueCount() < $this->max_daily_patients;
    }
}
