<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Modules\Cashier\Services\PaymentRequestService;
use App\Modules\SportsActivity\SaConstants;

final class EnrollmentService
{
    public static function enroll(int $groupId, int $playerId): array
    {
        $db = App::getInstance()->db();

        $player = $db->selectOne(
            "SELECT * FROM sa_players WHERE id = ? AND is_archived = 0",
            [$playerId]
        );
        if (!$player) {
            return ['success' => false, 'error' => 'اللاعب غير مسجل في النظام'];
        }

        if (!in_array($player['medical_status'], [SaConstants::MEDICAL_FIT, SaConstants::MEDICAL_CONDITIONAL])) {
            return ['success' => false, 'error' => 'الحالة الطبية للاعب لا تسمح بالتسجيل (' . $player['medical_status'] . ')'];
        }

        if ($player['medical_status'] === SaConstants::MEDICAL_FIT && $player['medical_expiry_date']) {
            if ($player['medical_expiry_date'] < date('Y-m-d')) {
                return ['success' => false, 'error' => 'الشهادة الطبية منتهية الصلاحية'];
            }
        }

        $group = $db->selectOne("SELECT * FROM sa_groups WHERE id = ? AND is_archived = 0", [$groupId]);
        if (!$group) {
            return ['success' => false, 'error' => 'المجموعة غير موجودة'];
        }

        if ($group['status'] !== SaConstants::GROUP_ACTIVE) {
            return ['success' => false, 'error' => 'المجموعة غير نشطة'];
        }

        // Age validation (backwards compatible — skips if columns are NULL)
        if (!empty($group['min_age']) || !empty($group['max_age'])) {
            $playerAge = null;
            if (!empty($player['date_of_birth'])) {
                $playerAge = (int) date_diff(
                    date_create($player['date_of_birth']),
                    date_create()
                )->y;
            }
            if ($playerAge !== null) {
                if (!empty($group['min_age']) && $playerAge < (int) $group['min_age']) {
                    return ['success' => false, 'error' => 'عمر اللاعب أقل من الحد الأدنى للمجموعة (' . $group['min_age'] . ' سنة)'];
                }
                if (!empty($group['max_age']) && $playerAge > (int) $group['max_age']) {
                    return ['success' => false, 'error' => 'عمر اللاعب أكبر من الحد الأقصى للمجموعة (' . $group['max_age'] . ' سنة)'];
                }
            }
        }

        $existing = $db->selectOne(
            "SELECT id FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status IN ('active','pending_payment')",
            [$groupId, $playerId]
        );
        if ($existing) {
            return ['success' => false, 'error' => 'اللاعب مسجل بالفعل في هذه المجموعة'];
        }

        if ((int) $group['current_count'] >= (int) $group['max_capacity']) {
            return ['success' => false, 'error' => 'المجموعة ممتلئة', 'suggest_waitlist' => true];
        }

        $fee = $player['player_type'] === SaConstants::PLAYER_MEMBER
            ? (string) $group['monthly_fee_member']
            : (string) $group['monthly_fee_nonmember'];

        $employeeId = (int) (App::getInstance()->session()->get('employee_id') ?? 0);

        $db->beginTransaction();
        try {
            $enrollmentId = $db->insert('sa_group_players', [
                'group_id'    => $groupId,
                'player_id'   => $playerId,
                'enrolled_at' => date('Y-m-d'),
                'status'      => SaConstants::STATUS_PENDING_PAYMENT,
                'created_at'  => date('Y-m-d H:i:s'),
                'updated_at'  => date('Y-m-d H:i:s'),
                'created_by'  => $employeeId,
            ]);

            $memberId = !empty($player['member_id']) ? (int) $player['member_id'] : 0;
            $description = 'تسجيل رياضي — ' . $group['name_ar'] . ' — ' . $player['full_name_ar'];

            $requestResult = PaymentRequestService::createRequest([
                'member_id'           => $memberId,
                'payment_type'        => SaConstants::PAY_TYPE_SPORTS_REG,
                'amount'              => $fee,
                'description_ar'      => $description,
                'related_entity_type' => SaConstants::ENTITY_GROUP_PLAYERS,
                'related_entity_id'   => $enrollmentId,
            ]);

            if ($requestResult['success']) {
                $db->update('sa_group_players', [
                    'payment_request_id' => (int) $requestResult['request_id'],
                    'updated_at'         => date('Y-m-d H:i:s'),
                ], 'id = ?', [$enrollmentId]);
            }

            $db->commit();
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => 'فشل عملية التسجيل: ' . $e->getMessage()];
        }

        return [
            'success'        => true,
            'enrollment_id'  => $enrollmentId,
            'request_id'     => $requestResult['request_id'] ?? null,
            'request_number' => $requestResult['request_number'] ?? null,
            'fee'            => $fee,
        ];
    }

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

        $db->beginTransaction();
        try {
            $enrollment = $db->selectOne(
                "SELECT id, status FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status IN ('active','pending_payment')",
                [$groupId, $playerId]
            );

            if (!$enrollment) {
                $db->rollBack();
                return ['success' => false, 'error' => 'اللاعب غير مسجل في هذه المجموعة'];
            }

            $wasActive = $enrollment['status'] === SaConstants::STATUS_ACTIVE;

            $db->update('sa_group_players', [
                'status'     => SaConstants::STATUS_WITHDRAWN,
                'left_at'    => date('Y-m-d'),
                'notes'      => $reason ?: null,
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $enrollment['id']]);

            $newCount = null;
            if ($wasActive) {
                $group = $db->selectOne("SELECT current_count FROM sa_groups WHERE id = ? FOR UPDATE", [$groupId]);
                $newCount = max(0, (int) $group['current_count'] - 1);

                $db->update('sa_groups', [
                    'current_count' => $newCount,
                    'is_full'       => 0,
                    'updated_at'    => date('Y-m-d H:i:s'),
                ], 'id = ?', [$groupId]);
            }

            $db->commit();

            if ($wasActive) {
                WaitlistAutoOfferService::offerNextInLine($groupId);
            }

            return ['success' => true, 'new_count' => $newCount];
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => 'فشل عملية الانسحاب: ' . $e->getMessage()];
        }
    }

    public static function activateEnrollment(int $enrollmentId, int $paymentId): bool
    {
        $db = App::getInstance()->db();

        $db->beginTransaction();
        try {
            $enrollment = $db->selectOne(
                "SELECT * FROM sa_group_players WHERE id = ? AND status = 'pending_payment'",
                [$enrollmentId]
            );
            if (!$enrollment) {
                $db->rollBack();
                return false;
            }

            $db->update('sa_group_players', [
                'status'                  => SaConstants::STATUS_ACTIVE,
                'activated_by_payment_id' => $paymentId,
                'updated_at'              => date('Y-m-d H:i:s'),
            ], 'id = ?', [$enrollmentId]);

            $group = $db->selectOne(
                "SELECT current_count, max_capacity FROM sa_groups WHERE id = ? FOR UPDATE",
                [(int) $enrollment['group_id']]
            );
            $newCount = (int) $group['current_count'] + 1;
            $isFull = $newCount >= (int) $group['max_capacity'] ? 1 : 0;

            $db->update('sa_groups', [
                'current_count' => $newCount,
                'is_full'       => $isFull,
                'updated_at'    => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $enrollment['group_id']]);

            $db->commit();
            return true;
        } catch (\Throwable $e) {
            $db->rollBack();
            return false;
        }
    }

    public static function deactivateEnrollment(int $enrollmentId): bool
    {
        $db = App::getInstance()->db();

        $db->beginTransaction();
        try {
            $enrollment = $db->selectOne(
                "SELECT * FROM sa_group_players WHERE id = ? AND status = 'active'",
                [$enrollmentId]
            );
            if (!$enrollment) {
                $db->rollBack();
                return false;
            }

            $db->update('sa_group_players', [
                'status'                  => SaConstants::STATUS_PENDING_PAYMENT,
                'activated_by_payment_id' => null,
                'updated_at'              => date('Y-m-d H:i:s'),
            ], 'id = ?', [$enrollmentId]);

            $group = $db->selectOne(
                "SELECT current_count FROM sa_groups WHERE id = ? FOR UPDATE",
                [(int) $enrollment['group_id']]
            );
            $newCount = max(0, (int) $group['current_count'] - 1);

            $db->update('sa_groups', [
                'current_count' => $newCount,
                'is_full'       => 0,
                'updated_at'    => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $enrollment['group_id']]);

            $db->commit();
            return true;
        } catch (\Throwable $e) {
            $db->rollBack();
            return false;
        }
    }
}
