<?php
declare(strict_types=1);

namespace App\Modules\Members\Services;

use App\Core\App;

final class MembershipValidationService
{
    private static array $statusLabels = [
        'potential'           => 'عضوية محتملة',
        'under_review'        => 'تحت المراجعة',
        'interview_scheduled' => 'في انتظار المقابلة',
        'accepted'            => 'مقبول — لم يكمل الإجراءات',
        'rejected'            => 'عضوية مرفوضة',
        'payment_pending'     => 'في انتظار السداد',
        'pending_cheques'     => 'في انتظار الشيكات',
        'frozen'              => 'عضوية مجمدة',
        'suspended'           => 'عضوية موقوفة',
        'dropped'             => 'عضوية مسقطة',
        'expired'             => 'عضوية منتهية',
        'terminated'          => 'عضوية منتهية بقرار',
    ];

    public static function checkByNationalId(string $nationalId): array
    {
        $db = App::getInstance()->db();

        $member = $db->selectOne(
            "SELECT id, membership_number, full_name_ar, full_name_en, national_id,
                    date_of_birth, gender, phone, status, photo_path
             FROM members WHERE national_id = ? AND is_archived = 0",
            [$nationalId]
        );

        if (!$member) {
            return [
                'found'             => false,
                'member_id'         => null,
                'membership_number' => null,
                'member'            => null,
                'is_active_member'  => false,
                'effective_type'    => 'non_member',
                'reason'            => null,
            ];
        }

        $base = [
            'found'             => true,
            'member_id'         => (int) $member['id'],
            'membership_number' => $member['membership_number'],
            'member'            => $member,
        ];

        if ($member['status'] !== 'active') {
            $reason = self::$statusLabels[$member['status']] ?? ('حالة العضوية: ' . $member['status']);
            return $base + [
                'is_active_member' => false,
                'effective_type'   => 'non_member',
                'reason'           => $reason,
            ];
        }

        $fy = financial_year();
        $subscription = $db->selectOne(
            "SELECT id FROM subscriptions WHERE member_id = ? AND financial_year = ? AND status = 'paid' LIMIT 1",
            [(int) $member['id'], $fy]
        );

        if (!$subscription) {
            return $base + [
                'is_active_member' => false,
                'effective_type'   => 'non_member',
                'reason'           => 'لم يسدد الاشتراك السنوي (' . $fy . ')',
            ];
        }

        return $base + [
            'is_active_member' => true,
            'effective_type'   => 'member',
            'reason'           => null,
        ];
    }
}
