<?php
declare(strict_types=1);

namespace App\Modules\Foreign\Models;

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

class ForeignMemberDetail extends Model
{
    protected static string $table = 'foreign_member_details';
    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', 'passport_number', 'issuing_country_id', 'nationality_country_id',
        'passport_issue_date', 'passport_expiry_date', 'place_of_birth',
        'fee_amount_usd', 'exchange_rate', 'fee_amount_egp',
        'fee_receipt_number', 'status', 'notes',
    ];

    public static function getForMember(int $memberId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT fd.*, ic.name_ar as issuing_country_name, nc.nationality_ar as nationality_name
             FROM foreign_member_details fd
             LEFT JOIN countries ic ON ic.id = fd.issuing_country_id
             LEFT JOIN countries nc ON nc.id = fd.nationality_country_id
             WHERE fd.member_id = ? AND fd.is_archived = 0",
            [$memberId]
        );
    }

    public static function getAllActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT fd.*, m.full_name_ar as member_name, m.membership_number,
                    ic.name_ar as issuing_country_name, nc.nationality_ar as nationality_name
             FROM foreign_member_details fd
             JOIN members m ON m.id = fd.member_id
             LEFT JOIN countries ic ON ic.id = fd.issuing_country_id
             LEFT JOIN countries nc ON nc.id = fd.nationality_country_id
             WHERE fd.is_archived = 0 AND fd.status = 'active'
             ORDER BY fd.passport_expiry_date ASC"
        );
    }

    public function isPassportExpiringSoon(int $monthsBefore = 6): bool
    {
        if (!$this->passport_expiry_date) return false;
        $expiryTs = strtotime($this->passport_expiry_date);
        $warnTs = time() + ($monthsBefore * 30 * 86400);
        return $expiryTs <= $warnTs;
    }
}