<?php

namespace App\Domain\Identity\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Person extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable;

    protected $table = 'people';

    protected $fillable = [
        'academy_id', 'user_id', 'name', 'name_ar',
        'email', 'phone', 'phone_secondary',
        'national_id', 'date_of_birth', 'gender', 'nationality',
        'address', 'city', 'governorate',
        'photo_path', 'blood_type', 'medical_notes',
        'emergency_contact_name', 'emergency_contact_phone', 'emergency_contact_relation',
        'classification', 'source', 'notes', 'metadata', 'created_by',
    ];

    protected $casts = [
        'date_of_birth' => 'date',
        'metadata' => 'array',
    ];

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

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

    public function participant(): HasOne
    {
        return $this->hasOne(\App\Domain\Participant\Models\Participant::class);
    }

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

    public function getFullNameAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->name_ar ?: $this->name)
            : ($this->name ?: $this->name_ar);
    }
}
