<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class Customer extends Model
{
    use HasFactory, SoftDeletes, BelongsToCompany, HasUuid;

    protected $fillable = [
        'uuid', 'company_id', 'user_id',
        'first_name', 'second_name', 'last_name', 'second_lastname',
        'email', 'phone',
        'document_type', 'document_number',
        'birthdate', 'gender', 'address', 'city', 'country',
        'blood_type', 'insurance_company',
        'emergency_contact_name', 'emergency_contact_phone',
        'notes', 'is_frequent', 'is_active', 'marketing_opt_in',
        'first_booking_at', 'last_booking_at',
        'total_bookings', 'total_spent',
    ];

    protected function casts(): array
    {
        return [
            'birthdate'         => 'date',
            'is_frequent'       => 'boolean',
            'is_active'         => 'boolean',
            'marketing_opt_in'  => 'boolean',
            'first_booking_at'  => 'datetime',
            'last_booking_at'   => 'datetime',
            'total_spent'       => 'decimal:2',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

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

    public function clinicalHistory(): HasOne
    {
        return $this->hasOne(ClinicalHistory::class);
    }

    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', true);
    }

    public function scopeFrequent(Builder $q): Builder
    {
        return $q->where('is_frequent', true);
    }

    public function fullName(): string
    {
        return trim(implode(' ', array_filter([
            $this->first_name,
            $this->second_name,
            $this->last_name,
            $this->second_lastname,
        ])));
    }

    public function age(): ?int
    {
        return $this->birthdate?->age;
    }

    public function clinicalEvolutions(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(ClinicalEvolution::class);
    }

    public function prescriptions(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Prescription::class);
    }

    public function clinicalOrders(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(ClinicalOrder::class);
    }
}
