<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Patient extends Model
{
    use BelongsToCompany, SoftDeletes;

    protected $fillable = [
        'company_id',
        'patient_code',
        'secure_token',
        'full_name',
        'phone',
        'whatsapp',
        'gender',
        'birth_date',
        'age',
        'address',
        'national_id',
        'emergency_contact_name',
        'emergency_contact_phone',
        'medical_history',
        'chronic_diseases',
        'allergies',
        'current_medications',
        'notes',
        'status',
    ];

    protected $casts = [
        'birth_date' => 'date',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($patient) {
            // Generate unique patient_code
            $latest = self::withoutGlobalScope('company')->latest('id')->first();
            $nextId = $latest ? $latest->id + 1 : 1;
            $patient->patient_code = 'PAT-' . str_pad($nextId, 6, '0', STR_PAD_LEFT);
            
            // Generate secure token
            $patient->secure_token = Str::random(40);
        });
    }

    public function visits(): HasMany
    {
        return $this->hasMany(Visit::class)->latest('visit_date');
    }

    public function invoices(): HasMany
    {
        return $this->hasMany(Invoice::class)->latest();
    }
}
