<?php
declare(strict_types=1);

namespace App\Modules\Disciplines\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Disciplines\Models\GroupWaitlist;
use App\Modules\Disciplines\Services\WaitlistService;

class WaitlistController extends Controller
{
    /**
     * List all waitlist entries with optional group filter.
     */
    public function index(Request $request): Response
    {
        $this->authorize('waitlist.view');

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

        $page = max(1, (int) $request->get('page', 1));
        $result = GroupWaitlist::search($filters, 25, $page);

        // Fetch groups for filter dropdown
        $db = App::getInstance()->db();
        $groups = $db->select("SELECT id, name_ar FROM training_groups WHERE is_archived = 0 ORDER BY name_ar ASC", []);

        return $this->view('Disciplines.Views.waitlist', [
            'entries'    => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'groups'     => $groups,
        ]);
    }

    /**
     * Show form to add a player to a group's waitlist.
     */
    public function addPlayer(Request $request): Response
    {
        $this->authorize('waitlist.manage');

        $db = App::getInstance()->db();
        $groups = $db->select("SELECT id, name_ar FROM training_groups WHERE is_archived = 0 ORDER BY name_ar ASC", []);
        $preselectedGroup = (int) $request->get('group_id', 0);

        return $this->view('Disciplines.Views.waitlist_add', [
            'groups'           => $groups,
            'preselectedGroup' => $preselectedGroup,
        ]);
    }

    /**
     * Store a new waitlist entry.
     */
    public function store(Request $request): Response
    {
        $this->authorize('waitlist.manage');

        $groupId = (int) $request->post('group_id', 0);
        $playerId = (int) $request->post('player_id', 0);
        $notes = trim((string) $request->post('notes', ''));

        // Validation
        $errors = [];
        if ($groupId <= 0) {
            $errors[] = 'يرجى اختيار المجموعة';
        }
        if ($playerId <= 0) {
            $errors[] = 'يرجى اختيار اللاعب';
        }

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $request->all());
            return $this->redirect('/waitlist/add');
        }

        $result = WaitlistService::addToWaitlist($groupId, $playerId, $notes);

        if ($result['success']) {
            return $this->redirect('/waitlist?group_id=' . $groupId)->withSuccess($result['message']);
        }

        return $this->redirect('/waitlist/add?group_id=' . $groupId)->withError($result['message']);
    }

    /**
     * Offer a spot to a waitlisted player.
     */
    public function offerSpot(Request $request, string $id): Response
    {
        $this->authorize('waitlist.manage');

        $result = WaitlistService::offerSpot((int) $id);

        if ($result['success']) {
            return $this->back()->withSuccess($result['message']);
        }

        return $this->back()->withError($result['message']);
    }

    /**
     * Accept an offered spot.
     */
    public function acceptOffer(Request $request, string $id): Response
    {
        $this->authorize('waitlist.manage');

        $result = WaitlistService::acceptOffer((int) $id);

        if ($result['success']) {
            return $this->back()->withSuccess($result['message']);
        }

        return $this->back()->withError($result['message']);
    }

    /**
     * Remove a player from the waitlist.
     */
    public function remove(Request $request, string $id): Response
    {
        $this->authorize('waitlist.manage');

        $result = WaitlistService::removeFromWaitlist((int) $id);

        if ($result['success']) {
            return $this->back()->withSuccess($result['message']);
        }

        return $this->back()->withError($result['message']);
    }
}
