<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DoctorMedicine extends Model
{
    protected $fillable = [
        'doctor_id','name','name_en','category',
        'default_dose','default_times','default_duration',
        'default_instructions','form','is_active',
        'usage_count','auto_suggest','sort_order',
    ];

    protected $casts = [
        'is_active'    => 'boolean',
        'auto_suggest' => 'boolean',
    ];

    public function doctor()
    {
        return $this->belongsTo(Doctor::class);
    }

    // الأدوية المقترحة تلقائياً (استُخدمت 3 مرات أو أكثر)
    public function scopeAutoSuggest($query, $limit = 20)
    {
        return $query->where('is_active', true)
                     ->where(fn($q) => $q->where('auto_suggest', true)->orWhere('usage_count', '>=', 3))
                     ->orderByDesc('usage_count')
                     ->limit($limit);
    }

    public function scopePopular($query, $limit = 30)
    {
        return $query->where('is_active', true)
                     ->orderByDesc('usage_count')
                     ->orderBy('sort_order')
                     ->limit($limit);
    }

    // زيادة العداد وتفعيل auto_suggest عند الوصول لـ 3
    public function incrementUsage(): void
    {
        $this->increment('usage_count');
        if ($this->usage_count >= 3 && !$this->auto_suggest) {
            $this->update(['auto_suggest' => true]);
        }
    }

    // جلب بيانات للـ JS
    public function toQuickButton(): array
    {
        return [
            'id'                   => $this->id,
            'name'                 => $this->name,
            'name_en'              => $this->name_en,
            'form'                 => $this->form,
            'default_dose'         => $this->default_dose,
            'default_times'        => $this->default_times,
            'default_duration'     => $this->default_duration,
            'default_instructions' => $this->default_instructions,
            'usage_count'          => $this->usage_count,
        ];
    }
}
