<?php
declare(strict_types=1);

namespace App\Modules\Tournaments\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Tournaments\Models\TournamentParticipant;
use App\Modules\Tournaments\Services\TournamentService;

class ParticipantController extends Controller
{
    /**
     * Register a player in a tournament.
     */
    public function register(Request $request, int $tournamentId): Response
    {
        $this->authorize('tournament.register_players');

        $data = $this->validated($_POST, [
            'player_id' => 'required|numeric',
            'team_name' => 'nullable',
        ]);

        $teamData = null;
        if (!empty($data['team_name'])) {
            $teamData = [
                'team_name'         => $data['team_name'],
                'team_members_json' => null,
            ];
        }

        try {
            TournamentService::registerParticipant($tournamentId, (int) $data['player_id'], $teamData);
            return $this->redirect('/tournaments/' . $tournamentId)->withSuccess('تم تسجيل اللاعب في البطولة بنجاح');
        } catch (\Throwable $e) {
            return $this->back()->withError($e->getMessage());
        }
    }

    /**
     * Withdraw a participant from a tournament.
     */
    public function withdraw(Request $request, int $tournamentId, int $participantId): Response
    {
        $this->authorize('tournament.register_players');

        $db = App::getInstance()->db();

        $participant = $db->selectOne(
            "SELECT * FROM tournament_participants WHERE id = ? AND tournament_id = ?",
            [$participantId, $tournamentId]
        );

        if (!$participant) {
            throw new \RuntimeException('المشارك غير موجود', 404);
        }

        if (in_array($participant['status'], ['withdrawn', 'disqualified'], true)) {
            return $this->back()->withError('المشارك منسحب بالفعل');
        }

        $db->update('tournament_participants', [
            'status' => 'withdrawn',
        ], 'id = ?', [$participantId]);

        return $this->redirect('/tournaments/' . $tournamentId)->withSuccess('تم تسجيل انسحاب المشارك');
    }

    /**
     * Show standings for a tournament.
     */
    public function standings(Request $request, int $tournamentId): Response
    {
        $this->authorize('tournament.view');

        $db = App::getInstance()->db();

        $tournament = $db->selectOne("SELECT * FROM tournaments WHERE id = ?", [$tournamentId]);
        if (!$tournament) {
            throw new \RuntimeException('البطولة غير موجودة', 404);
        }

        $standings = TournamentParticipant::getStandings($tournamentId);

        return $this->view('Tournaments.Views.standings', [
            'tournament' => $tournament,
            'standings'  => $standings,
        ]);
    }
}
