<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'commissioner') {
    header('Location: login.php');
    exit();
}
$commissioner_id = $_SESSION['user_id'];

$fixture_id = filter_input(INPUT_GET, 'fixture_id', FILTER_VALIDATE_INT);
if (!$fixture_id) {
    // If no fixture is selected, redirect to the selection page.
    header('Location: commissioner_matches.php');
    exit();
}

// --- Instantiate Models and Fetch Data ---
$fixtureModel = new Fixture();
$lineupModel = new Lineup();
$eventModel = new MatchEvent();
$playerModel = new Player();
$teamModel = new Team();

$fixture = $fixtureModel->findById($fixture_id);

// Security check: Ensure the logged-in commissioner is assigned to this fixture.
if (!$fixture || $fixture->commissioner_id != $commissioner_id) {
    header('Location: commissioner_matches.php?error=not_assigned');
    exit();
}

$pageTitle = 'Live Scorer';
include 'includes/header.php';

// Fetch system settings
// $settings is already fetched in includes/header.php

// Fetch lineups and recent events
$home_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->home_team_id);
$away_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->away_team_id);

// Fetch recent events with player_id explicitly
$db = new Database();
$db->query("SELECT * FROM match_events WHERE fixture_id = :fixture_id ORDER BY minute DESC");
$db->bind(':fixture_id', $fixture_id);
$recent_events = $db->resultSet();

$player_names = $playerModel->getPlayerNamesForFixture($fixture_id);

// Fetch player details for squad number and position
$player_details_raw = $playerModel->getPlayerDetailsForFixture($fixture_id);
$players_js_data = [];
foreach ($player_details_raw as $pid => $p) {
    $pos_map = ['Goalkeeper' => 'GK', 'Defender' => 'DEF', 'Midfielder' => 'MID', 'Forward' => 'FWD'];
    $short_pos = $pos_map[$p->position] ?? substr($p->position, 0, 3);
    $players_js_data[$pid] = [
        'name' => $p->first_name . ' ' . $p->last_name,
        'number' => $p->squad_number ?? '',
        'pos' => strtoupper($short_pos)
    ];
}

// Separate starters and subs for the new UI
$home_starters = array_intersect_key($player_names, $home_lineup->starters);
$home_subs = array_intersect_key($player_names, array_flip($home_lineup->substitutes ?? []));
$away_starters = array_intersect_key($player_names, $away_lineup->starters);
$away_subs = array_intersect_key($player_names, array_flip($away_lineup->substitutes ?? []));

// Get timer settings with defaults
$full_time_duration = (int)($settings['full_time_duration'] ?? 90);
$half_time_duration = (int)($settings['half_time_duration'] ?? 15);
$half_time_mark = (int)($full_time_duration / 2);

// --- Use DB Elapsed Time ---
$elapsed_1st = max(0, (int)($fixture->elapsed_1st ?? 0));
$elapsed_2nd = max(0, (int)($fixture->elapsed_2nd ?? 0));
$elapsed_half_time = max(0, (int)($fixture->elapsed_half_time ?? 0));

// --- Calculate players currently on the pitch ---
$home_players_on_pitch_ids = array_keys($home_lineup->starters ?? []);
$away_players_on_pitch_ids = array_keys($away_lineup->starters ?? []);

foreach ($recent_events as $event) {
    if ($event->event_type === 'substitution') {
        $player_off_id = $event->player_id;
        $player_on_id = $event->assisted_by_player_id;

        // Determine which team the event belongs to
        if (in_array($player_off_id, $home_players_on_pitch_ids)) {
            $home_players_on_pitch_ids = array_diff($home_players_on_pitch_ids, [$player_off_id]);
            $home_players_on_pitch_ids[] = $player_on_id;
        } elseif (in_array($player_off_id, $away_players_on_pitch_ids)) {
            $away_players_on_pitch_ids = array_diff($away_players_on_pitch_ids, [$player_off_id]);
            $away_players_on_pitch_ids[] = $player_on_id;
        }
    }
}

// --- Check Referee Fee Payment Status ---
$fees_paid = true;
$unpaid_teams = [];
if (!$fixture->home_team_paid_referee && ($fixture->referee_payment_status ?? '') !== 'paid') {
    $fees_paid = false;
    $unpaid_teams[] = $fixture->home_team_name;
}
if (!$fixture->away_team_paid_referee && ($fixture->referee_payment_status ?? '') !== 'paid') {
    $fees_paid = false;
    $unpaid_teams[] = $fixture->away_team_name;
}

?>

    <!-- New Match Hero Section -->
    <div class="match-hero">
        <div class="hero-team home">
            <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->home_team_name); ?>" class="hero-logo">
            <span class="hero-team-name"><?php echo htmlspecialchars($fixture->home_team_name); ?></span>
        </div>
        <div class="hero-score">
            <div class="score" id="score-display"><?php echo $fixture->home_team_score ?? '0'; ?> - <?php echo $fixture->away_team_score ?? '0'; ?></div>
            <div class="match-status">
                <span id="timer-display">00:00</span>
                <span id="added-time-display" style="display: none;"></span>
            </div>
        </div>
        <div class="hero-team away">
            <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="<?php echo htmlspecialchars($fixture->away_team_name); ?>" class="hero-logo">
            <span class="hero-team-name"><?php echo htmlspecialchars($fixture->away_team_name); ?></span>
        </div>
    </div>

<div class="page-content live-scorer-page" 
    data-fixture-id="<?php echo $fixture_id; ?>"
    data-first-half-start="<?php echo $fixture->first_half_start_time; ?>"
    data-first-half-end="<?php echo $fixture->first_half_end_time; ?>"
    data-second-half-start="<?php echo $fixture->second_half_start_time; ?>"
    data-second-half-end="<?php echo $fixture->second_half_end_time; ?>"
    data-elapsed-first="<?php echo $elapsed_1st; ?>"
    data-elapsed-second="<?php echo $elapsed_2nd; ?>"
    data-elapsed-half-time="<?php echo $elapsed_half_time; ?>"
    data-status="<?php echo $fixture->status; ?>">
    <div class="matches-header">
        <h1>Live Scorer: Gameweek <?php echo htmlspecialchars($fixture->gameweek); ?></h1>
    </div>
    <div class="live-scoreboard" style="margin-bottom: 2rem;">
        <div id="half-time-countdown-container" style="display: none; text-align: center; margin-bottom: 1rem;">
            <span class="countdown-label">Second half starts in:</span> <span id="half-time-countdown">15:00</span>
        </div>
        <div class="timer-controls">
            <?php if ($fees_paid): ?>
                <form action="live_scorer_process.php" method="POST" style="display: none;" id="form-start-match"><input type="hidden" name="fixture_id" value="<?php echo $fixture_id; ?>"><input type="hidden" name="action" value="start_match"><button type="button" onclick="confirmAction('start the first half', 'form-start-match')" id="start-first-half-btn" class="btn">Start 1st Half</button></form>
            <?php else: ?>
                <div class="alert alert-danger" style="display: none; padding: 10px; background: #f8d7da; color: #721c24; border-radius: 5px;" id="unpaid-fees-alert">
                    <i class="fa-solid fa-triangle-exclamation"></i> Cannot start match. Referee fees unpaid by: <strong><?php echo implode(', ', $unpaid_teams); ?></strong>
                </div>
            <?php endif; ?> 
            <form action="live_scorer_process.php" method="POST" style="display: none;" id="form-end-first-half"><input type="hidden" name="fixture_id" value="<?php echo $fixture_id; ?>"><input type="hidden" name="action" value="end_first_half"><button type="button" onclick="confirmAction('end the first half', 'form-end-first-half')" id="end-half-btn" class="btn btn-secondary">End 1st Half</button></form>
            <form action="live_scorer_process.php" method="POST" style="display: none;" id="form-start-second-half"><input type="hidden" name="fixture_id" value="<?php echo $fixture_id; ?>"><input type="hidden" name="action" value="start_second_half"><button type="button" onclick="confirmAction('start the second half', 'form-start-second-half')" id="start-second-half-btn" class="btn">Start 2nd Half</button></form>
            <form action="live_scorer_process.php" method="POST" style="display: none;" id="form-end-second-half"><input type="hidden" name="fixture_id" value="<?php echo $fixture_id; ?>"><input type="hidden" name="action" value="endSecondHalf"><button type="button" onclick="confirmAction('end the second half', 'form-end-second-half')" id="end-second-half-btn" class="btn btn-secondary">End 2nd Half</button></form>
            <button type="button" id="end-match-btn" class="btn btn-danger" style="display: none;">End Match</button>
        </div>
    </div>

    <!-- New Side-by-Side Event Palette -->
    <div class="event-palette-grid">
        <!-- Home Team Events -->
        <div class="event-column home-events">
            <h3 class="team-title"><?php echo htmlspecialchars($fixture->home_team_name); ?></h3>
            <button class="event-btn event-goal" data-event="goal" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-futbol"></i><span>Goal</span></button>
            <button class="event-btn" data-event="shot_on_target" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-bullseye"></i><span>Shot on Target</span></button>
            <button class="event-btn" data-event="shot_off_target" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-crosshairs"></i><span>Shot off Target</span></button>
            <button class="event-btn" data-event="corner" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-regular fa-flag"></i><span>Corner</span></button>
            <button class="event-btn" data-event="foul" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-hand"></i><span>Foul</span></button>
            <button class="event-btn" data-event="offside" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-flag"></i><span>Offside</span></button>
            <button class="event-btn event-yellow" data-event="yellow_card" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-square"></i><span>Yellow Card</span></button>
            <button class="event-btn event-red" data-event="red_card" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-square"></i><span>Red Card</span></button>
            <button class="event-btn event-penalty" data-event="penalty" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-circle-dot"></i><span>Penalty</span></button>
            <button class="event-btn event-own-goal" data-event="own_goal" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-futbol"></i><span>Own Goal</span></button>
            <button class="event-btn event-sub" data-event="substitution" data-team-id="<?php echo $fixture->home_team_id; ?>"><i class="fa-solid fa-right-left"></i><span>Substitution</span></button>
        </div>

        <!-- Away Team Events -->
        <div class="event-column away-events">
            <h3 class="team-title"><?php echo htmlspecialchars($fixture->away_team_name); ?></h3>
            <button class="event-btn event-goal" data-event="goal" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-futbol"></i><span>Goal</span></button>
            <button class="event-btn" data-event="shot_on_target" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-bullseye"></i><span>Shot on Target</span></button>
            <button class="event-btn" data-event="shot_off_target" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-crosshairs"></i><span>Shot off Target</span></button>
            <button class="event-btn" data-event="corner" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-regular fa-flag"></i><span>Corner</span></button>
            <button class="event-btn" data-event="foul" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-hand"></i><span>Foul</span></button>
            <button class="event-btn" data-event="offside" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-flag"></i><span>Offside</span></button>
            <button class="event-btn event-yellow" data-event="yellow_card" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-square"></i><span>Yellow Card</span></button>
            <button class="event-btn event-red" data-event="red_card" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-square"></i><span>Red Card</span></button>
            <button class="event-btn event-penalty" data-event="penalty" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-circle-dot"></i><span>Penalty</span></button>
            <button class="event-btn event-own-goal" data-event="own_goal" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-futbol"></i><span>Own Goal</span></button>
            <button class="event-btn event-sub" data-event="substitution" data-team-id="<?php echo $fixture->away_team_id; ?>"><i class="fa-solid fa-right-left"></i><span>Substitution</span></button>
        </div>
    </div>

    <!-- Recent Events Log -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Live Event Feed</h2>
        <form action="live_scorer_process.php" method="POST" style="margin-bottom: 10px;" id="undo-event-form">
            <input type="hidden" name="fixture_id" value="<?php echo $fixture_id; ?>"><input type="hidden" name="action" value="undo_last_event"><button type="submit" id="undo-last-event-btn" class="btn btn-secondary btn-sm">Undo Last Event</button>
        </form>
        <div id="recent-events-log" class="event-log-container">
            <?php if (empty($recent_events)): ?>
                <p class="no-data-msg">No events logged yet.</p>
            <?php else: ?>
                <?php foreach ($recent_events as $event): ?>
                    <div class="event-log-item">
                        <?php
                        $displayMinute = $event->minute;
                        if ($event->minute > $full_time_duration) {
                            $displayMinute = "$full_time_duration+" . ($event->minute - $full_time_duration);
                        } elseif ($event->minute > $half_time_mark) {
                            // Check if event is 1st half stoppage (created before 2nd half start)
                            $isStoppage = false;
                            if (empty($fixture->second_half_start_time) || $fixture->second_half_start_time == '0000-00-00 00:00:00') {
                                $isStoppage = true;
                            } elseif ($event->created_at < $fixture->second_half_start_time) {
                                $isStoppage = true;
                            }
                            if ($isStoppage) $displayMinute = "$half_time_mark+" . ($event->minute - $half_time_mark);
                        }
                        ?>
                        <span class="minute"><?php echo $displayMinute; ?>'</span>
                        <span class="event-text" data-event-id="<?php echo $event->id; ?>">
                            <?php
                                $eventType = $event->event_type;
                                $playerName = htmlspecialchars($player_names[$event->player_id] ?? 'N/A');
                                
                                // Enhance player name with number and position if available
                                if (isset($players_js_data[$event->player_id])) {
                                    $p = $players_js_data[$event->player_id];
                                    $playerName = "<strong>#{$p['number']} {$p['name']}</strong> <small>({$p['pos']})</small>";
                                }

                                $icon = '<i class="fa-solid fa-circle" style="font-size: 0.5rem;"></i>';
                                switch ($eventType) {
                                    case 'goal': $icon = '<i class="fa-solid fa-futbol" style="color: #2ecc71;"></i>'; break;
                                    case 'penalty_scored': $icon = '<i class="fa-solid fa-futbol" style="color: #2ecc71;"></i>'; break;
                                    case 'penalty_missed': $icon = '<i class="fa-solid fa-circle-xmark" style="color: #e74c3c;"></i>'; break;
                                    case 'own_goal': $icon = '<i class="fa-solid fa-futbol" style="color: #e74c3c;"></i>'; break;
                                    case 'yellow_card': $icon = '<i class="fa-solid fa-square" style="color: #f1c40f;"></i>'; break;
                                    case 'red_card': $icon = '<i class="fa-solid fa-square" style="color: #e74c3c;"></i>'; break;
                                    case 'substitution': $icon = '<i class="fa-solid fa-right-left" style="color: #3498db;"></i>'; break;
                                    case 'corner': $icon = '<i class="fa-regular fa-flag" style="color: #34495e;"></i>'; break;
                                    case 'foul': $icon = '<i class="fa-solid fa-hand" style="color: #e67e22;"></i>'; break;
                                    case 'offside': $icon = '<i class="fa-solid fa-flag" style="color: #e74c3c;"></i>'; break;
                                    case 'shot_on_target': $icon = '<i class="fa-solid fa-bullseye" style="color: #2980b9;"></i>'; break;
                                    case 'shot_off_target': $icon = '<i class="fa-solid fa-crosshairs" style="color: #7f8c8d;"></i>'; break;
                                }

                                if ($eventType === 'goal' || $eventType === 'penalty_scored') {
                                    $assistText = '';
                                    if (!empty($event->assisted_by_player_id) && isset($player_names[$event->assisted_by_player_id])) {
                                        $assistName = htmlspecialchars($player_names[$event->assisted_by_player_id]);
                                        $assistText = " <span class='text-muted'>(Assist: {$assistName})</span>";
                                    }
                                    echo "{$icon} Goal! {$playerName}{$assistText}";
                                } elseif ($eventType === 'substitution') {
                                    $playerOnName = htmlspecialchars($player_names[$event->assisted_by_player_id] ?? 'N/A');
                                    if (isset($players_js_data[$event->assisted_by_player_id])) {
                                        $pOn = $players_js_data[$event->assisted_by_player_id];
                                        $playerOnName = "<strong>#{$pOn['number']} {$pOn['name']}</strong>";
                                    }
                                    echo "{$icon} Sub: <span style='color: #2ecc71;'>IN</span> {$playerOnName} <span style='color: #e74c3c;'>OUT</span> {$playerName}";
                                } else {
                                    $label = ucwords(str_replace('_', ' ', $eventType));
                                    echo "{$icon} {$label}" . ($playerName !== 'N/A' ? " - {$playerName}" : "");
                                }
                            ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Toast Notification Container -->
<div id="toast-container">
    <!-- Toasts will be injected here by JavaScript -->
</div>

<!-- Modal for secondary actions -->
<div id="event-modal" class="modal-overlay" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">Event Details</h3>
            <button id="modal-close-btn" class="modal-close-btn">&times;</button>
        </div>
        <form action="live_scorer_process.php" method="POST">
            <div class="modal-body" id="modal-body-content">
                <!-- Modal content injected by JS -->
            </div>
        </form>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmation-modal" class="modal-overlay" style="display: none;">
    <div class="modal-content" style="max-width: 400px; text-align: center;">
        <div class="modal-header" style="justify-content: center; border-bottom: none; padding-bottom: 0;">
            <h3>Confirm Action</h3>
        </div>
        <div class="modal-body">
            <p id="confirmation-text" style="margin-bottom: 20px; color: #666;">Are you sure?</p>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: center;">
                <button type="button" id="confirmation-cancel-btn" class="btn btn-secondary">Cancel</button>
                <button type="button" id="confirmation-confirm-btn" class="btn btn-danger">Confirm</button>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loading-overlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.7); z-index: 9999; align-items: center; justify-content: center;">
    <div class="spinner" style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite;"></div>
</div>
<style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const page = document.querySelector('.live-scorer-page');
    const fixtureId = parseInt(page.dataset.fixtureId);

    const homeLineup = <?php echo json_encode(array_merge(array_keys($home_lineup->starters ?? []), $home_lineup->substitutes ?? [])); ?>;
    const awayLineup = <?php echo json_encode(array_merge(array_keys($away_lineup->starters ?? []), $away_lineup->substitutes ?? [])); ?>;
    const playerNames = <?php echo json_encode($player_names); ?>;
    const playersData = <?php echo json_encode($players_js_data); ?>;
    const homePlayersOnPitch = <?php echo json_encode(array_values($home_players_on_pitch_ids)); ?>;
    const awayPlayersOnPitch = <?php echo json_encode(array_values($away_players_on_pitch_ids)); ?>;
    const homeManager = <?php echo json_encode(['id' => $fixture->home_manager_id, 'name' => $fixture->home_manager_name . ' (Manager)']); ?>;
    const awayManager = <?php echo json_encode(['id' => $fixture->away_manager_id, 'name' => $fixture->away_manager_name . ' (Manager)']); ?>;

    const FULL_TIME_DURATION = <?php echo $full_time_duration; ?> * 60; // in seconds
    const HALF_TIME_MARK = FULL_TIME_DURATION / 2;
    const HALF_TIME_DURATION = <?php echo $half_time_duration; ?> * 60; // in seconds

    const timerDisplay = document.getElementById('timer-display');
    const timerControlsContainer = document.querySelector('.timer-controls');
    const scoreDisplay = document.getElementById('score-display');
    const modal = document.getElementById('event-modal');
    const modalTitle = document.getElementById('modal-title');
    const modalBody = document.getElementById('modal-body-content');
    const modalForm = modal.querySelector('form');
    const modalCloseBtn = document.getElementById('modal-close-btn');
    const addedTimeDisplay = document.getElementById('added-time-display');
    const halfTimeCountdownContainer = document.getElementById('half-time-countdown-container');
    const halfTimeCountdownDisplay = document.getElementById('half-time-countdown');
    const loadingOverlay = document.getElementById('loading-overlay');

    let timerInterval = null;
    let timerBaseTimestamp = 0;
    let timerInitialElapsed = 0;
    let additionalMinutes = 0;
    let halfTimeStart = 0;
    let isPaused = false;

    // --- Confirmation Modal Logic ---
    const confirmationModal = document.getElementById('confirmation-modal');
    const confirmationText = document.getElementById('confirmation-text');
    const confirmBtn = document.getElementById('confirmation-confirm-btn');
    const cancelBtn = document.getElementById('confirmation-cancel-btn');
    let onConfirmCallback = null;

    function showConfirmation(text, callback) {
        confirmationText.textContent = text;
        onConfirmCallback = callback;
        confirmationModal.style.display = 'flex';
    }

    function closeConfirmation() {
        confirmationModal.style.display = 'none';
        onConfirmCallback = null;
    }

    if (confirmBtn) confirmBtn.addEventListener('click', () => {
        if (onConfirmCallback) onConfirmCallback();
        closeConfirmation();
    });
    if (cancelBtn) cancelBtn.addEventListener('click', closeConfirmation);
    if (confirmationModal) confirmationModal.addEventListener('click', (e) => { if (e.target === confirmationModal) closeConfirmation(); });

    // --- Confirmation for Timer Actions ---
    window.confirmAction = function(actionText, formId) {
        const text = `Are you sure you want to ${actionText}?`;
        showConfirmation(text, () => {
            const form = document.getElementById(formId);
            if (form) submitViaAjax(new FormData(form));
        });
    }

    // --- Toast Notification System ---
    const toastContainer = document.getElementById('toast-container');
    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

    // --- AJAX Submission Logic ---
    async function submitViaAjax(formData) {
        loadingOverlay.style.display = 'flex';
        
        try {
            const response = await fetch('live_scorer_process.php', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) throw new Error('Network response was not ok');
            
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            // Update Score
            const newScore = doc.getElementById('score-display');
            if (newScore && scoreDisplay) scoreDisplay.innerHTML = newScore.innerHTML;
            
            // Update Event Log
            const newLog = doc.getElementById('recent-events-log');
            const currentLog = document.getElementById('recent-events-log');
            if (newLog && currentLog) currentLog.innerHTML = newLog.innerHTML;
            
            // Update Timer Controls (buttons)
            const newControls = doc.querySelector('.timer-controls');
            const currentControls = document.querySelector('.timer-controls');
            if (newControls && currentControls) {
                currentControls.innerHTML = newControls.innerHTML;
                // Re-attach listener to new End Match button
                const newEndMatchBtn = document.getElementById('end-match-btn');
                if (newEndMatchBtn) {
                    newEndMatchBtn.addEventListener('click', showManOfTheMatchModal);
                }
            }

            // Update Page Data Attributes (Status, Times)
            const newPage = doc.querySelector('.live-scorer-page');
            if (newPage) {
                page.dataset.firstHalfStart = newPage.dataset.firstHalfStart;
                page.dataset.firstHalfEnd = newPage.dataset.firstHalfEnd;
                page.dataset.secondHalfStart = newPage.dataset.secondHalfStart;
                page.dataset.secondHalfEnd = newPage.dataset.secondHalfEnd;
                page.dataset.elapsedFirst = newPage.dataset.elapsedFirst;
                page.dataset.elapsedSecond = newPage.dataset.elapsedSecond;
                page.dataset.status = newPage.dataset.status;
            }

            initializeUIState();
            showToast('Update successful', 'success');
        } catch (error) {
            console.error('Error:', error);
            showToast('Failed to update. Please try again.', 'error');
        } finally {
            loadingOverlay.style.display = 'none';
            closeModal();
        }
    }

    // --- Timer Logic ---
    function formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    }

    function startTimer(initialElapsed, offsetMinutes = 0) {
        if (timerInterval) clearInterval(timerInterval);
        isPaused = false;
        
        timerBaseTimestamp = Date.now();
        timerInitialElapsed = initialElapsed;
        additionalMinutes = offsetMinutes;
        halfTimeStart = 0; // Reset half-time start

        timerInterval = setInterval(() => {
            const now = Date.now();
            const delta = Math.floor((now - timerBaseTimestamp) / 1000);
            // Total elapsed = (Offset Minutes * 60) + (Server Elapsed at Load) + (Client Delta)
            let displaySeconds = (additionalMinutes * 60) + initialElapsed + delta;

            // Handle stoppage time
            if (displaySeconds >= HALF_TIME_MARK && displaySeconds < FULL_TIME_DURATION && additionalMinutes < (FULL_TIME_DURATION / 60 / 2)) {
                timerDisplay.textContent = formatTime(HALF_TIME_MARK);
                const stoppageSeconds = displaySeconds - HALF_TIME_MARK;
                addedTimeDisplay.textContent = `+${formatTime(stoppageSeconds)}`;
                addedTimeDisplay.style.display = 'inline';
            } else if (displaySeconds >= FULL_TIME_DURATION) {
                timerDisplay.textContent = formatTime(FULL_TIME_DURATION);
                const stoppageSeconds = displaySeconds - FULL_TIME_DURATION;
                addedTimeDisplay.textContent = `+${formatTime(stoppageSeconds)}`;
                addedTimeDisplay.style.display = 'inline';
            } else {
                timerDisplay.textContent = formatTime(displaySeconds);
                addedTimeDisplay.style.display = 'none';
            }
        }, 1000);
    }

    function startHalfTimeCountdown() {
        halfTimeCountdownContainer.style.display = 'block';
        const initialElapsed = parseInt(page.dataset.elapsedHalfTime || 0);
        const localStartTimestamp = Date.now();

        const countdownInterval = setInterval(() => {
            const now = Date.now();
            const delta = Math.floor((now - localStartTimestamp) / 1000);
            const currentElapsed = initialElapsed + delta;
            const remaining = Math.max(0, HALF_TIME_DURATION - currentElapsed);
            
            halfTimeCountdownDisplay.textContent = formatTime(remaining);
            if (remaining <= 0) clearInterval(countdownInterval);
        }, 1000);
    }

    function stopTimer() {
        clearInterval(timerInterval);
        isPaused = true;
    }

    function getCurrentMinute() {
        if (!timerBaseTimestamp) {
            // Fallback if timer isn't running but we need a minute (e.g. half-time events)
            if (page.dataset.status === 'half_time') return 45;
            return 0;
        }
        const now = Date.now();
        const deltaSeconds = Math.floor((now - timerBaseTimestamp) / 1000);
        const totalSeconds = (additionalMinutes * 60) + timerInitialElapsed + deltaSeconds;
        return Math.floor(totalSeconds / 60) + 1;
    }

    function setEventButtonsDisabled(disabled) {
        document.querySelectorAll('.event-btn').forEach(btn => btn.disabled = disabled);
    }

    function initializeUIState() {
        // Clear any existing timer interval to prevent conflicts
        if (timerInterval) clearInterval(timerInterval);

        const initialSecondHalfStart = page.dataset.secondHalfStart;
        const initialFirstHalfStart = page.dataset.firstHalfStart;
        const initialFirstHalfEnd = page.dataset.firstHalfEnd;
        const initialSecondHalfEnd = page.dataset.secondHalfEnd;
        let status = page.dataset.status;

        // Fallback: If status is empty (due to DB ENUM error) or 'live' but 1st half ended, treat as half_time
        const isFirstHalfEnded = initialFirstHalfEnd && initialFirstHalfEnd !== '0000-00-00 00:00:00';
        const isSecondHalfStarted = initialSecondHalfStart && initialSecondHalfStart !== '0000-00-00 00:00:00';
        const isSecondHalfEnded = initialSecondHalfEnd && initialSecondHalfEnd !== '0000-00-00 00:00:00';
        
        if ((status === '' || status === 'live') && isFirstHalfEnded && !isSecondHalfStarted) {
            status = 'half_time';
        } else if ((status === '' || status === 'live') && isSecondHalfEnded) {
            // If 2nd half ended timestamp exists, force full_time status
            status = 'full_time';
        }

        // Hide all controls initially - this is now done in the HTML to prevent flicker

        setEventButtonsDisabled(true);
        
        if (status === 'scheduled') {
            timerDisplay.textContent = 'Scheduled';
            const startBtnForm = document.getElementById('form-start-match');
            if (startBtnForm) {
                startBtnForm.style.display = 'block';
            } else {
                const alertDiv = document.getElementById('unpaid-fees-alert');
                if (alertDiv) alertDiv.style.display = 'block';
            }
        } else if (status === 'half_time') {
            timerDisplay.textContent = 'Half Time';
            addedTimeDisplay.style.display = 'none';
            document.getElementById('form-start-second-half').style.display = 'block';
            startHalfTimeCountdown();
        } else if (status === 'live') {
            if (!initialSecondHalfStart || initialSecondHalfStart === '0000-00-00 00:00:00') {
                // 1st Half Live
                startTimer(parseInt(page.dataset.elapsedFirst), 0);
                document.getElementById('form-end-first-half').style.display = 'block';
                setEventButtonsDisabled(false);
            } else {
                // 2nd Half Live
                startTimer(parseInt(page.dataset.elapsedSecond), HALF_TIME_MARK / 60);
                document.getElementById('form-end-second-half').style.display = 'block';
                setEventButtonsDisabled(false);
            }
        } else if (status === 'full_time') {
            timerDisplay.textContent = 'Full Time';
            addedTimeDisplay.style.display = 'none';
            document.getElementById('end-match-btn').style.display = 'block';
        } else if (status === 'finished') {
            timerDisplay.textContent = 'Finished';
            addedTimeDisplay.style.display = 'none';
        }
    }

    // --- Event Handling Logic ---
    document.querySelectorAll('.event-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            const eventType = this.dataset.event;
            const teamId = parseInt(this.dataset.teamId);
            
            if (eventType === 'goal') {
                showGoalModal(teamId);
            } else if (eventType === 'own_goal') {
                showPlayerSelectModal(eventType, teamId, "Select Player (Scored Own Goal)");
            } else if (eventType === 'corner') {
                // Corner doesn't require a player
                const formData = new FormData();
                formData.append('action', 'log_event');
                formData.append('fixture_id', fixtureId);
                formData.append('team_id', teamId);
                formData.append('event_type', eventType);
                formData.append('minute', getCurrentMinute());
                submitViaAjax(formData);
            } else if (eventType === 'penalty') {
                showPenaltyModal(teamId);
            } else if (eventType === 'substitution') {
                showSubModal(teamId);
            } else if (eventType === 'offside') {
                showPlayerSelectModal(eventType, teamId, "Offside");
            } else {
                showPlayerSelectModal(eventType, teamId);
            }
        });
    });

    function getPlayerOptions(teamId, eventType, subContext = null) {
        const isHomeTeam = teamId == <?php echo $fixture->home_team_id; ?>;
        let playerPool = [];
        let manager = null;

        if (eventType === 'yellow_card' || eventType === 'red_card') {
            // For cards, use the full lineup (starters + subs) and the manager
            playerPool = isHomeTeam ? homeLineup : awayLineup;
            manager = isHomeTeam ? homeManager : awayManager;
        } else if (eventType === 'substitution') {
            if (subContext === 'on') {
                // For "Player On", show subs who are not already on the pitch
                const onPitch = isHomeTeam ? homePlayersOnPitch : awayPlayersOnPitch;
                const subs = isHomeTeam ? <?php echo json_encode($home_lineup->substitutes ?? []); ?> : <?php echo json_encode($away_lineup->substitutes ?? []); ?>;
                playerPool = subs.filter(pId => !onPitch.includes(pId));
            } else { // 'off' or default
                // For "Player Off", show players currently on the pitch
                playerPool = isHomeTeam ? homePlayersOnPitch : awayPlayersOnPitch;
            }
        } else {
            // For other events, only use players currently on the pitch
            playerPool = isHomeTeam ? homePlayersOnPitch : awayPlayersOnPitch;
        }

        let options = '';
        playerPool.forEach(pid => {
            if (playersData[pid]) {
                const p = playersData[pid];
                let label = p.name;
                if (p.number) label = `#${p.number} ${label}`;
                if (p.pos) label = `${label} (${p.pos})`;
                options += `<option value="${pid}">${label}</option>`;
            } else if (playerNames[pid]) {
                options += `<option value="${pid}">${playerNames[pid]}</option>`;
            }
        });

        // Add manager to the list for card events
        if (manager && manager.id) {
            options += `<option value="${manager.id}">${manager.name}</option>`;
        }

        return options;
    }

    function showPlayerSelectModal(eventType, teamId, title = null) {
        modalTitle.textContent = title || `${eventType.replace(/_/g, ' ')}`.toUpperCase();
        modalBody.innerHTML = `
            <input type="hidden" name="action" value="log_event">
            <input type="hidden" name="fixture_id" value="${fixtureId}">
            <input type="hidden" name="team_id" value="${teamId}">
            <input type="hidden" name="event_type" value="${eventType}">
            <input type="hidden" name="minute" value="${getCurrentMinute()}">
            <div class="form-group">
                <label for="player-select-modal">Select Player:</label>
                <select name="player_id" id="player-select-modal" required>${getPlayerOptions(teamId, eventType)}</select>
            </div>
            <button type="submit" class="btn">Confirm</button>
        `;
        modal.style.display = 'flex';
        
        // Bind submit for the new form content
        modalForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(modalForm);
            submitViaAjax(formData);
        };
    }

    function showGoalModal(teamId) {
        modalTitle.textContent = 'Goal Details';
        modalBody.innerHTML = `
            <input type="hidden" name="action" value="log_event">
            <input type="hidden" name="fixture_id" value="${fixtureId}">
            <input type="hidden" name="team_id" value="${teamId}">
            <input type="hidden" name="event_type" value="goal">
            <input type="hidden" name="minute" value="${getCurrentMinute()}">
            <div class="form-group">
                <label for="goal-scorer-modal">Goal Scorer:</label>
                <select name="player_id" id="goal-scorer-modal" required>${getPlayerOptions(teamId, 'goal')}</select>
            </div>
            <div class="form-group">
                <label for="assist-player-modal">Assisted By:</label>
                <select name="assisted_by_player_id" id="assist-player-modal"><option value="">-- None --</option>${getPlayerOptions(teamId, 'goal')}</select>
            </div>
            <button type="submit" class="btn">Confirm Goal</button>
        `;
        modal.style.display = 'flex';
        
        modalForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(modalForm);
            submitViaAjax(formData);
        };
    }

    function showSubModal(teamId) {
        modalTitle.textContent = 'Substitution';
        modalBody.innerHTML = `
            <input type="hidden" name="action" value="log_event">
            <input type="hidden" name="fixture_id" value="${fixtureId}">
            <input type="hidden" name="team_id" value="${teamId}">
            <input type="hidden" name="event_type" value="substitution">
            <input type="hidden" name="minute" value="${getCurrentMinute()}">
            <div class="form-group">
                <label for="player-off-modal">Player Off:</label>
                <select name="player_id" id="player-off-modal" required>${getPlayerOptions(teamId, 'substitution', 'off')}</select>
            </div>
            <div class="form-group">
                <label for="player-on-modal">Player On:</label>
                <select name="assisted_by_player_id" id="player-on-modal" required>${getPlayerOptions(teamId, 'substitution', 'on')}</select>
            </div>
            <button type="submit" class="btn">Confirm Substitution</button>
        `;
        modal.style.display = 'flex';
        
        modalForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(modalForm);
            submitViaAjax(formData);
        };
    }

    function showPenaltyModal(teamId) {
        modalTitle.textContent = 'Penalty Kick';
        modalBody.innerHTML = `
            <input type="hidden" name="fixture_id" value="${fixtureId}">
            <input type="hidden" name="action" value="log_event">
            <input type="hidden" name="team_id" value="${teamId}">
            <input type="hidden" name="minute" value="${getCurrentMinute()}">
            <input type="hidden" name="event_type" id="penalty-event-type" value="">
            <div class="form-group">
                <label for="penalty-taker-modal">Penalty Taker:</label>
                <select name="player_id" id="penalty-taker-modal" required>${getPlayerOptions(teamId, 'penalty')}</select>
            </div>
            <div class="form-group" style="display: flex; gap: 10px; justify-content: center;">
                <button type="submit" class="btn event-goal" data-event-type="penalty_scored">Scored</button>
                <button type="submit" class="btn event-red" data-event-type="penalty_missed">Missed</button>
            </div>
        `;
        modal.style.display = 'flex';
        modalForm.onsubmit = function(e) {
            e.preventDefault();
            const eventType = e.submitter.dataset.eventType;
            if (eventType) {
                document.getElementById('penalty-event-type').value = eventType;
            }
            const formData = new FormData(modalForm);
            submitViaAjax(formData);
        };
    }

    function showManOfTheMatchModal() {
        modalTitle.textContent = 'Select Man of the Match';
        let allPlayerOptions = '<option value="">-- Optional: Select a Player --</option>';
        allPlayerOptions += '<optgroup label="<?php echo htmlspecialchars($fixture->home_team_name); ?>">';
        homeLineup.forEach(pid => {
            if (playersData[pid]) {
                const p = playersData[pid];
                let label = p.name;
                if (p.number) label = `#${p.number} ${label}`;
                if (p.pos) label = `${label} (${p.pos})`;
                allPlayerOptions += `<option value="${pid}">${label}</option>`;
            } else {
                allPlayerOptions += `<option value="${pid}">${playerNames[pid]}</option>`;
            }
        });
        allPlayerOptions += '</optgroup>';
        allPlayerOptions += '<optgroup label="<?php echo htmlspecialchars($fixture->away_team_name); ?>">';
        awayLineup.forEach(pid => {
            if (playersData[pid]) {
                const p = playersData[pid];
                let label = p.name;
                if (p.number) label = `#${p.number} ${label}`;
                if (p.pos) label = `${label} (${p.pos})`;
                allPlayerOptions += `<option value="${pid}">${label}</option>`;
            } else {
                allPlayerOptions += `<option value="${pid}">${playerNames[pid]}</option>`;
            }
        });
        allPlayerOptions += '</optgroup>';
        modalBody.innerHTML = `
            <p>The match is over. You can optionally select a Man of the Match.</p>
            <input type="hidden" name="action" value="end_match">
            <input type="hidden" name="fixture_id" value="${fixtureId}">
            <div class="form-group">
                <label for="motm-select-modal">Player of the Match:</label>
                <select name="motm_player_id" id="motm-select-modal">${allPlayerOptions}</select>
            </div>
            <button type="submit" class="btn btn-danger" style="width: 100%; margin-top: 1rem;">Confirm & End Match</button>
        `;
        modal.style.display = 'flex';
        
        modalForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(modalForm);
            submitViaAjax(formData);
        };
    }

    document.getElementById('end-match-btn').addEventListener('click', showManOfTheMatchModal);

    function closeModal() {
        modal.style.display = 'none';
        modalBody.innerHTML = '';
    }
    modalCloseBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });

    // --- Undo Button Logic ---
    const undoForm = document.getElementById('undo-event-form');
    if (undoForm) {
        undoForm.onsubmit = function(e) {
            e.preventDefault();
            submitViaAjax(new FormData(undoForm));
        };
    }

    // --- Display Flash Message as Toast ---
    <?php if (isset($_SESSION['flash_message'])): ?>
        showToast('<?php echo addslashes($_SESSION['flash_message']['text']); ?>', '<?php echo $_SESSION['flash_message']['type']; ?>');
        <?php unset($_SESSION['flash_message']); ?>
    <?php endif; ?>

    initializeUIState();
});
</script>

<style>
    .event-palette-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-top: 2rem;
    }
    .event-column {
        display: flex;
        flex-direction: column;
        gap: 10px;
        position: relative; /* For sticky child */
    }
    .event-column .team-title {
        text-align: center;
        margin: 0 0 10px 0;
        padding: 15px;
        border-bottom: 2px solid #ddd;
        position: sticky;
        top: 0px; /* Adjust based on header height */
        background: #f8f9fa;
        z-index: 900;
        border-radius: 0 0 8px 8px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        font-weight: 800;
        color: #2c3e50;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .timer-controls {
        display: flex;
        flex-direction: column;
        gap: 10px;
        width: 100%;
    }
    .timer-controls form, .timer-controls button, .timer-controls .alert {
        width: 100%;
        margin: 0;
    }
    .event-btn {
        width: 100%;
        padding: 12px;
        font-size: 0.9rem;
        font-weight: bold;
        cursor: pointer;
        border: 1px solid #ddd;
        background-color: #f8f9fa;
        color: #333;
        border-radius: 5px;
        transition: background-color 0.2s, border-color 0.2s;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        gap: 10px;
    }
    .event-btn:disabled,
    .event-btn[disabled] {
        opacity: 0.5;
        cursor: not-allowed;
    }
    .event-btn:disabled:hover,
    .event-btn[disabled]:hover {
        background-color: #f8f9fa;
        border-color: #ddd;
    }
    .event-btn:hover {
        background-color: #e9ecef;
        border-color: #ccc;
    }
    .event-btn i {
        width: 20px;
        text-align: center;
    }
    .event-btn.event-goal { background-color: #2ecc71; color: white; border-color: #27ae60; }
    .event-btn.event-goal:hover { background-color: #25a25a; }

    .event-btn.event-yellow { background-color: #f1c40f; color: #333; border-color: #f39c12; }
    .event-btn.event-yellow:hover { background-color: #d4ac0d; }
    .event-btn.event-yellow:disabled:hover,
    .event-btn.event-yellow[disabled]:hover {
        background-color: #f1c40f;
        border-color: #f39c12;
    }

    .event-btn.event-red { background-color: #e74c3c; color: white; border-color: #c0392b; }
    .event-btn.event-red:hover { background-color: #b83d30; }

    .event-btn.event-sub { background-color: #3498db; color: white; border-color: #2980b9; }
    .event-btn.event-sub:hover { background-color: #2980b9; }

    .event-btn.event-penalty { background-color: #34495e; color: white; border-color: #2c3e50; }
    .event-btn.event-penalty:hover { background-color: #2c3e50; }

    .event-btn.event-own-goal { background-color: #e74c3c; color: white; border-color: #c0392b; }
    .event-btn.event-own-goal:hover { background-color: #b83d30; }

    .event-log-container {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #eee;
        padding: 10px;
        border-radius: 5px;
    }
    .event-log-item {
        display: flex;
        gap: 15px;
        padding: 8px 5px;
        border-bottom: 1px solid #f0f0f0;
    }
    .event-log-item .minute { font-weight: bold; }

    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    /* Toast Notification Styles */
    #toast-container {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 10000;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .toast {
        background-color: #333;
        color: #fff;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        opacity: 1;
        transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
        transform: translateY(0);
        min-width: 250px;
        display: flex;
        align-items: center;
        font-size: 0.95rem;
    }

    .toast.hide {
        opacity: 0;
        transform: translateY(20px);
    }

    .toast-success {
        background-color: #28a745;
    }

    .toast-error {
        background-color: #dc3545;
    }

    .toast-info {
        background-color: #17a2b8;
    }
</style>

<?php
include 'includes/footer.php';
?>