<?php
declare(strict_types=1);

namespace App\Modules\Temporary\Models;

use App\Core\Model;
use App\Core\App;

class TemporaryMember extends Model
{
    protected static string $table = 'temporary_members';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $dispatchEvents = true;

    protected static array $fillable = [
        'member_id', 'category', 'full_name_ar', 'full_name_en',
        'national_id', 'passport_number', 'date_of_birth',
        'age_years', 'age_months', 'gender', 'nationality',
        'relationship_to_member', 'has_championship', 'disability_documentation',
        'addition_fee', 'fee_breakdown_json', 'fee_receipt_number',
        'can_separate', 'can_get_independent',
        'status', 'photo_path', 'notes',
    ];

    public static function getForMember(int $memberId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM temporary_members WHERE member_id = ? AND is_archived = 0 ORDER BY created_at ASC",
            [$memberId]
        );
    }

    public static function countActiveForMember(int $memberId): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM temporary_members WHERE member_id = ? AND is_archived = 0 AND status = 'active'",
            [$memberId]
        );
        return (int) ($row['cnt'] ?? 0);
    }

    public static function getCategories(): array
    {
        return [
            'parent'              => 'والدين العضو العامل',
            'special_needs'       => 'أبناء ذوي الاحتياجات الخاصة',
            'unmarried_daughter'  => 'بنات العضو غير المتزوجات',
            'sister'              => 'شقيقة العضو العامل',
            'stepchild'           => 'أبناء الزوج/الزوجة',
            'orphan'              => 'الطفل اليتيم',
            'disabled_sibling'    => 'شقيق العضو المعاق',
            'nanny'               => 'المربية',
        ];
    }

    public function getCategoryLabel(): string
    {
        $cats = self::getCategories();
        return $cats[$this->category] ?? $this->category;
    }

    public function getStatusLabel(): string
    {
        return match ($this->status) {
            'active'   => 'نشط',
            'inactive' => 'غير نشط',
            'expired'  => 'منتهي',
            default    => $this->status,
        };
    }

    public static function nidExistsElsewhere(string $nid, ?int $excludeId = null): ?array
    {
        $db = App::getInstance()->db();

        $memberDup = $db->selectOne("SELECT id, full_name_ar FROM members WHERE national_id = ? AND is_archived = 0", [$nid]);
        if ($memberDup) return ['type' => 'member', 'data' => $memberDup];

        $spouseDup = $db->selectOne("SELECT s.id, s.full_name_ar FROM spouses s WHERE s.national_id = ? AND s.is_archived = 0", [$nid]);
        if ($spouseDup) return ['type' => 'spouse', 'data' => $spouseDup];

        $childDup = $db->selectOne("SELECT c.id, c.full_name_ar FROM children c WHERE c.national_id = ? AND c.is_archived = 0", [$nid]);
        if ($childDup) return ['type' => 'child', 'data' => $childDup];

        $sql = "SELECT t.id, t.full_name_ar FROM temporary_members t WHERE t.national_id = ? AND t.is_archived = 0";
        $params = [$nid];
        if ($excludeId) {
            $sql .= " AND t.id != ?";
            $params[] = $excludeId;
        }
        $tempDup = $db->selectOne($sql, $params);
        if ($tempDup) return ['type' => 'temporary', 'data' => $tempDup];

        return null;
    }
}