<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\SportsActivity\SaConstants;

final class PlayerLifecycleService
{
    public static function pause(int $groupId, int $playerId, string $month, string $reason = ''): array
    {
        $db = App::getInstance()->db();

        $enrollment = $db->selectOne(
            "SELECT id, paused_months FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status = ?",
            [$groupId, $playerId, SaConstants::STATUS_ACTIVE]
        );
        if (!$enrollment) {
            return ['success' => false, 'error' => 'اللاعب غير مسجل أو غير نشط في هذه المجموعة'];
        }

        if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
            return ['success' => false, 'error' => 'صيغة الشهر غير صحيحة (YYYY-MM)'];
        }

        $pausedMonths = json_decode($enrollment['paused_months'] ?? '[]', true) ?: [];
        if (in_array($month, $pausedMonths, true)) {
            return ['success' => false, 'error' => 'الشهر متوقف بالفعل'];
        }

        $maxPauses = self::getConfig('sa.max_pause_months', 3);
        if (count($pausedMonths) >= $maxPauses) {
            return ['success' => false, 'error' => "تم تجاوز الحد الأقصى لعدد شهور الإيقاف ({$maxPauses} شهور)"];
        }

        $pausedMonths[] = $month;
        sort($pausedMonths);

        $db->update('sa_group_players', [
            'paused_months' => json_encode($pausedMonths),
            'notes'         => $reason ? ($enrollment['notes'] ?? '') . "\nإيقاف {$month}: {$reason}" : null,
            'updated_at'    => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $enrollment['id']]);

        $existingSub = $db->selectOne(
            "SELECT id, payment_status FROM sa_subscriptions WHERE player_id = ? AND group_id = ? AND period_start = ?",
            [$playerId, $groupId, $month . '-01']
        );
        if ($existingSub && $existingSub['payment_status'] === SaConstants::PAYMENT_UNPAID) {
            $db->update('sa_subscriptions', [
                'exemption_reason' => 'إيقاف مؤقت',
                'final_amount'     => '0.00',
                'updated_at'       => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $existingSub['id']]);
        }

        EventBus::dispatch('sa.player.paused', [
            'player_id' => $playerId,
            'group_id'  => $groupId,
            'month'     => $month,
            'reason'    => $reason,
        ]);

        return ['success' => true, 'paused_months' => $pausedMonths];
    }

    public static function resume(int $groupId, int $playerId, string $month): array
    {
        $db = App::getInstance()->db();

        $enrollment = $db->selectOne(
            "SELECT id, paused_months FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status = ?",
            [$groupId, $playerId, SaConstants::STATUS_ACTIVE]
        );
        if (!$enrollment) {
            return ['success' => false, 'error' => 'اللاعب غير مسجل أو غير نشط في هذه المجموعة'];
        }

        $pausedMonths = json_decode($enrollment['paused_months'] ?? '[]', true) ?: [];
        $key = array_search($month, $pausedMonths, true);
        if ($key === false) {
            return ['success' => false, 'error' => 'هذا الشهر غير متوقف'];
        }

        array_splice($pausedMonths, $key, 1);

        $db->update('sa_group_players', [
            'paused_months' => !empty($pausedMonths) ? json_encode($pausedMonths) : null,
            'updated_at'    => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $enrollment['id']]);

        EventBus::dispatch('sa.player.resumed', [
            'player_id' => $playerId,
            'group_id'  => $groupId,
            'month'     => $month,
        ]);

        return ['success' => true, 'paused_months' => $pausedMonths];
    }

    public static function checkMedicalGraceExpired(): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        $expired = $db->select(
            "SELECT gp.id, gp.player_id, gp.group_id, sp.full_name_ar, g.name_ar as group_name
             FROM sa_group_players gp
             JOIN sa_players sp ON sp.id = gp.player_id
             JOIN sa_groups g ON g.id = gp.group_id
             WHERE gp.status = ? AND gp.medical_grace_deadline IS NOT NULL AND gp.medical_grace_deadline < ?
               AND sp.medical_status NOT IN (?, ?)",
            [
                SaConstants::STATUS_ACTIVE,
                $today,
                SaConstants::MEDICAL_FIT,
                SaConstants::MEDICAL_CONDITIONAL,
            ]
        );

        $suspended = 0;
        foreach ($expired as $row) {
            $db->update('sa_group_players', [
                'status'     => SaConstants::STATUS_WITHDRAWN,
                'left_at'    => $today,
                'notes'      => 'إيقاف تلقائي — انتهاء مهلة الشهادة الطبية',
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $row['id']]);

            $group = $db->selectOne(
                "SELECT current_count FROM sa_groups WHERE id = ?",
                [(int) $row['group_id']]
            );
            $newCount = max(0, (int) ($group['current_count'] ?? 0) - 1);
            $db->update('sa_groups', [
                'current_count' => $newCount,
                'is_full'       => 0,
                'updated_at'    => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $row['group_id']]);

            EventBus::dispatch('sa.medical_grace.expired', [
                'player_id'   => (int) $row['player_id'],
                'group_id'    => (int) $row['group_id'],
                'player_name' => $row['full_name_ar'],
            ]);

            $suspended++;
        }

        return ['success' => true, 'suspended' => $suspended];
    }

    public static function extendMedicalGrace(int $enrollmentId, int $extraDays): array
    {
        $db = App::getInstance()->db();

        $enrollment = $db->selectOne(
            "SELECT * FROM sa_group_players WHERE id = ? AND status IN (?, ?)",
            [$enrollmentId, SaConstants::STATUS_ACTIVE, SaConstants::STATUS_PENDING_PAYMENT]
        );
        if (!$enrollment) {
            return ['success' => false, 'error' => 'التسجيل غير موجود'];
        }

        $baseDate = !empty($enrollment['medical_grace_deadline'])
            ? max($enrollment['medical_grace_deadline'], date('Y-m-d'))
            : date('Y-m-d');

        $newDeadline = date('Y-m-d', strtotime($baseDate . " +{$extraDays} days"));

        $db->update('sa_group_players', [
            'medical_grace_deadline' => $newDeadline,
            'updated_at'             => date('Y-m-d H:i:s'),
        ], 'id = ?', [$enrollmentId]);

        return ['success' => true, 'new_deadline' => $newDeadline];
    }

    private static function getConfig(string $key, $default = null)
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT config_value FROM system_config WHERE config_key = ?",
            [$key]
        );
        return $row ? $row['config_value'] : $default;
    }
}
