<?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\TournamentMatch;
use App\Modules\Tournaments\Models\TournamentParticipant;
use App\Modules\Tournaments\Services\TournamentService;

class MatchController extends Controller
{
    /**
     * List matches for a tournament.
     */
    public function index(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);
        }

        $matches = TournamentMatch::getForTournament($tournamentId);

        // Group by round
        $rounds = [];
        foreach ($matches as $match) {
            $round = (int) $match['round_number'];
            $rounds[$round][] = $match;
        }

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

    /**
     * Record match result.
     */
    public function recordResult(Request $request, int $matchId): Response
    {
        $this->authorize('tournament.record_results');

        $data = $this->validated($_POST, [
            'score_a'               => 'nullable',
            'score_b'               => 'nullable',
            'winner_participant_id' => 'nullable|numeric',
            'is_draw'               => 'nullable',
            'referee_name'          => 'nullable',
            'match_notes'           => 'nullable',
        ]);

        $data['is_draw'] = isset($_POST['is_draw']) ? 1 : 0;

        try {
            TournamentService::recordMatchResult($matchId, $data);

            // Redirect back to tournament
            $db = App::getInstance()->db();
            $match = $db->selectOne("SELECT tournament_id FROM tournament_matches WHERE id = ?", [$matchId]);
            $tournamentId = (int) ($match['tournament_id'] ?? 0);

            return $this->redirect('/tournaments/' . $tournamentId)->withSuccess('تم تسجيل نتيجة المباراة بنجاح');
        } catch (\Throwable $e) {
            return $this->back()->withError('خطأ: ' . $e->getMessage());
        }
    }

    /**
     * Show match result form.
     */
    public function showResultForm(Request $request, int $matchId): Response
    {
        $this->authorize('tournament.record_results');

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

        $match = $db->selectOne(
            "SELECT tm.*,
                    COALESCE(pa.team_name, pla.full_name_ar) AS participant_a_name,
                    COALESCE(pb.team_name, plb.full_name_ar) AS participant_b_name,
                    t.name_ar AS tournament_name, t.format AS tournament_format
             FROM tournament_matches tm
             LEFT JOIN tournament_participants pa ON pa.id = tm.participant_a_id
             LEFT JOIN players pla ON pla.id = pa.player_id
             LEFT JOIN tournament_participants pb ON pb.id = tm.participant_b_id
             LEFT JOIN players plb ON plb.id = pb.player_id
             LEFT JOIN tournaments t ON t.id = tm.tournament_id
             WHERE tm.id = ?",
            [$matchId]
        );

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

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

    /**
     * Reschedule a match.
     */
    public function reschedule(Request $request, int $matchId): Response
    {
        $this->authorize('tournament.manage');

        $data = $this->validated($_POST, [
            'scheduled_date' => 'required',
            'scheduled_time' => 'nullable',
            'facility_id'    => 'nullable|numeric',
        ]);

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

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

        $db->update('tournament_matches', [
            'scheduled_date' => $data['scheduled_date'],
            'scheduled_time' => $data['scheduled_time'] ?? null,
            'facility_id'    => !empty($data['facility_id']) ? (int) $data['facility_id'] : null,
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id = ?', [$matchId]);

        return $this->redirect('/tournaments/' . $match['tournament_id'])->withSuccess('تم إعادة جدولة المباراة');
    }
}
