<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Auto-login functionality for QR code access
session_start();

// Check for auto-login from scores.php or QR code access
if (isset($_SESSION['auto_event_id']) && isset($_SESSION['auto_flight'])) {
    $EventId = $_SESSION['auto_event_id'];
    $flight = $_SESSION['auto_flight'];
    $_SESSION['loggedin'] = true;
    $_SESSION['EventId'] = $EventId;
    $_SESSION['flight'] = $flight;
    $_SESSION['auto_login'] = true;
    unset($_SESSION['auto_event_id']);
    unset($_SESSION['auto_flight']);
} else {
    // Fallback to GET parameters for direct access
    $EventId = isset($_GET['EventId']) ? intval($_GET['EventId']) : 0;
    $flight = isset($_GET['flight']) ? $_GET['flight'] : '';
    
    // Auto-login for QR code access
    if ($EventId && $flight) {
        $_SESSION['loggedin'] = true;
        $_SESSION['EventId'] = $EventId;
        $_SESSION['flight'] = $flight;
        $_SESSION['auto_login'] = true;
    }
}

include "event-session-check.php";
include "event-server.php";

// Get event details
$groupType = 'Flights';
$eventName = '';
$eventDate = '';
$eventFormat = '';

if ($EventId) {
    $eventSql = "SELECT e.groupType, e.event, e.date, e.groupNumber FROM Events e WHERE e.id = ?";
    $eventStmt = $conn->prepare($eventSql);
    $eventStmt->bind_param("i", $EventId);
    $eventStmt->execute();
    $eventResult = $eventStmt->get_result();
    if ($eventData = $eventResult->fetch_assoc()) {
        $groupType = $eventData['groupType'] ?? 'Flights';
        $eventName = $eventData['event'] ?? '';
        $eventDate = $eventData['date'] ?? '';
        $groupNumber = $eventData['groupNumber'] ?? 0;
        
        // Get Format from InviteEventGroupsText
        if ($groupNumber) {
            $formatSql = "SELECT Format FROM InviteEventGroupsText WHERE groupNumber = ?";
            $formatStmt = $conn->prepare($formatSql);
            $formatStmt->bind_param("i", $groupNumber);
            $formatStmt->execute();
            $formatResult = $formatStmt->get_result();
            if ($formatData = $formatResult->fetch_assoc()) {
                $eventFormat = $formatData['Format'] ?? '';
            }
            $formatStmt->close();
        }
    }
    $eventStmt->close();
}

// Determine format type: Individual or Pairs
$isPairs = ($groupType === 'Pairs' || strtoupper($eventFormat) === 'AM/AM' || strtoupper($eventFormat) === 'PAIRS');

// Get hole par and index data
$epholes_par = [];
$epholes_index = [];
$parRes = $conn->query("SELECT * FROM epholes WHERE type = 'par'");
if ($parRes && $parRow = $parRes->fetch_assoc()) {
    $epholes_par = $parRow;
}
$indexRes = $conn->query("SELECT * FROM epholes WHERE type = 'index'");
if ($indexRes && $indexRow = $indexRes->fetch_assoc()) {
    $epholes_index = $indexRow;
}

// Load players for this flight
$players = [];
if ($EventId && $flight) {
    $playerSql = "SELECT 
        eu.id,
        COALESCE(Guests.name, Users.name) AS name,
        COALESCE(Guests.handicap, Users.handicap) AS handicap,
        COALESCE(Guests.gender, Users.gender) AS gender,
        eu.flight,
        eu.tee,
        CASE 
            WHEN eu.GuestId IS NOT NULL THEN COALESCE(eu.otherClub, 'Guest Club')
            ELSE 'El Paraiso'
        END as club
    FROM EventUsers eu 
    LEFT JOIN Users ON eu.UserId = Users.id 
    LEFT JOIN Guests ON eu.GuestId = Guests.id 
    WHERE eu.EventId = ? AND eu.flight = ?
    ORDER BY eu.id";
    
    $playerStmt = $conn->prepare($playerSql);
    $playerStmt->bind_param("is", $EventId, $flight);
    $playerStmt->execute();
    $playerResult = $playerStmt->get_result();
    
    while ($row = $playerResult->fetch_assoc()) {
        // Calculate slope for each player
        $slopeData = calculatePlayerShotsAndHoles($row, $EventId, $conn);
        $row['slope'] = $slopeData['shots'];
        $row['tee'] = $row['tee'] ?? 1; // Default to tee 1 if not set
        $players[] = $row;
    }
    $playerStmt->close();
}

// For Pairs format, organize into teams
$team1Players = [];
$team2Players = [];
if ($isPairs && count($players) >= 2) {
    // Split players into two teams (first half = Team 1, second half = Team 2)
    $midPoint = ceil(count($players) / 2);
    $team1Players = array_slice($players, 0, $midPoint);
    $team2Players = array_slice($players, $midPoint);
}

// Function to calculate player shots and get shot holes
function calculatePlayerShotsAndHoles($player, $EventId, $conn) {
    $handicap = floatval(str_replace(',', '.', $player['handicap'] ?? 0));
    $gender = $player['gender'] ?? 'M';
    
    // Get event setup data
    $setupSql = "SELECT e.groupNumber, i.percent, i.men, i.women, i.MaxHandicapMen, i.MaxHandicapWomen 
                 FROM Events e 
                 LEFT JOIN InviteEventGroupsText i ON e.groupNumber = i.groupNumber 
                 WHERE e.id = ?";
    $setupStmt = $conn->prepare($setupSql);
    $setupStmt->bind_param("i", $EventId);
    $setupStmt->execute();
    $setupResult = $setupStmt->get_result();
    $setupData = $setupResult->fetch_assoc() ?? [];
    $setupStmt->close();
    
    $Men = intval($setupData['men'] ?? 52);
    $Women = intval($setupData['women'] ?? 45);
    $percent = intval($setupData['percent'] ?? 100);
    $maxHandicapMen = intval($setupData['MaxHandicapMen'] ?? 28);
    $maxHandicapWomen = intval($setupData['MaxHandicapWomen'] ?? 36);
    
    // Set teebox based on gender
    $teebox = ($gender == "F") ? $Women : $Men;
    
    // Convert teebox to comptees format
    $comptees = $teebox;
    if ($comptees == 45) {
        $comptees = "Ora";
    } elseif ($comptees == 50) {
        $comptees = "Red";
    } elseif ($comptees == 52) {
        $comptees = "Blu";
    } elseif ($comptees == 56) {
        $comptees = "Yel";
    } elseif ($comptees == 58) {
        $comptees = "Vio";
    } elseif ($comptees == 60) {
        $comptees = "Whi";
    }
    
    // Set session variables for ephcp.php
    $_SESSION['men'] = $Men;
    $_SESSION['women'] = $Women;
    $_SESSION['percent'] = $percent;
    
    // Include ephcp.php to calculate shots
    $name = $player['name'] ?? '';
    include "event-hcp.php";
    
    // Apply max handicap limits
    if ($gender == "F" && $Shots > $maxHandicapWomen) {
        $Shots = $maxHandicapWomen;
    }
    if ($gender == "M" && $Shots > $maxHandicapMen) {
        $Shots = $maxHandicapMen;
    }
    
    $slope = $Shots ?? 0;
    
    // Get which holes get shots from slopeshots table
    $shotHoles = [];
    if ($slope > 0) {
        $slopeSql = "SELECT * FROM slopeshots WHERE slope = ?";
        $slopeStmt = $conn->prepare($slopeSql);
        $slopeStmt->bind_param("i", $slope);
        $slopeStmt->execute();
        $slopeResult = $slopeStmt->get_result();
        $slopeData = $slopeResult->fetch_assoc() ?? [];
        $slopeStmt->close();
        
        if (!empty($slopeData)) {
            // Get hole indices and sort by difficulty (lowest index = easiest = gets shots first)
            $holeIndices = [];
            $indexRes = $conn->query("SELECT * FROM epholes WHERE type = 'index'");
            if ($indexRes && $indexRow = $indexRes->fetch_assoc()) {
                for ($h = 1; $h <= 18; $h++) {
                    $holeIndices[$h] = intval($indexRow['h' . $h] ?? 18);
                }
            }
            
            // Sort holes by index (easiest first)
            asort($holeIndices);
            $sortedHoles = array_keys($holeIndices);
            
            // First $slope holes get shots
            $shotHoles = array_slice($sortedHoles, 0, $slope);
        }
    }
    
    return ['shots' => $slope, 'shotHoles' => $shotHoles];
}

// Handle AJAX request for player slope data
if (isset($_GET['action']) && $_GET['action'] === 'getPlayerSlope' && isset($_GET['playerId'])) {
    header('Content-Type: application/json');
    $playerId = intval($_GET['playerId']);
    $player = null;
    foreach ($players as $p) {
        if ($p['id'] == $playerId) {
            $player = $p;
            break;
        }
    }
    
    if ($player) {
        $slopeData = calculatePlayerShotsAndHoles($player, $EventId, $conn);
        echo json_encode($slopeData);
    } else {
        echo json_encode(['error' => 'Player not found']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Digital Scorecard - <?php echo htmlspecialchars($eventName); ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body { 
            font-family: Arial, sans-serif; 
            background-color: #f5f5f5;
            padding: 10px;
        }
        
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 18px;
            margin: 0;
        }
        
        .exit-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
        }
        
        .exit-btn:hover {
            background-color: #c0392b;
        }
        
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 14px;
        }
        
        .score-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .score-table th,
        .score-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .score-table th {
            background-color: #34495e;
            color: white;
            font-weight: bold;
        }
        
        .score-table input[type="number"] {
            width: 60px;
            padding: 5px;
            text-align: center;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        
        .team1-row {
            background-color: #e9ecef;
        }
        
        .team2-row {
            background-color: #fff3cd;
        }
        
        .save-btn {
            background-color: #27ae60;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
                width: 100%; 
            margin-top: 20px;
        }
        
        .save-btn:hover {
            background-color: #229954;
        }
        
        .message {
                padding: 10px;
            margin-bottom: 20px;
            border-radius: 3px;
            display: none;
        }
        
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .summary-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .summary-field {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 180px;
        }
        
        .summary-field input {
            width: 70px;
            padding: 4px;
            font-size: 1em;
        }
        
        .icon {
            font-size: 1.3em;
            vertical-align: middle;
        }
        
        .icon.success {
            color: #27ae60;
        }
        
        .icon.error {
            color: #e74c3c;
        }
        
        .check-btn {
            padding: 8px 18px;
            font-size: 1.1em;
            background: #0074d9;
            color: #fff;
            border: none;
                border-radius: 4px;
            cursor: pointer;
        }
        
        .check-btn:hover {
            background: #005fa3;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><?php echo htmlspecialchars($eventName); ?> - Flight <?php echo htmlspecialchars($flight); ?></h1>
        <button class="exit-btn" onclick="exitPage()">✕ Exit</button>
        </div>

    <div class="container">
        <div id="message" class="message"></div>
        
        <?php if ($isPairs): ?>
            <!-- PAIRS FORMAT -->
            <div class="form-group">
                <label for="teamSelect">Select Team to Mark:</label>
                <select id="teamSelect">
                    <option value="">-- Select Team --</option>
                    <option value="1">Team 1</option>
                    <option value="2">Team 2</option>
                </select>
                </div>
            
            <div id="team1Scores" style="display: none;">
                <h3>Team 1 Scores</h3>
                <table class="score-table team1-row">
                    <thead>
                        <tr>
                            <th>Hole</th>
                            <th>Par</th>
                            <th>Index</th>
                            <th>Score</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php for ($i = 1; $i <= 18; $i++): ?>
                            <tr>
                                <td><?php echo $i; ?></td>
                                <td><?php echo $epholes_par["h{$i}"] ?? '-'; ?></td>
                                <td><?php echo $epholes_index["h{$i}"] ?? '-'; ?></td>
                                <td><input type="number" min="1" max="15" class="team1-score" data-hole="<?php echo $i; ?>"></td>
                            </tr>
                        <?php endfor; ?>
                    </tbody>
                </table>
            </div>
            
            <div id="team2Scores" style="display: none;">
                <h3>Team 2 Scores</h3>
                <table class="score-table team2-row">
                    <thead>
                        <tr>
                            <th>Hole</th>
                            <th>Par</th>
                            <th>Index</th>
                            <th>Score</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php for ($i = 1; $i <= 18; $i++): ?>
                            <tr>
                                <td><?php echo $i; ?></td>
                                <td><?php echo $epholes_par["h{$i}"] ?? '-'; ?></td>
                                <td><?php echo $epholes_index["h{$i}"] ?? '-'; ?></td>
                                <td><input type="number" min="1" max="15" class="team2-score" data-hole="<?php echo $i; ?>"></td>
                            </tr>
                        <?php endfor; ?>
                    </tbody>
                </table>
                        </div>
            
        <?php else: ?>
            <!-- INDIVIDUAL FORMAT -->
            <div class="form-group">
                <label for="playerSelect">Select Player:</label>
                <select id="playerSelect">
                    <option value="">-- Select Player --</option>
                    <?php foreach ($players as $player): ?>
                        <option value="<?php echo $player['id']; ?>" 
                                data-name="<?php echo htmlspecialchars($player['name']); ?>"
                                data-handicap="<?php echo $player['handicap']; ?>"
                                data-slope="<?php echo $player['slope'] ?? 0; ?>"
                                data-tee="<?php echo $player['tee'] ?? 1; ?>">
                            <?php echo htmlspecialchars($player['name']); ?> (Hcp: <?php echo $player['handicap']; ?>, Slope: <?php echo $player['slope'] ?? 0; ?>, Tee: <?php echo $player['tee'] ?? 1; ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div id="playerScores" style="display: none;">
                <h3>Player Scores</h3>
                
                <!-- Totals Entry Section -->
                <div class="summary-row" style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
                    <div class="summary-field">
                        <label for="enteredFront9Points">Front 9 Points:</label>
                        <input type="number" id="enteredFront9Points" min="0" style="width: 70px; padding: 4px;">
                        <span id="iconFront9"></span>
                    </div>
                    <div class="summary-field">
                        <label for="enteredBack9Points">Back 9 Points:</label>
                        <input type="number" id="enteredBack9Points" min="0" style="width: 70px; padding: 4px;">
                        <span id="iconBack9"></span>
                    </div>
                    <div class="summary-field">
                        <label for="enteredTotalPoints">Total Points:</label>
                        <input type="number" id="enteredTotalPoints" min="0" style="width: 70px; padding: 4px; background-color: #f0f0f0;" readonly>
                        <span id="iconTotal"></span>
                </div>
                    <button class="check-btn" id="checkBtn" style="padding: 8px 18px; font-size: 1.1em; background: #0074d9; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Check</button>
            </div>
                
                <table class="score-table" id="individualScoreTable">
                    <thead>
                        <tr>
                            <th>Hole</th>
                            <th>Par</th>
                            <th>Index</th>
                            <th>Score</th>
                            <th>Points</th>
                </tr>
                    </thead>
                    <tbody id="individualScoreBody">
                        <?php for ($i = 1; $i <= 18; $i++): ?>
                            <tr data-hole="<?php echo $i; ?>">
                                <td><?php echo $i; ?></td>
                                <td class="par-cell"><?php echo $epholes_par["h{$i}"] ?? '-'; ?></td>
                                <td class="index-cell"><?php echo $epholes_index["h{$i}"] ?? '-'; ?></td>
                                <td><input type="number" min="1" max="15" class="player-score" data-hole="<?php echo $i; ?>" oninput="calculateStableford()" onchange="calculateStableford()"></td>
                                <td class="points-cell" data-hole="<?php echo $i; ?>">-</td>
                </tr>
                        <?php endfor; ?>
                        <tr class="totals-row" style="background-color: #e9ecef;">
                            <td colspan="3" style="text-align: right; font-weight: bold;">Front 9 Totals:</td>
                            <td id="front9Total" style="font-weight: bold;">-</td>
                            <td id="front9Points" style="font-weight: bold;">0</td>
                </tr>
                        <tr class="totals-row" style="background-color: #e9ecef;">
                            <td colspan="3" style="text-align: right; font-weight: bold;">Back 9 Totals:</td>
                            <td id="back9Total" style="font-weight: bold;">-</td>
                            <td id="back9Points" style="font-weight: bold;">0</td>
                </tr>
                        <tr class="totals-row" style="background-color: #d4edda;">
                            <td colspan="3" style="text-align: right; font-weight: bold;">Total 18 Holes:</td>
                            <td id="total18Total" style="font-weight: bold;">-</td>
                            <td id="total18Points" style="font-weight: bold;">0</td>
                </tr>
                    </tbody>
            </table>
        </div>
        <?php endif; ?>

        <button class="save-btn" onclick="saveScores()">Save Scores</button>
    </div>
    
    <script>
        const eventId = <?php echo $EventId; ?>;
        const flight = '<?php echo $flight; ?>';
        const isPairs = <?php echo $isPairs ? 'true' : 'false'; ?>;
        const players = <?php echo json_encode($players); ?>;
        const parValues = <?php echo json_encode($epholes_par); ?>;
        
        // Store current player slope data
        let currentPlayerSlope = null;
        let currentPlayerShotHoles = [];
        
        // Show/hide score tables based on selection
            if (isPairs) {
            document.getElementById('teamSelect').addEventListener('change', function() {
                const team = this.value;
                document.getElementById('team1Scores').style.display = (team === '1') ? 'block' : 'none';
                document.getElementById('team2Scores').style.display = (team === '2') ? 'block' : 'none';
            });
                } else {
            document.getElementById('playerSelect').addEventListener('change', function() {
                const playerId = this.value;
                if (playerId) {
                    document.getElementById('playerScores').style.display = 'block';
                    // Reset all scores and highlights
                    document.querySelectorAll('.player-score').forEach(input => input.value = '');
                    document.querySelectorAll('.points-cell').forEach(cell => {
                        cell.textContent = '-';
                        cell.style.fontWeight = 'normal';
                    });
                    document.querySelectorAll('tr[data-hole]').forEach(row => row.style.backgroundColor = '');
                    // Reset totals
                    document.getElementById('front9Total').textContent = '-';
                    document.getElementById('front9Points').textContent = '0';
                    document.getElementById('back9Total').textContent = '-';
                    document.getElementById('back9Points').textContent = '0';
                    document.getElementById('total18Total').textContent = '-';
                    document.getElementById('total18Points').textContent = '0';
                    // Load player slope data
                    loadPlayerSlope(playerId);
                } else {
                    document.getElementById('playerScores').style.display = 'none';
                    currentPlayerSlope = null;
                    currentPlayerShotHoles = [];
                    // Clear totals inputs
                    document.getElementById('enteredFront9Points').value = '';
                    document.getElementById('enteredBack9Points').value = '';
                    document.getElementById('enteredTotalPoints').value = '';
                    showIcon('iconFront9', null);
                    showIcon('iconBack9', null);
                    showIcon('iconTotal', null);
                }
            });
        }
        
        function loadPlayerSlope(playerId) {
            fetch(`event-scorecard-digital.php?action=getPlayerSlope&playerId=${playerId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        console.error('Error loading player slope:', data.error);
                        return;
                    }
                    currentPlayerSlope = data.shots || 0;
                    currentPlayerShotHoles = data.shotHoles || [];
                    
                    // Highlight holes that get shots
                    for (let hole = 1; hole <= 18; hole++) {
                        const row = document.querySelector(`tr[data-hole="${hole}"]`);
                        if (row) {
                            // Check if hole is in shot holes array (handle both string and number)
                            const hasShot = currentPlayerShotHoles.includes(hole) || 
                                          currentPlayerShotHoles.includes(parseInt(hole)) ||
                                          currentPlayerShotHoles.includes(String(hole));
                            if (hasShot) {
                                row.style.backgroundColor = '#fff3cd'; // Yellow highlight for shot holes
                    } else {
                                row.style.backgroundColor = '';
                            }
                        }
                    }
                    
                    // Recalculate stableford after loading slope
                    calculateStableford();
                })
                .catch(error => {
                    console.error('Error loading player slope:', error);
                });
        }
        
        function calculateStableford() {
            // Allow calculation even if slope is 0 (player might have 0 shots)
            // But if slope hasn't been loaded yet (null/undefined), we can still calculate without shots
            const hasSlope = currentPlayerSlope !== null && currentPlayerSlope !== undefined;
            
            // Debug log
            console.log('calculateStableford called', { hasSlope, currentPlayerSlope, currentPlayerShotHoles });
            
            let front9Total = 0;
            let back9Total = 0;
            let front9Points = 0;
            let back9Points = 0;
            
            // Calculate for each hole
            for (let hole = 1; hole <= 18; hole++) {
                const scoreInput = document.querySelector(`.player-score[data-hole="${hole}"]`);
                const pointsCell = document.querySelector(`.points-cell[data-hole="${hole}"]`);
                
                if (!scoreInput || !pointsCell) continue;
                
                const score = parseInt(scoreInput.value);
                // Get par value - try different formats
                let par = 4; // default
                if (parValues) {
                    par = parseInt(parValues['h' + hole]) || parseInt(parValues['H' + hole]) || 4;
                }
                
                if (score && score > 0) {
                    // Check if this hole gets a shot (only if slope is loaded)
                    let shotsOnHole = 0;
                    if (hasSlope && currentPlayerShotHoles && Array.isArray(currentPlayerShotHoles)) {
                        // Check if hole number is in the shot holes array (handle both string and number)
                        const hasShot = currentPlayerShotHoles.includes(hole) || 
                                       currentPlayerShotHoles.includes(parseInt(hole)) ||
                                       currentPlayerShotHoles.includes(String(hole));
                        shotsOnHole = hasShot ? 1 : 0;
                    }
                    
                    // Calculate stableford points
                    // Points = max(0, par + shots - score + 2)
                    // Standard: 2 points for par, 3 for birdie, 4 for eagle, 1 for bogey, 0 for double+
                    const points = Math.max(0, par + shotsOnHole - score + 2);
                    
                    pointsCell.textContent = points;
                    pointsCell.style.fontWeight = 'bold';
                    
                    // Add to totals
                    if (hole <= 9) {
                        front9Total += score;
                        front9Points += points;
                    } else {
                        back9Total += score;
                        back9Points += points;
                    }
                } else {
                    pointsCell.textContent = '-';
                    pointsCell.style.fontWeight = 'normal';
                }
            }
            
            // Update totals
            document.getElementById('front9Total').textContent = front9Total || '-';
            document.getElementById('front9Points').textContent = front9Points;
            document.getElementById('back9Total').textContent = back9Total || '-';
            document.getElementById('back9Points').textContent = back9Points;
            document.getElementById('total18Total').textContent = (front9Total + back9Total) || '-';
            document.getElementById('total18Points').textContent = front9Points + back9Points;
            
            // Update total points field (readonly, auto-calculated)
            const enteredFront9 = parseInt(document.getElementById('enteredFront9Points').value) || 0;
            const enteredBack9 = parseInt(document.getElementById('enteredBack9Points').value) || 0;
            document.getElementById('enteredTotalPoints').value = enteredFront9 + enteredBack9;
        }
        
        // Add event listeners for totals input fields
        if (!isPairs) {
            document.getElementById('enteredFront9Points').addEventListener('input', function() {
                const front9 = parseInt(this.value) || 0;
                const back9 = parseInt(document.getElementById('enteredBack9Points').value) || 0;
                document.getElementById('enteredTotalPoints').value = front9 + back9;
            });
            
            document.getElementById('enteredBack9Points').addEventListener('input', function() {
                const front9 = parseInt(document.getElementById('enteredFront9Points').value) || 0;
                const back9 = parseInt(this.value) || 0;
                document.getElementById('enteredTotalPoints').value = front9 + back9;
            });
            
            // Check button functionality
            document.getElementById('checkBtn').addEventListener('click', function() {
                checkTotals();
            });
        }
        
        function showIcon(elementId, isOk) {
            const el = document.getElementById(elementId);
            if (isOk === null) {
                el.innerHTML = '';
            } else if (isOk) {
                el.innerHTML = '<span class="icon success">✔</span>';
            } else {
                el.innerHTML = '<span class="icon error">❌</span>';
            }
        }
        
        function checkTotals() {
            const enteredFront9 = parseInt(document.getElementById('enteredFront9Points').value) || 0;
            const enteredBack9 = parseInt(document.getElementById('enteredBack9Points').value) || 0;
            const enteredTotal = parseInt(document.getElementById('enteredTotalPoints').value) || 0;
            
            const calculatedFront9 = parseInt(document.getElementById('front9Points').textContent) || 0;
            const calculatedBack9 = parseInt(document.getElementById('back9Points').textContent) || 0;
            const calculatedTotal = parseInt(document.getElementById('total18Points').textContent) || 0;
            
            let firstError = null;
            
            // Check Front 9
            if (enteredFront9 === 0 && calculatedFront9 === 0) {
                showIcon('iconFront9', null);
            } else if (enteredFront9 === calculatedFront9) {
                showIcon('iconFront9', true);
            } else {
                showIcon('iconFront9', false);
                if (!firstError) firstError = document.getElementById('enteredFront9Points');
            }
            
            // Check Back 9
            if (enteredBack9 === 0 && calculatedBack9 === 0) {
                showIcon('iconBack9', null);
            } else if (enteredBack9 === calculatedBack9) {
                showIcon('iconBack9', true);
                    } else {
                showIcon('iconBack9', false);
                if (!firstError) firstError = document.getElementById('enteredBack9Points');
            }
            
            // Check Total
            if (enteredTotal === 0 && calculatedTotal === 0) {
                showIcon('iconTotal', null);
            } else if (enteredTotal === calculatedTotal) {
                showIcon('iconTotal', true);
                    } else {
                showIcon('iconTotal', false);
                if (!firstError) firstError = document.getElementById('enteredTotalPoints');
            }
            
            // Scroll to first error if any
            if (firstError) {
                setTimeout(() => {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstError.focus();
                }, 100);
            }
        }
        
        function showMessage(text, type) {
            const msgDiv = document.getElementById('message');
            msgDiv.textContent = text;
            msgDiv.className = 'message ' + type;
            msgDiv.style.display = 'block';
            setTimeout(() => {
                msgDiv.style.display = 'none';
            }, 5000);
        }
        
        function saveScores() {
            let scores = {};
            let player1Name = '';
            let player2Name = '';
            let player1Hcp = 0;
            let player2Hcp = 0;
            
                if (isPairs) {
                const team = document.getElementById('teamSelect').value;
                if (!team) {
                    showMessage('Please select a team first', 'error');
                    return;
                }
                
                // Get scores for selected team
                const scoreInputs = team === '1' 
                    ? document.querySelectorAll('.team1-score')
                    : document.querySelectorAll('.team2-score');
                
                scoreInputs.forEach(input => {
                    const hole = input.getAttribute('data-hole');
                    const score = input.value;
                    if (score) {
                        scores[hole] = parseInt(score);
                    }
                });
                
                // Get team player names
                if (team === '1' && players.length >= 2) {
                    player1Name = players[0].name || '';
                    player1Hcp = parseFloat(players[0].handicap) || 0;
                    player2Name = players[1].name || '';
                    player2Hcp = parseFloat(players[1].handicap) || 0;
                } else if (team === '2' && players.length >= 4) {
                    player1Name = players[2].name || '';
                    player1Hcp = parseFloat(players[2].handicap) || 0;
                    player2Name = players[3].name || '';
                    player2Hcp = parseFloat(players[3].handicap) || 0;
                } else if (team === '2' && players.length >= 2) {
                    // If only 2 players total, Team 2 uses same players
                    player1Name = players[0].name || '';
                    player1Hcp = parseFloat(players[0].handicap) || 0;
                    player2Name = players[1].name || '';
                    player2Hcp = parseFloat(players[1].handicap) || 0;
                }
            } else {
                const playerSelect = document.getElementById('playerSelect');
                const selectedPlayerId = playerSelect.value;
                if (!selectedPlayerId) {
                    showMessage('Please select a player first', 'error');
                    return;
                }
                
                const selectedPlayer = players.find(p => p.id == selectedPlayerId);
                if (!selectedPlayer) {
                    showMessage('Player not found', 'error');
                    return;
                }
                
                player1Name = selectedPlayer.name;
                player1Hcp = parseFloat(selectedPlayer.handicap) || 0;
                
                // Get scores
                document.querySelectorAll('.player-score').forEach(input => {
                    const hole = input.getAttribute('data-hole');
                    const score = input.value;
                    if (score) {
                        scores[hole] = parseInt(score);
                    }
                });
            }
            
            if (Object.keys(scores).length === 0) {
                showMessage('Please enter at least one score', 'error');
                return;
            }
            
            // Calculate stableford points using proper calculation
            let front9Stableford = 0;
            let back9Stableford = 0;
            
            if (!isPairs && currentPlayerSlope !== null) {
                // Individual format - use proper stableford calculation
                for (let hole = 1; hole <= 9; hole++) {
                    if (scores[hole]) {
                        const par = parseInt(parValues['h' + hole]) || 4;
                        const score = scores[hole];
                        const hasShot = currentPlayerShotHoles.includes(hole);
                        const shotsOnHole = hasShot ? 1 : 0;
                        const points = Math.max(0, par + shotsOnHole - score + 2);
                        front9Stableford += points;
                    }
                }
                
                for (let hole = 10; hole <= 18; hole++) {
                    if (scores[hole]) {
                        const par = parseInt(parValues['h' + hole]) || 4;
                        const score = scores[hole];
                        const hasShot = currentPlayerShotHoles.includes(hole);
                        const shotsOnHole = hasShot ? 1 : 0;
                        const points = Math.max(0, par + shotsOnHole - score + 2);
                        back9Stableford += points;
                    }
                            }
                        } else {
                // Pairs format or slope not loaded - use basic calculation
                for (let hole = 1; hole <= 9; hole++) {
                    if (scores[hole]) {
                        const par = parseInt(parValues['h' + hole]) || 4;
                        const score = scores[hole];
                        const points = Math.max(0, par - score + 2);
                        front9Stableford += points;
                    }
                }
                
                for (let hole = 10; hole <= 18; hole++) {
                    if (scores[hole]) {
                        const par = parseInt(parValues['h' + hole]) || 4;
                        const score = scores[hole];
                        const points = Math.max(0, par - score + 2);
                        back9Stableford += points;
                    }
                }
            }
            
            const totalStableford = front9Stableford + back9Stableford;
            
            // Prepare data for saving
            const saveData = {
                event_id: eventId,
                flight: flight,
                player1_name: player1Name,
                player1_hcp: player1Hcp,
                player1_slope: currentPlayerSlope || 0,
                player2_name: player2Name,
                player2_hcp: player2Hcp,
                player2_slope: 0, // You may need to calculate this
                front9_stableford: front9Stableford,
                back9_stableford: back9Stableford,
                total_stableford: totalStableford,
                club: 'El Paraiso',
                marked: ''
            };
            
            // Send to server
            fetch('event-save-scores.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(saveData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('Scores saved successfully!', 'success');
                } else {
                    showMessage('Error saving scores: ' + (data.error || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('Error saving scores. Please try again.', 'error');
            });
        }
        
        function exitPage() {
            // Detect if we're on mobile
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            
            if (isMobile) {
                // On mobile, try to close the window/app
                // For QR code opened pages, window.close() typically won't work,
                // so we'll navigate to a minimal exit page instead
                try {
                    // Try to close first (works in some WebView scenarios)
                    window.close();
                    
                    // If we get here, window.close() didn't work, so navigate away
                    // Navigate to a minimal exit page
                    window.location.replace('data:text/html,<html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="font-family:Arial;text-align:center;padding:50px 20px;background:#f5f5f5;"><h2 style="color:#27ae60;">✓ Scorecard Closed</h2><p style="color:#666;margin-top:20px;">You can now close this tab.</p></body></html>');
                } catch (e) {
                    // If anything fails, navigate to exit page
                    window.location.replace('data:text/html,<html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="font-family:Arial;text-align:center;padding:50px 20px;background:#f5f5f5;"><h2 style="color:#27ae60;">✓ Scorecard Closed</h2><p style="color:#666;margin-top:20px;">You can now close this tab.</p></body></html>');
                }
            } else {
                // On desktop, use normal navigation
                if (window.history.length > 1) {
                    window.history.back();
                } else {
                    window.location.href = 'event-participants.php?EventId=' + eventId;
                }
            }
        }
    </script>
</body>
</html> 

