<?php

namespace App\Models\CRM;

use App\Models\Result;
use App\Models\AMC\Nda;
use App\Enums\AddressType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Individual extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'phone',
        'mobile',
        'resident',
        'official',
        'employment_company',
        'employment_position',
    ];

    protected $casts = [
        'resident' => 'boolean',
        'official' => 'boolean',
    ];
    
    protected static function booted()
    {
        parent::booted();

        static::created(function ($individual) {
            // Check if an Entity already exists for this Individual
            if (!$individual->entity()->exists()) {
                $individual->entity()->create();
            }
        });

        static::deleting(function ($individual) {
            // Soft delete the related Entity
            if ($individual->entity) {
                $individual->entity->delete();
            }
        });
    }

    public function entity(): MorphOne
    {
        return $this->morphOne(Entity::class, 'entityable');
    }

    public function idCards()
    {
        return $this->morphMany(IdCard::class, 'documentable');
    }

    public function passports()
    {
        return $this->morphMany(Passport::class, 'documentable');
    }

    public function bankAccounts()
    {
        return $this->morphMany(BankAccount::class, 'documentable');
    }

    public function eurAccounts()
    {
        return $this->morphMany(EurAccount::class, 'documentable');
    }

    public function usdAccounts()
    {
        return $this->morphMany(UsdAccount::class, 'documentable');
    }

    public function securityAccounts()
    {
        return $this->morphMany(SecurityAccount::class, 'documentable');
    }


    public function addresses()
    {
        return $this->morphMany(Address::class, 'addressable');
    }
    
    public function address()
    {
        return $this->morphOne(Address::class, 'addressable');
    }

    public function lastActiveBankAccount()
    {
        return $this->morphOne(BankAccount::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActiveEurAccount()
    {
        return $this->morphOne(EurAccount::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActiveUsdAccount()
    {
        return $this->morphOne(UsdAccount::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActiveSecurityAccount()
    {
        return $this->morphOne(SecurityAccount::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActiveIdCard()
    {
        return $this->morphOne(IdCard::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActivePassport()
    {
        return $this->morphOne(Passport::class, 'documentable')
            ->active()
            ->latestOfMany();
    }

    public function lastActiveResidence()
    {
        return $this->morphOne(Address::class, 'addressable')
            ->where('type', AddressType::Residence->value)
            ->active()
            ->latest();
    }

    public function lastActiveMailing()
    {
        return $this->morphOne(Address::class, 'addressable')
            ->where('type', AddressType::Mailing->value)
            ->active()
            ->latest();
    }


    /**
     * Accessor to get the birth details.
     *
     * It returns an array with keys 'birth_city', 'birth_country' and 'date_of_birth',
     * determined from the last active IdCard or, if missing, the last active Passport.
     */
    public function getBirthDetailsAttribute(): array
    {
        $birthCity = null;
        $birthCountry = null;
        $dateOfBirth = null;

        if ($this->lastActiveIdCard) {
            // Use the IdCard's placeOfBirthCity relationship:
            $idCard = $this->lastActiveIdCard;
            $city = $idCard->placeOfBirthCity;
            $birthCity = $city?->name;
            $birthCountry = $city?->country?->name;
            $dateOfBirth = $idCard->date_of_birth?->format('d.m.Y.');
        } elseif ($this->lastActivePassport) {
            // Fallback: use Passport.
            $passport = $this->lastActivePassport;
            $city = $passport->placeOfBirthCity ?? null;
            $birthCity = $city?->name;
            $birthCountry = $city?->country?->name;
            $dateOfBirth = $passport->date_of_birth?->format('d.m.Y.');
        }

        return [
            'birth_city'    => $birthCity,
            'birth_country' => $birthCountry,
            'date_of_birth' => $dateOfBirth,
        ];
    }

    public function getIdDocumentDetailsAttribute(): array
    {
        // Use the active IdCard if available; otherwise fallback to Passport.
        $document = $this->lastActiveIdCard ?? $this->lastActivePassport;

        if (!$document) {
            return [
                'document_type'   => null,
                'document_number' => null,
                'issuer'          => null,
                'date_of_issue'   => null,
                'place_of_issue'  => null,
            ];
        }

        // Determine the document type.
        $documentType = $document instanceof \App\Models\CRM\IdCard ? 'Lična karta' : 'Pasoš';

        // Common fields.
        $documentNumber = $document->reg_no;
        $issuer = $document->issuer;
        $dateOfIssue = $document->issued_at ? $document->issued_at->format('d.m.Y') : null;

        // For an ID Card, the issuing country is always Serbia.
        // For a Passport, determine the issuing country via its relationship.
        if ($documentType === 'Lična karta') {
            $placeOfIssue = 'Srbija';
        } else {
            $placeOfIssue = $document->placeOfIssueCountry?->name;
        }

        return [
            'document_type'   => $documentType,
            'document_number' => $documentNumber,
            'issuer'          => $issuer,
            'date_of_issue'   => $dateOfIssue,
            'place_of_issue'  => $placeOfIssue,
        ];
    }
}
