<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

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

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'], ['fit', 'conditional'])) {
            return ['success' => false, 'error' => 'الحالة الطبية للاعب لا تسمح بالتسجيل (' . $player['medical_status'] . ')'];
        }

        if ($player['medical_status'] === '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'] !== 'active') {
            return ['success' => false, 'error' => 'المجموعة غير نشطة'];
        }

        $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'] === 'member'
            ? (string) $group['monthly_fee_member']
            : (string) $group['monthly_fee_nonmember'];

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

        $enrollmentId = $db->insert('sa_group_players', [
            'group_id'    => $groupId,
            'player_id'   => $playerId,
            'enrolled_at' => date('Y-m-d'),
            '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'        => 'sports_registration',
            'amount'              => $fee,
            'description_ar'      => $description,
            'related_entity_type' => 'sa_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]);
        }

        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();

        $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) {
            return ['success' => false, 'error' => 'اللاعب غير مسجل في هذه المجموعة'];
        }

        $wasActive = $enrollment['status'] === 'active';

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

        if ($wasActive) {
            $group = $db->selectOne("SELECT current_count FROM sa_groups WHERE id = ?", [$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]);

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

        return ['success' => true, 'new_count' => null];
    }

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

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

        $db->update('sa_group_players', [
            '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 = ?", [(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']]);

        return true;
    }

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

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

        $db->update('sa_group_players', [
            '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 = ?", [(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']]);

        return true;
    }
}
