<?php

namespace App\Modules\Pharmacy\Models;

use App\Modules\Core\Models\BaseModel;
use App\Modules\Pharmacy\Events\PrescriptionStatusChanged;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Prescription extends BaseModel
{
    protected $fillable = [
        'customer_id', 'phone', 'file_path', 'file_type', 'original_filename',
        'notes', 'status', 'reviewed_by', 'reviewed_at',
        'pharmacist_notes', 'valid_until',
    ];

    protected function casts(): array
    {
        return [
            'reviewed_at' => 'datetime',
            'valid_until' => 'date',
        ];
    }

    // ── Relationships ─────────────────────────────────────────────────────────

    public function customer(): BelongsTo
    {
        return $this->belongsTo(\App\Modules\User\Models\User::class, 'customer_id');
    }

    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(\App\Modules\User\Models\User::class, 'reviewed_by');
    }

    public function orders(): BelongsToMany
    {
        return $this->belongsToMany(
            \App\Modules\Order\Models\Order::class,
            'order_prescriptions'
        )->withTimestamps();
    }

    // ── Scopes ────────────────────────────────────────────────────────────────

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeApproved($query)
    {
        return $query->where('status', 'approved')
            ->where(fn ($q) => $q->whereNull('valid_until')
                ->orWhere('valid_until', '>=', now()->toDateString()));
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    public function isApproved(): bool
    {
        return $this->status === 'approved'
            && (! $this->valid_until || $this->valid_until->isFuture());
    }

    public function isExpired(): bool
    {
        return $this->valid_until && $this->valid_until->isPast();
    }

    public function getFileUrlAttribute(): string
    {
        return asset('storage/' . $this->file_path);
    }

    public function approve(\App\Modules\User\Models\User $pharmacist, ?string $notes = null): void
    {
        $this->update([
            'status'           => 'approved',
            'reviewed_by'      => $pharmacist->id,
            'reviewed_at'      => now(),
            'pharmacist_notes' => $notes,
            'valid_until'      => now()->addMonths(6)->toDateString(),
        ]);

        // Reload so email view gets fresh valid_until / reviewer
        $this->refresh();
        event(new PrescriptionStatusChanged($this, 'approved'));
    }

    public function reject(\App\Modules\User\Models\User $pharmacist, string $reason): void
    {
        $this->update([
            'status'           => 'rejected',
            'reviewed_by'      => $pharmacist->id,
            'reviewed_at'      => now(),
            'pharmacist_notes' => $reason,
        ]);

        $this->refresh();
        event(new PrescriptionStatusChanged($this, 'rejected'));
    }
}
