<?php
declare(strict_types=1);

namespace App\Modules\MatchCenter\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\MatchCenter\Models\LiveMatch;
use App\Modules\MatchCenter\Models\MatchEvent;

class MatchCenterController extends Controller
{
    /**
     * Dashboard: show all matches grouped by status (live first, then scheduled, then finished).
     */
    public function dashboard(Request $request): Response
    {
        $matches = LiveMatch::getDashboardMatches();

        return $this->view('MatchCenter.Views.dashboard', [
            'liveMatches'      => $matches['live'],
            'scheduledMatches' => $matches['scheduled'],
            'finishedMatches'  => $matches['finished'],
        ]);
    }

    /**
     * Show the form to create/schedule a new match.
     */
    public function create(Request $request): Response
    {
        return $this->view('MatchCenter.Views.create');
    }

    /**
     * Validate and store a new match.
     */
    public function store(Request $request): Response
    {
        $matchTitleAr = trim((string) $request->post('match_title_ar', ''));
        $teamAName    = trim((string) $request->post('team_a_name', ''));
        $teamBName    = trim((string) $request->post('team_b_name', ''));
        $matchDate    = trim((string) $request->post('match_date', ''));
        $startTime    = trim((string) $request->post('start_time', ''));
        $refereeName  = trim((string) $request->post('referee_name', ''));
        $notes        = trim((string) $request->post('notes', ''));

        // Validation
        $errors = [];
        if ($matchTitleAr === '') {
            $errors[] = 'عنوان المباراة مطلوب';
        }
        if ($teamAName === '') {
            $errors[] = 'اسم الفريق الأول مطلوب';
        }
        if ($teamBName === '') {
            $errors[] = 'اسم الفريق الثاني مطلوب';
        }
        if ($matchDate === '') {
            $errors[] = 'تاريخ المباراة مطلوب';
        }
        if ($startTime === '') {
            $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('/match-center/create');
        }

        $employee = App::getInstance()->currentEmployee();

        $match = LiveMatch::create([
            'match_title_ar'    => $matchTitleAr,
            'team_a_name'       => $teamAName,
            'team_b_name'       => $teamBName,
            'match_date'        => $matchDate,
            'start_time'        => $startTime,
            'referee_name'      => $refereeName ?: null,
            'notes'             => $notes ?: null,
            'status'            => 'scheduled',
            'score_a'           => 0,
            'score_b'           => 0,
            'entry_employee_id' => $employee ? ($employee->id ?? ($employee['id'] ?? null)) : null,
        ]);

        return $this->redirect('/match-center/' . $match->id)->withSuccess('تم جدولة المباراة بنجاح');
    }

    /**
     * Display match details with timeline of events.
     */
    public function show(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        $events = MatchEvent::getByMatch((int) $id);

        return $this->view('MatchCenter.Views.show', [
            'match'      => $match,
            'events'     => $events,
            'eventTypes' => MatchEvent::getEventTypeLabels(),
        ]);
    }

    /**
     * Start a match: set status to live.
     */
    public function startMatch(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        if ($match->status !== 'scheduled') {
            return $this->redirect('/match-center/' . $id)->withError('لا يمكن بدء مباراة غير مجدولة');
        }

        $match->update([
            'status'     => 'live',
            'started_at' => date('Y-m-d H:i:s'),
        ]);

        return $this->redirect('/match-center/' . $id)->withSuccess('تم بدء المباراة');
    }

    /**
     * End a match: set status to finished.
     */
    public function endMatch(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        if ($match->status !== 'live') {
            return $this->redirect('/match-center/' . $id)->withError('لا يمكن إنهاء مباراة غير جارية');
        }

        $match->update([
            'status'      => 'finished',
            'finished_at' => date('Y-m-d H:i:s'),
        ]);

        return $this->redirect('/match-center/' . $id)->withSuccess('تم إنهاء المباراة');
    }

    /**
     * Live entry interface for pitch-side employees.
     */
    public function liveEntry(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        $events = MatchEvent::getByMatch((int) $id);

        return $this->view('MatchCenter.Views.live_entry', [
            'match'      => $match,
            'events'     => $events,
            'eventTypes' => MatchEvent::getEventTypeLabels(),
        ]);
    }

    /**
     * Add an event to a match. If it's a goal, also increment the score.
     */
    public function addEvent(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        $minute      = (int) $request->post('minute', 0);
        $eventType   = trim((string) $request->post('event_type', ''));
        $team        = trim((string) $request->post('team', ''));
        $playerName  = trim((string) $request->post('player_name', ''));
        $descriptionAr = trim((string) $request->post('description_ar', ''));

        // Validation
        $validTypes = array_keys(MatchEvent::getEventTypeLabels());
        if (!in_array($eventType, $validTypes, true)) {
            return $this->redirect('/match-center/' . $id . '/live')->withError('نوع الحدث غير صالح');
        }

        $teamValue = null;
        if (in_array($team, ['a', 'b'], true)) {
            $teamValue = $team;
        }

        MatchEvent::create([
            'match_id'       => (int) $id,
            'minute'         => $minute,
            'event_type'     => $eventType,
            'team'           => $teamValue,
            'player_name'    => $playerName ?: null,
            'description_ar' => $descriptionAr ?: null,
        ]);

        // If it's a goal, increment the appropriate team's score
        if ($eventType === 'goal' && $teamValue !== null) {
            $db = App::getInstance()->db();
            $scoreField = $teamValue === 'a' ? 'score_a' : 'score_b';
            $db->query(
                "UPDATE live_matches SET {$scoreField} = {$scoreField} + 1, updated_at = NOW() WHERE id = ?",
                [(int) $id]
            );
        }

        return $this->redirect('/match-center/' . $id . '/live')->withSuccess('تم إضافة الحدث');
    }

    /**
     * Directly update the score of a match.
     */
    public function updateScore(Request $request, string $id): Response
    {
        $match = LiveMatch::find((int) $id);
        if (!$match) {
            return $this->redirect('/match-center')->withError('المباراة غير موجودة');
        }

        $scoreA = max(0, (int) $request->post('score_a', 0));
        $scoreB = max(0, (int) $request->post('score_b', 0));

        $match->update([
            'score_a' => $scoreA,
            'score_b' => $scoreB,
        ]);

        return $this->redirect('/match-center/' . $id . '/live')->withSuccess('تم تحديث النتيجة');
    }
}
