<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

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 = 'active'",
            [$groupId, $playerId]
        );
        if ($existing) {
            return ['success' => false, 'error' => 'اللاعب مسجل بالفعل في هذه المجموعة'];
        }

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

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

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

        $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 = ?', [$groupId]);

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

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

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

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

        $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']]);

        $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];
    }
}
