<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\EventBus;
use App\Core\Exceptions\ValidationException;

final class EnrollmentController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function enroll(Request $request, string $id): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();
        $groupId = (int) $id;

        $group = $db->selectOne(
            "SELECT * FROM training_groups WHERE id = ? AND is_active = 1 AND is_archived = 0",
            [$groupId]
        );

        if (!$group) {
            return $this->errorResponse('المجموعة غير موجودة', 404);
        }

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

        if ($existing) {
            return $this->errorResponse('أنت مسجل بالفعل في هذه المجموعة', 422);
        }

        if ($group['is_full'] || (int) $group['current_count'] >= (int) $group['max_capacity']) {
            $db->insert('waiting_list', [
                'player_id' => $player->id,
                'discipline_id' => $group['discipline_id'],
                'level_id' => $group['level_id'],
                'preferred_day_of_week' => $group['day_of_week'],
                'preferred_time' => $group['start_time'],
                'requested_group_type' => $group['group_type'],
                'status' => 'pending',
                'priority' => 10,
            ]);

            return $this->successResponse([
                'status' => 'waiting_list',
                'message' => 'المجموعة ممتلئة، تم إضافتك لقائمة الانتظار',
            ], 201);
        }

        $db->insert('group_memberships', [
            'player_id' => $player->id,
            'group_id' => $groupId,
            'status' => 'active',
            'joined_at' => date('Y-m-d H:i:s'),
        ]);

        $db->query(
            "UPDATE training_groups SET current_count = current_count + 1, is_full = (current_count + 1 >= max_capacity) WHERE id = ?",
            [$groupId]
        );

        EventBus::dispatch('player.enrolled', [
            'player_id' => (int) $player->id,
            'group_id' => $groupId,
            'group_name' => $group['name_ar'],
        ]);

        return $this->successResponse([
            'status' => 'enrolled',
            'group_id' => $groupId,
            'message' => 'تم التسجيل بنجاح',
        ], 201);
    }

    public function myEnrollments(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $enrollments = $db->select(
            "SELECT gm.id, gm.status, gm.joined_at,
                    tg.name_ar as group_name, tg.group_type, tg.day_of_week, tg.start_time, tg.end_time,
                    c.name_ar as coach_name,
                    f.name_ar as facility_name,
                    sd.name_ar as discipline_name
             FROM group_memberships gm
             INNER JOIN training_groups tg ON tg.id = gm.group_id
             LEFT JOIN coaches c ON c.id = tg.coach_id
             LEFT JOIN facilities f ON f.id = tg.facility_id
             LEFT JOIN sport_disciplines sd ON sd.id = tg.discipline_id
             WHERE gm.player_id = ? AND gm.status = 'active'
             ORDER BY tg.day_of_week, tg.start_time",
            [$player->id]
        );

        return $this->successResponse($enrollments);
    }

    public function myEvaluations(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $evaluations = $db->select(
            "SELECT pe.id, pe.skill_level, pe.scores_json, pe.strengths_ar, pe.weaknesses_ar,
                    pe.status, pe.created_at,
                    sd.name_ar as discipline_name,
                    c.name_ar as evaluator_name
             FROM player_evaluations pe
             LEFT JOIN sport_disciplines sd ON sd.id = pe.discipline_id
             LEFT JOIN coaches c ON c.id = pe.evaluator_coach_id
             WHERE pe.player_id = ? AND pe.status = 'approved'
             ORDER BY pe.created_at DESC",
            [$player->id]
        );

        return $this->successResponse($evaluations);
    }
}
