<?php
declare(strict_types=1);

namespace App\Modules\Honorary\Models;

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

class HonoraryMember extends Model
{
    protected static string $table = 'honorary_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', 'granted_by_decision', 'reason', 'start_date', 'end_date',
        'is_renewable', 'renewal_count', 'last_renewed_at', 'status', 'notes',
    ];

    public static function getForMember(int $memberId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM honorary_members WHERE member_id = ? AND is_archived = 0 ORDER BY start_date DESC LIMIT 1",
            [$memberId]
        );
    }

    public static function getAllActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT h.*, m.full_name_ar as member_name, m.membership_number
             FROM honorary_members h
             JOIN members m ON m.id = h.member_id
             WHERE h.is_archived = 0 AND h.status = 'active'
             ORDER BY h.end_date ASC"
        );
    }

    public function isExpiring(int $daysBefore = 30): bool
    {
        if (!$this->end_date) return false;
        $endTs = strtotime($this->end_date);
        $warnTs = time() + ($daysBefore * 86400);
        return $endTs <= $warnTs && $endTs >= time();
    }
}