<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Services\EnrollmentService;

class PlayerAssignmentController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $disciplineId = trim((string) $request->get('discipline_id', ''));
        $status = trim((string) $request->get('status', 'unassigned'));

        $disciplines = $db->select(
            "SELECT id, name_ar, code FROM sa_disciplines WHERE is_archived = 0 ORDER BY name_ar"
        );

        $where = "pl.is_archived = 0";
        $params = [];

        if ($status === 'unassigned') {
            if ($disciplineId !== '') {
                $where .= " AND NOT EXISTS (
                    SELECT 1 FROM sa_group_players gp
                    INNER JOIN sa_groups g ON g.id = gp.group_id
                    INNER JOIN sa_programs p ON p.id = g.program_id
                    WHERE p.discipline_id = ? AND gp.player_id = pl.id AND gp.status IN ('active','pending_payment')
                )";
                $params[] = (int) $disciplineId;
            } else {
                $where .= " AND NOT EXISTS (
                    SELECT 1 FROM sa_group_players gp
                    WHERE gp.player_id = pl.id AND gp.status IN ('active','pending_payment')
                )";
            }
        }

        $players = $db->select("
            SELECT pl.id, pl.full_name_ar, pl.date_of_birth, pl.gender, pl.phone,
                   pl.medical_status, pl.medical_expiry_date, pl.photo_path, pl.player_type,
                   pl.created_at,
                   (SELECT GROUP_CONCAT(g.name_ar SEPARATOR ', ')
                    FROM sa_group_players gp
                    INNER JOIN sa_groups g ON g.id = gp.group_id
                    WHERE gp.player_id = pl.id AND gp.status IN ('active','pending_payment')
                   ) as current_groups
            FROM sa_players pl
            WHERE {$where}
            ORDER BY pl.full_name_ar ASC
            LIMIT 200
        ", $params);

        return $this->view('SportsActivity.Views.assignments.index', [
            'players'      => $players,
            'disciplines'  => $disciplines,
            'filters'      => ['discipline_id' => $disciplineId, 'status' => $status],
        ]);
    }

    public function show(Request $request, string $playerId): Response
    {
        $db = App::getInstance()->db();

        $player = $db->selectOne("SELECT * FROM sa_players WHERE id = ? AND is_archived = 0", [(int) $playerId]);
        if (!$player) {
            return $this->redirect('/sa/assignments')->withError('اللاعب غير موجود');
        }

        $disciplineId = trim((string) $request->get('discipline_id', ''));

        $groupWhere = "g.status = 'active' AND g.is_archived = 0";
        $groupParams = [];

        if ($disciplineId !== '') {
            $groupWhere .= " AND p.discipline_id = ?";
            $groupParams[] = (int) $disciplineId;
        }

        $groups = $db->select("
            SELECT g.id, g.name_ar, g.current_count, g.max_capacity, g.min_age, g.max_age,
                   p.name_ar as program_name, p.monthly_fee_member, p.monthly_fee_nonmember,
                   d.name_ar as discipline_name,
                   c.full_name_ar as coach_name
            FROM sa_groups g
            JOIN sa_programs p ON p.id = g.program_id
            JOIN sa_disciplines d ON d.id = p.discipline_id
            LEFT JOIN sa_coaches c ON c.id = g.coach_id
            WHERE {$groupWhere}
            ORDER BY d.name_ar, p.name_ar, g.name_ar
        ", $groupParams);

        $currentEnrollments = $db->select("
            SELECT gp.*, g.name_ar as group_name, p.name_ar as program_name
            FROM sa_group_players gp
            JOIN sa_groups g ON g.id = gp.group_id
            JOIN sa_programs p ON p.id = g.program_id
            WHERE gp.player_id = ? AND gp.status IN ('active','pending_payment')
            ORDER BY gp.enrolled_at DESC
        ", [(int) $playerId]);

        return $this->view('SportsActivity.Views.assignments.show', [
            'player'             => $player,
            'groups'             => $groups,
            'currentEnrollments' => $currentEnrollments,
            'filters'            => ['discipline_id' => $disciplineId],
        ]);
    }

    public function assign(Request $request, string $playerId): Response
    {
        $groupId = (int) $request->post('group_id', 0);
        $force = (bool) $request->post('force', false);

        if (!$groupId) {
            return $this->redirect('/sa/assignments/' . $playerId)->withError('يجب اختيار مجموعة');
        }

        if ($force) {
            $result = EnrollmentService::forceEnroll($groupId, (int) $playerId);
        } else {
            $result = EnrollmentService::enroll($groupId, (int) $playerId);
        }

        if (!$result['success']) {
            return $this->redirect('/sa/assignments/' . $playerId)->withError($result['error']);
        }

        $msg = 'تم تسجيل اللاعب بنجاح';
        if (!empty($result['medical_warning'])) {
            $msg .= ' — ' . $result['medical_warning'];
        }
        if (!empty($result['request_number'])) {
            $msg .= ' — رقم الطلب: ' . $result['request_number'];
        }

        return $this->redirect('/sa/assignments/' . $playerId)->withSuccess($msg);
    }
}
