<?php
declare(strict_types=1);

namespace App\Modules\TrainingGroups\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\TrainingGroups\Services\WaitingListService;

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

        $filters = [
            'status'        => trim((string) $request->get('status', '')),
            'discipline_id' => trim((string) $request->get('discipline_id', '')),
            'q'             => trim((string) $request->get('q', '')),
        ];

        $where = ['1=1'];
        $params = [];

        if (!empty($filters['status'])) {
            $where[] = 'wl.status = ?';
            $params[] = $filters['status'];
        }

        if (!empty($filters['discipline_id'])) {
            $where[] = 'wl.discipline_id = ?';
            $params[] = (int) $filters['discipline_id'];
        }

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where[] = '(p.full_name_ar LIKE ? OR p.phone LIKE ?)';
            $params[] = $search;
            $params[] = $search;
        }

        $whereClause = implode(' AND ', $where);

        $page = max(1, (int) $request->get('page', 1));
        $perPage = 25;

        $countResult = $db->selectOne(
            "SELECT COUNT(*) AS total FROM waiting_list wl LEFT JOIN players p ON p.id = wl.player_id WHERE {$whereClause}",
            $params
        );
        $total = (int) ($countResult['total'] ?? 0);
        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        $entries = $db->select(
            "SELECT wl.*, p.full_name_ar AS player_name, p.phone AS player_phone,
                    sd.name_ar AS discipline_name, al.name_ar AS level_name,
                    tg.name_ar AS offered_group_name
             FROM waiting_list wl
             LEFT JOIN players p ON p.id = wl.player_id
             LEFT JOIN sport_disciplines sd ON sd.id = wl.discipline_id
             LEFT JOIN academy_levels al ON al.id = wl.level_id
             LEFT JOIN training_groups tg ON tg.id = wl.offered_group_id
             WHERE {$whereClause}
             ORDER BY wl.priority ASC, wl.created_at ASC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        $disciplines = $db->select(
            "SELECT id, name_ar FROM sport_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        // Get available groups for offering
        $availableGroups = $db->select(
            "SELECT id, name_ar FROM training_groups WHERE is_active = 1 AND is_full = 0 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        return $this->view('TrainingGroups.Views.waiting_list', [
            'entries'         => $entries,
            'filters'         => $filters,
            'disciplines'     => $disciplines,
            'availableGroups' => $availableGroups,
            'pagination'      => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => $lastPage,
            ],
        ]);
    }

    public function offer(Request $request, string $id): Response
    {
        $groupId = (int) $request->post('group_id', 0);
        if ($groupId <= 0) {
            return $this->redirect('/waiting-list')->withError('يجب اختيار مجموعة');
        }

        WaitingListService::offerSpot((int) $id, $groupId);

        return $this->redirect('/waiting-list')->withSuccess('تم عرض المقعد على اللاعب');
    }

    public function cancel(Request $request, string $id): Response
    {
        WaitingListService::cancel((int) $id);

        return $this->redirect('/waiting-list')->withSuccess('تم إلغاء طلب الانتظار');
    }
}
