<?php

declare(strict_types=1);

namespace App\Models\Barangay;

use App\Models\Model;
use Hypervel\Database\Eloquent\SoftDeletes;

class Resident extends Model
{
    use SoftDeletes;

    protected ?string $table = 'barangay_residents';

    protected array $fillable = [
        'hashkey', 'user_id', 'firstname', 'middlename', 'lastname', 'suffix',
        'dob', 'birthplace', 'gender', 'civil_status', 'citizenship', 'religion',
        'occupation', 'monthly_income', 'blood_type',
        'voter_status', 'registered_voter_id', 'voter_precinct', 'head_of_household',
        'purok', 'street', 'barangay', 'city', 'province', 'region',
        'philhealth_id', 'sss_id', 'gsis_id', 'tin',
        'emergency_contact_name', 'emergency_contact_phone', 'emergency_contact_address',
        'is_active', 'created_by', 'updated_by',
    ];

    protected array $casts = [
        'dob'               => 'date',
        'monthly_income'    => 'decimal:2',
        'voter_status'      => 'boolean',
        'head_of_household' => 'boolean',
        'is_active'         => 'boolean',
    ];

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

    public function household()
    {
        return $this->hasOne(Household::class, 'head_resident_id');
    }

    public function householdMemberships()
    {
        return $this->hasMany(HouseholdMember::class, 'resident_id');
    }

    public function documentRequests()
    {
        return $this->hasMany(DocumentRequest::class, 'resident_user_id', 'user_id');
    }

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

    public function getFullnameAttribute(): string
    {
        $parts = array_filter([$this->firstname, $this->middlename, $this->lastname]);
        $name = implode(' ', $parts);
        if ($this->suffix) $name .= ', ' . $this->suffix;
        return $name;
    }
}
