<?php
declare(strict_types=1);

namespace App\Modules\Carnets\Services;

use App\Core\App;
use App\Modules\Fines\Models\Fine;

final class CarnetPrintService
{
    /**
     * Check if a member is eligible to have a carnet printed.
     * Returns array of blocking reasons. Empty array = eligible.
     */
    public static function checkEligibility(int $memberId): array
    {
        $db = App::getInstance()->db();
        $reasons = [];

        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [$memberId]);
        if (!$member) {
            return ['العضو غير موجود'];
        }

        // Must be active
        if (!in_array($member['status'], ['active', 'payment_pending'])) {
            $reasons[] = 'حالة العضوية: ' . $member['status'] . ' — يجب أن تكون فعالة';
        }

        // Check subscription paid (current year)
        if ($db->tableExists('subscriptions')) {
            $currentYear = self::getCurrentFinancialYear();
            $unpaidSub = $db->selectOne(
                "SELECT COUNT(*) as cnt FROM subscriptions WHERE member_id = ? AND financial_year = ? AND status NOT IN ('paid','exempt')",
                [$memberId, $currentYear]
            );
            if (((int) ($unpaidSub['cnt'] ?? 0)) > 0) {
                $reasons[] = 'الاشتراك السنوي للعام ' . $currentYear . ' غير مدفوع';
            }
        }

        // Check no active suspension/ban
        if ($db->tableExists('fines')) {
            if (Fine::isSuspended($memberId)) {
                $reasons[] = 'العضو موقوف حالياً';
            }
        }

        // Check no overdue installments
        if ($db->tableExists('installment_plans') && $db->tableExists('installment_schedule')) {
            $overdue = $db->selectOne(
                "SELECT COUNT(*) as cnt FROM installment_schedule s
                 JOIN installment_plans p ON p.id = s.installment_plan_id
                 WHERE p.member_id = ? AND p.status = 'active' AND s.status = 'pending' AND s.due_date < CURDATE()",
                [$memberId]
            );
            if (((int) ($overdue['cnt'] ?? 0)) > 0) {
                $reasons[] = 'يوجد أقساط متأخرة';
            }
        }

        return $reasons;
    }

    private static function getCurrentFinancialYear(): string
    {
        $month = (int) date('n');
        $year = (int) date('Y');
        if ($month >= 7) {
            return $year . '/' . ($year + 1);
        }
        return ($year - 1) . '/' . $year;
    }
}