<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Client extends Model
{
    protected $fillable = [
        'registration_code',
        'document_type',
        'document_number',
        'name',
        'phone',
        'email',
        'address',
        'notes',
        'photo_path',
    ];

    protected static function booted(): void
    {
        static::saving(function (Client $client): void {
            if (blank($client->document_number)) {
                $client->document_type = null;

                return;
            }
            if (blank($client->document_type)) {
                $client->document_type = 'V';
            }
        });

        static::created(function (Client $client): void {
            if ($client->registration_code) {
                return;
            }
            $client->forceFill([
                'registration_code' => 'REP-'.str_pad((string) $client->id, 6, '0', STR_PAD_LEFT),
            ])->saveQuietly();
        });
    }

    public function patients(): HasMany
    {
        return $this->hasMany(Patient::class);
    }

    public function activePatients(): HasMany
    {
        return $this->patients()->where('is_active', true)->orderBy('name');
    }
}
