<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;
use App\Contact;
use Carbon\Carbon;
use Modules\VetClinic\Entities\VcMedicalReport;

class VcPet extends Model
{
    protected $table = 'vc_pets';
    protected $guarded = ['id'];

    protected $casts = [
        'neutered'  => 'boolean',
        'deceased'  => 'boolean',
        'dob'       => 'date',
    ];

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

    public function preferredDoctor()
    {
        return $this->belongsTo(VcDoctor::class, 'preferred_doctor_id');
    }

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

    /**
     * Effective preferred doctor id: the pet's own override, falling back to
     * the owner's general preferred doctor.
     */
    public function effectivePreferredDoctorId()
    {
        if ($this->preferred_doctor_id) {
            return $this->preferred_doctor_id;
        }
        return optional($this->ownerDetail)->preferred_doctor_id;
    }

    public function conditions()
    {
        return $this->hasMany(VcPetCondition::class, 'pet_id');
    }

    public function appointments()
    {
        return $this->hasMany(VcAppointment::class, 'pet_id');
    }

    public function vaccinations()
    {
        return $this->hasMany(VcVaccination::class, 'pet_id')->orderByDesc('administered_date');
    }

    public function prescriptions()
    {
        return $this->hasMany(VcPrescription::class, 'pet_id')->orderByDesc('prescribed_date');
    }

    public function medicalReports()
    {
        return $this->hasMany(VcMedicalReport::class, 'pet_id')->orderByDesc('created_at');
    }

    public function getPhotoUrlAttribute()
    {
        if ($this->photo_path) {
            return asset('uploads/' . $this->photo_path);
        }
        return null;
    }

    public function getAgeAttribute()
    {
        if (!$this->dob) return null;
        return Carbon::parse($this->dob)->age;
    }

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