<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;
use App\Contact;
use Carbon\Carbon;

class ClcVaccination extends Model
{
    protected $table = 'clc_vaccinations';
    protected $guarded = ['id'];

    protected $casts = [
        'administered_date' => 'date',
        'next_due_date'     => 'date',
        'reminder_sent'     => 'boolean',
        'waived_at'         => 'datetime',
    ];

    public function getIsWaivedAttribute(): bool
    {
        return $this->waived_at !== null;
    }

    public function pet()
    {
        return $this->belongsTo(ClcPatient::class, 'patient_id');
    }

    public function owner()
    {
        return $this->belongsTo(Contact::class, 'contact_id');
    }

    public function vaccineType()
    {
        return $this->belongsTo(ClcVaccineType::class, 'vaccine_type_id');
    }

    public function appointment()
    {
        return $this->belongsTo(ClcAppointment::class, 'appointment_id');
    }

    public function medicine()
    {
        return $this->belongsTo(ClcMedicine::class, 'medicine_id');
    }

    public function doctor()
    {
        return $this->belongsTo(ClcDoctor::class, 'administered_by');
    }

    public function getDueStatusAttribute()
    {
        if ($this->waived_at) return 'waived';

        $threshold = (int) config('cliniccore.reminder_days', 30);

        // Not-taken (scheduled) records: urgency based on the scheduled administration date
        if ($this->taken_status === 'not_taken' || $this->status === 'scheduled') {
            if (!$this->administered_date) return null;
            $days = (int) now()->diffInDays($this->administered_date, false);
            if ($days < 0)          return 'overdue';
            if ($days <= $threshold) return 'due_soon';
            return 'upcoming';
        }

        // Taken records: next_due_date is the reminder for the next dose
        // Only show a badge when the next dose is itself approaching
        if (!$this->next_due_date) return null;
        $days = (int) now()->diffInDays($this->next_due_date, false);
        if ($days < 0)          return 'overdue';
        if ($days <= $threshold) return 'due_soon';
        return null; // taken + far future → no badge; the auto-created not_taken record carries the reminder
    }

    public function getDueBadgeColorAttribute()
    {
        return [
            'overdue'  => 'danger',
            'due_soon' => 'warning',
            'upcoming' => 'success',
        ][$this->due_status] ?? 'default';
    }
}
