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

// Auto-login functionality
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;
    
    // Clear the auto-login session variables
    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 (when EventId and flight are provided via GET)
    if ($EventId && $flight) {
        $_SESSION['loggedin'] = true;
        $_SESSION['EventId'] = $EventId;
        $_SESSION['flight'] = $flight;
        $_SESSION['auto_login'] = true;
    }
}

include "event-session-check.php";

// Get marker flight (odd/even system)
$markerFlight = 0;
if ($flight) {
    // Flight 1 -> Flight 2, Flight 2 -> Flight 1, Flight 3 -> Flight 4, Flight 4 -> Flight 3, etc.
    $markerFlight = ($flight % 2 == 1) ? $flight + 1 : $flight - 1;
}

// Create scores table if it doesn't exist
$createTableSql = "CREATE TABLE IF NOT EXISTS EventScores (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_id INT NOT NULL,
    event_date DATE,
    club VARCHAR(255),
    flight INT NOT NULL,
    player1_name VARCHAR(255),
    player1_hcp DECIMAL(5,2),
    player1_slope INT,
    player2_name VARCHAR(255),
    player2_hcp DECIMAL(5,2),
    player2_slope INT,
    front9_stableford INT DEFAULT 0,
    back9_stableford INT DEFAULT 0,
    total_stableford INT DEFAULT 0,
    marked_by_flight INT,
    marked_by_player1 VARCHAR(255),
    marked_by_player2 VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_event_flight (event_id, flight)
)";

$conn->query($createTableSql);

$teeboxes = [45, 50, 52, 56, 58, 60];
$epholes_par = [];
$epholes_index = [];
$players = [];

// Get event groupType
$groupType = 'Flights'; // default
if ($EventId) {
    $eventSql = "SELECT groupType FROM Events WHERE 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';
    }
    $eventStmt->close();
}

// Get the pair parameter from URL
$pairParam = $_GET['pair'] ?? '';

// Get flights data for pairs events
$flights = [];
if ($EventId && $groupType === 'Pairs') {
    
    $flightSql = "SELECT 
        flight,
        CASE 
            WHEN eu.GuestId IS NOT NULL THEN COALESCE(eu.otherClub, 'Guest Club')
            ELSE 'El Paraiso'
        END as club_name,
        GROUP_CONCAT(
            CONCAT(COALESCE(Guests.name, Users.name), '|', 
                   COALESCE(Guests.gender, Users.gender), '|',
                   COALESCE(Guests.handicap, Users.handicap), '|',
                   eu.id
            ) SEPARATOR '||'
        ) as players_data
    FROM EventUsers eu 
    LEFT JOIN Users ON eu.UserId = Users.id 
    LEFT JOIN Guests ON eu.GuestId = Guests.id 
    WHERE eu.EventId = ?";
    
    // Add pair filtering if pair parameter is provided
    if (!empty($pairParam)) {
        $flightSql .= " AND COALESCE(eu.otherClub, 'El Paraiso') = ?";
    }
    
    $flightSql .= " GROUP BY flight, club_name ORDER BY flight";
    
    $flightStmt = $conn->prepare($flightSql);
    if (!empty($pairParam)) {
        $flightStmt->bind_param("is", $EventId, $pairParam);
    } else {
        $flightStmt->bind_param("i", $EventId);
    }
    $flightStmt->execute();
    $flightResult = $flightStmt->get_result();
    while ($row = $flightResult->fetch_assoc()) {
        $flights[] = $row;
    }
    $flightStmt->close();
}

// Get current pair data for pairs events
$currentPairData = null;
if ($EventId && $flight && $pairParam) {
    $pairSql = "SELECT 
        COALESCE(Guests.name, Users.name) AS name,
        COALESCE(Guests.gender, Users.gender) AS gender,
        COALESCE(Guests.handicap, Users.handicap) AS handicap,
        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 = ? AND COALESCE(eu.otherClub, 'El Paraiso') = ?
    ORDER BY eu.id";
    
    $pairStmt = $conn->prepare($pairSql);
    $pairStmt->bind_param("iis", $EventId, $flight, $pairParam);
    $pairStmt->execute();
    $pairResult = $pairStmt->get_result();
    
    $currentPairData = [];
    while ($row = $pairResult->fetch_assoc()) {
        // Calculate teebox based on gender
        $gender = $row['gender'] ?? 'M';
        $row['teebox'] = ($gender === 'F') ? 50 : 56;
        
        // Calculate slope using the same logic as the function
        $handicap = floatval($row['handicap'] ?? 0);
        $teebox = $row['teebox'];
        $name = $row['name'] ?? '';
        
        // Use session variables for teebox calculation
        $Men = isset($_SESSION['men']) ? $_SESSION['men'] : 52;
        $Women = isset($_SESSION['women']) ? $_SESSION['women'] : 45;
        
        if ($gender == "F") {
            $teebox = $Women;
        } else {
            $teebox = $Men;
        }
        
        // Calculate slope using ephcp.php logic
        $shotsData = calculatePlayerShots($row, $conn);
        $row['slope'] = $shotsData['slope'] ?? 0;
        $row['teebox'] = $teebox;
        
        $currentPairData[] = $row;
    }
    $pairStmt->close();
}

// Get score status for current pair
$currentPairStatus = 'no_scores';
$currentPairScores = null;
if ($EventId && $flight && $pairParam) {
    $scoreSql = "SELECT * FROM EventScores WHERE eventId = ? AND flight = ? AND club = ?";
    $scoreStmt = $conn->prepare($scoreSql);
    $scoreStmt->bind_param("iis", $EventId, $flight, $pairParam);
    $scoreStmt->execute();
    $scoreResult = $scoreStmt->get_result();
    
    if ($scoreRow = $scoreResult->fetch_assoc()) {
        $currentPairScores = $scoreRow;
        
        // Determine status based on marked field and total_stableford
        if (isset($scoreRow['marked']) && !empty(trim($scoreRow['marked']))) {
            $currentPairStatus = 'confirmed';
        } elseif (isset($scoreRow['total_stableford']) && $scoreRow['total_stableford'] > 0) {
            $currentPairStatus = 'not_confirmed';
        } else {
            $currentPairStatus = 'no_scores';
        }
    }
    $scoreStmt->close();
}

// Function to calculate player shots and slope (same logic as PDF)
function calculatePlayerShots($player, $conn) {
    $handicap = $player['handicap'] ?? 0;
    $gender = $player['gender'] ?? 'M';
    $name = $player['name'] ?? '';
    
    // Use session variables to override teebox values
    $Men = isset($_SESSION['men']) ? $_SESSION['men'] : 52;
    $Women = isset($_SESSION['women']) ? $_SESSION['women'] : 45;
    $percent = isset($_SESSION['percent']) ? $_SESSION['percent'] : 100;
    
    // Set teebox based on gender using session values
    if ($gender == "F") {
        $teebox = $Women; // Use session women value
    } else {
        $teebox = $Men; // Use session men value
    }
    
    $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";
    }
    
    include "ephcp.php";
    if ($gender == "F" && $Shots > 36) {
        $Shots = 36;
    }
    if ($gender == "M" && $Shots > 28) {
        $Shots = 28;
    }
    
    // The slope for asterisk calculation should match the shots value
    // So if player gets 10 shots, we look for slope=10 in slopeshots table
    $slope = $Shots ?? 0;
    
    return ['shots' => ($Shots ?? 0), 'slope' => $slope];
}

// Get par row
$res = $conn->query("SELECT * FROM epholes WHERE type = 'par'");
if ($res && $row = $res->fetch_assoc()) {
    $epholes_par = $row;
}
// Get index row
$res = $conn->query("SELECT * FROM epholes WHERE type = 'index'");
if ($res && $row = $res->fetch_assoc()) {
    $epholes_index = $row;
}
// Get players for this event
if ($EventId) {
    $sql = "SELECT eu.id, COALESCE(Guests.name, Users.name) AS name, eu.tee, COALESCE(Guests.handicap, Users.handicap) AS hcp, COALESCE(Guests.gender, Users.gender) AS gender FROM EventUsers eu LEFT JOIN Users ON eu.UserId = Users.id LEFT JOIN Guests ON eu.GuestId = Guests.id WHERE eu.EventId = $EventId ORDER BY name";
    $res = $conn->query($sql);
    while ($row = $res->fetch_assoc()) {
        $players[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Digital Scorecard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 10px; 
            font-size: 14px; 
            padding: 0;
            background-color: #f5f5f5;
        }
        h1 { margin-bottom: 0; font-size: 18px; }
        .event-name { font-size: 14px; margin-bottom: 20px; }
        .main-container {
            max-width: 100%;
            margin: 0 auto;
            padding: 0 10px;
        }
        .top-controls {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            flex-wrap: wrap;
        }
        .control-group {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 120px;
            flex: 1;
        }
        .control-group label {
            font-weight: bold;
            color: #495057;
            white-space: nowrap;
            font-size: 14px;
        }
        .control-group select {
            min-width: 100px;
            font-size: 14px;
            flex: 1;
        }
        .score-inputs {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            flex-wrap: wrap;
        }
        .score-group {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 120px;
            flex: 1;
        }
        .score-group label {
            font-weight: bold;
            color: #495057;
            white-space: nowrap;
            font-size: 14px;
        }
        .summary-sum {
            font-weight: bold;
            color: #27ae60;
            font-size: 14px;
            font-family: inherit;
        }
        .icon {
            font-size: 14px;
            vertical-align: middle;
        }
        .icon.success { color: #27ae60; }
        .icon.error { color: #e74c3c; }
        .scorecard-table {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 20px;
            width: 100%;
            justify-content: center;
        }
        table {
            border-collapse: collapse;
            margin-bottom: 10px;
            min-width: 280px;
            max-width: 100%;
            background: #fafafa;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            font-size: 14px;
            width: 100%;
        }
        th, td {
            border: 1px solid #aaa;
            padding: 3px 4px;
            text-align: center;
            font-size: 14px;
        }
        th { background: #e0e0e0; }
        .gross-input {
            width: 3em;
            max-width: 3em;
            min-width: 3em;
            text-align: center;
            font-size: 16px;
            font-weight: bold;
        }
        .net-input, .stblf-input {
            width: 3ch;
            max-width: 3ch;
            min-width: 3ch;
            text-align: center;
            font-size: 14px;
        }
        .gross-input-pair {
            width: 3em;
            max-width: 3em;
            min-width: 3em;
            text-align: center;
            font-size: 16px;
            font-weight: bold;
        }
        .net-input-pair, .stblf-input-pair {
            width: 3ch;
            max-width: 3ch;
            min-width: 3ch;
            text-align: center;
            font-size: 14px;
        }
        .check-btn {
            padding: 8px 18px;
            font-size: 14px;
            background: #0074d9;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 20px;
        }
        .check-btn:hover { background: #005fa3; }
        .sum-value {
            font-weight: bold;
            font-size: 14px;
            color: #222;
        }
        @media (max-width: 900px) {
            body { margin: 5px; }
            .main-container { padding: 0 5px; }
            .top-table { font-size: 14px; }
            .scorecard-table { gap: 15px; }
            table { min-width: 250px; }
            .top-controls, .score-inputs {
                padding: 10px;
                gap: 10px;
            }
        }
        @media (max-width: 768px) {
            .scorecard-table { 
                flex-direction: column; 
                gap: 10px; 
            }
            .top-table { font-size: 14px; }
            table { 
                min-width: 0; 
                width: 100%; 
                max-width: 100%;
            }
            th, td {
                padding: 4px 3px;
                font-size: 12px;
            }
            .gross-input, .gross-input-pair {
                width: 3em;
                max-width: 3em;
                min-width: 3em;
                font-size: 16px;
                height: 35px;
            }
            .net-input, .net-input-pair {
                width: 2.5em;
                max-width: 2.5em;
                min-width: 2.5em;
                font-size: 12px;
                height: 30px;
            }
            .stblf-input, .stblf-input-pair {
                width: 2.5em;
                max-width: 2.5em;
                min-width: 2.5em;
                font-size: 12px;
                height: 30px;
            }
            .top-controls, .score-inputs {
                flex-direction: column;
                gap: 10px;
            }
            .control-group, .score-group {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
            .control-group select, .score-group input {
                width: 100%;
                min-width: auto;
            }
        }
        @media (max-width: 480px) {
            body { margin: 2px; font-size: 12px; }
            .main-container { padding: 0 2px; }
            th, td {
                padding: 3px 2px;
                font-size: 11px;
            }
            .gross-input, .gross-input-pair {
                width: 2.5em;
                max-width: 2.5em;
                min-width: 2.5em;
                font-size: 14px;
                height: 32px;
            }
            .net-input, .net-input-pair {
                width: 2em;
                max-width: 2em;
                min-width: 2em;
                font-size: 11px;
                height: 28px;
            }
            .stblf-input, .stblf-input-pair {
                width: 2em;
                max-width: 2em;
                min-width: 2em;
                font-size: 11px;
                height: 28px;
            }
            .top-controls, .score-inputs {
                padding: 8px;
                margin-bottom: 10px;
            }
            .pair-card {
                padding: 10px;
                margin-bottom: 10px;
            }
            .player-details {
                font-size: 10px;
            }
            .summary-table th, .summary-table td {
                padding: 6px 8px;
                font-size: 12px;
            }
            .summary-table input[type="number"],
            .summary-table td[id$="Display"] {
                width: 5ch;
                max-width: 5ch;
                min-width: 5ch;
                font-size: 12px;
            }
        }
        .summary-table-container {
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            overflow-x: auto;
        }
        .summary-table {
            border-collapse: collapse;
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.07);
            border-radius: 8px;
            overflow: hidden;
            font-size: 14px;
            min-width: 300px;
        }
        .summary-table th, .summary-table td {
            border: 1px solid #ccc;
            padding: 8px 16px;
            text-align: center;
            font-size: 14px;
        }
        .summary-table th {
            background: #f8f9fa;
            font-weight: bold;
        }
        .summary-table td {
            background: #f9f9f9;
        }
        .summary-table input[type="number"],
        .summary-table td[id$="Display"] {
            width: 7ch;
            max-width: 7ch;
            min-width: 7ch;
            text-align: center;
            font-size: 14px;
        }
        .summary-table input[readonly],
        .summary-table td[id$="Display"] {
            background: #f0f0f0;
        }
        #playerInfo {
            font-size: 14px;
        }
        #playerInfo h4 {
            font-size: 14px;
        }
        #playerInfo div {
            font-size: 14px;
        }
        .pair-card {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .player-info {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 10px;
        }
        .player-details {
            flex: 1;
            font-size: 11px;
        }
        .status-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            border-left: 4px solid;
        }
        .status-no-scores {
            color: #6c757d;
            background: #f8f9fa;
            border-left-color: #6c757d;
            margin: 0;
            font-weight: normal;
        }
        .status-not-confirmed {
            color: #856404;
            background: #fff3cd;
            border-left-color: #ffc107;
            margin: 0;
            font-weight: bold;
        }
        .status-confirmed {
            color: #155724;
            background: #d4edda;
            border-left-color: #28a745;
            margin: 0;
            font-weight: bold;
        }
        
        /* Mobile touch improvements */
        @media (max-width: 768px) {
            .gross-input, .gross-input-pair, .net-input, .net-input-pair, .stblf-input, .stblf-input-pair {
                -webkit-appearance: none;
                -moz-appearance: none;
                appearance: none;
                border: 2px solid #ddd;
                border-radius: 4px;
                touch-action: manipulation;
            }
            .gross-input:focus, .gross-input-pair:focus {
                border-color: #007bff;
                outline: none;
                box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
            }
            .check-btn {
                width: 100%;
                padding: 12px;
                font-size: 16px;
                margin: 10px 0;
            }
            .pair-card h4 {
                font-size: 1.1rem;
                margin-bottom: 10px;
            }
        }
        
        /* Landscape mobile optimization */
        @media (max-width: 768px) and (orientation: landscape) {
            .scorecard-table {
                flex-direction: row;
                gap: 10px;
            }
            table {
                min-width: 200px;
                max-width: 50%;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid px-2 py-2">
        <div class="text-center mb-3">
            <img src="logo.webp" alt="Logo" class="img-fluid" style="max-height: 60px;">
            <h2 style="font-size: 1.5rem; margin: 10px 0;">El Paraiso Event Register</h2>
            <h5 class="text-muted" style="font-size: 1rem; margin: 0;">Mixed Interclub</h5>
        </div>

        <!-- Current Pair Information -->
        <?php if ($currentPairData && count($currentPairData) >= 2): ?>
        <div class="pair-card">
            <h4>Current Pair - <?= htmlspecialchars($pairParam) ?></h4>
            <div class="player-info">
                <div class="player-details">
                    <strong>Player 1:</strong> <?= htmlspecialchars($currentPairData[0]['name']) ?> 
                    (<?= htmlspecialchars($currentPairData[0]['gender']) ?>) - 
                    HCP: <?= htmlspecialchars($currentPairData[0]['handicap']) ?> - 
                    Slope: <?= htmlspecialchars($currentPairData[0]['slope']) ?> - 
                    Teebox: <?= htmlspecialchars($currentPairData[0]['teebox']) ?>
                </div>
                <div class="player-details">
                    <strong>Player 2:</strong> <?= htmlspecialchars($currentPairData[1]['name']) ?> 
                    (<?= htmlspecialchars($currentPairData[1]['gender']) ?>) - 
                    HCP: <?= htmlspecialchars($currentPairData[1]['handicap']) ?> - 
                    Slope: <?= htmlspecialchars($currentPairData[1]['slope']) ?> - 
                    Teebox: <?= htmlspecialchars($currentPairData[1]['teebox']) ?>
                </div>
            </div>
            
            <!-- Current Pair Status inside the card -->
            <div class="status-message">
                <?php if ($currentPairStatus === 'no_scores'): ?>
                    <p class="status-no-scores">❌ No scores registered yet</p>
                <?php elseif ($currentPairStatus === 'not_confirmed'): ?>
                    <p class="status-not-confirmed">⚠️ Scores registered, but not confirmed yet</p>
                    <?php if ($currentPairScores): ?>
                        <div class="scores-display">
                            <p><strong>Front 9:</strong> <?= $currentPairScores['front9_stableford'] ?? 'N/A' ?> | <strong>Back 9:</strong> <?= $currentPairScores['back9_stableford'] ?? 'N/A' ?> | <strong>Total:</strong> <?= $currentPairScores['total_stableford'] ?? 'N/A' ?></p>
                        </div>
                    <?php endif; ?>
                <?php elseif ($currentPairStatus === 'confirmed'): ?>
                    <p class="status-confirmed">✅ Scores registered and confirmed</p>
                    <?php if ($currentPairScores): ?>
                        <div class="scores-display">
                            <p><strong>Total Stableford:</strong> <?= $currentPairScores['total_stableford'] ?? 'N/A' ?></p>
                            <p><strong>Front 9:</strong> <?= $currentPairScores['front9_stableford'] ?? 'N/A' ?> | <strong>Back 9:</strong> <?= $currentPairScores['back9_stableford'] ?? 'N/A' ?></p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Separator line between Current Pair and Other Pair -->
        <div style="width: 100%; height: 2px; background: linear-gradient(to right, #ddd, #999, #ddd); margin: 30px 0; border-radius: 1px;"></div>

        <!-- Always show other pair information for pairs events -->
        <?php if ($groupType === 'Pairs' && $currentPairData && count($currentPairData) >= 2): ?>
        <?php
        // Get other pair data
        $otherPairClub = ($pairParam === 'El Paraiso') ? 'La Hacienda' : 'El Paraiso';
        $otherPairData = null;
        if ($EventId && $flight && $otherPairClub) {
            $otherPairSql = "SELECT 
                COALESCE(Guests.name, Users.name) AS name,
                COALESCE(Guests.gender, Users.gender) AS gender,
                COALESCE(Guests.handicap, Users.handicap) AS handicap,
                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 = ? AND COALESCE(eu.otherClub, 'El Paraiso') = ?
            ORDER BY eu.id";
            
            $otherPairStmt = $conn->prepare($otherPairSql);
            $otherPairStmt->bind_param("iis", $EventId, $flight, $otherPairClub);
            $otherPairStmt->execute();
            $otherPairResult = $otherPairStmt->get_result();
            
            $otherPairData = [];
            while ($row = $otherPairResult->fetch_assoc()) {
                // Calculate teebox based on gender
                $gender = $row['gender'] ?? 'M';
                $row['teebox'] = ($gender === 'F') ? 50 : 56;
                
                // Calculate slope using the same logic as the function
                $handicap = floatval($row['handicap'] ?? 0);
                $teebox = $row['teebox'];
                $name = $row['name'] ?? '';
                
                // Use session variables for teebox calculation
                $Men = isset($_SESSION['men']) ? $_SESSION['men'] : 52;
                $Women = isset($_SESSION['women']) ? $_SESSION['women'] : 45;
                
                if ($gender == "F") {
                    $teebox = $Women;
                } else {
                    $teebox = $Men;
                }
                
                // Calculate slope using ephcp.php logic
                $shotsData = calculatePlayerShots($row, $conn);
                $row['slope'] = $shotsData['slope'] ?? 0;
                $row['teebox'] = $teebox;
                
                $otherPairData[] = $row;
            }
            $otherPairStmt->close();
        }

        // Get score status for other pair
        $otherPairStatus = 'no_scores';
        $otherPairScores = null;
        if ($EventId && $flight && $otherPairClub) {
            $otherScoreSql = "SELECT * FROM EventScores WHERE eventId = ? AND flight = ? AND club = ?";
            $otherScoreStmt = $conn->prepare($otherScoreSql);
            $otherScoreStmt->bind_param("iis", $EventId, $flight, $otherPairClub);
            $otherScoreStmt->execute();
            $otherScoreResult = $otherScoreStmt->get_result();
            
            if ($otherScoreRow = $otherScoreResult->fetch_assoc()) {
                $otherPairScores = $otherScoreRow;
                
                // Determine status based on marked field and total_stableford
                if (isset($otherScoreRow['marked']) && !empty(trim($otherScoreRow['marked']))) {
                    $otherPairStatus = 'confirmed';
                } elseif (isset($otherScoreRow['total_stableford']) && $otherScoreRow['total_stableford'] > 0) {
                    $otherPairStatus = 'not_confirmed';
                } else {
                    $otherPairStatus = 'no_scores';
                }
            }
            $otherScoreStmt->close();
        }
        ?>
        
        <!-- Other Pair card will be moved to bottom of page -->
        <?php endif; ?>

    <div class="main-container">
        <form id="scorecardForm">
        <?php if ($groupType !== 'Pairs'): ?>
        <div class="top-controls">
            <div class="control-group">
                <label for="playerSelect">Player:</label>
                <select id="playerSelect">
                    <option value="">-- Select Player --</option>
                    <?php foreach ($players as $p): ?>
                        <option value="<?= htmlspecialchars($p['id']) ?>" 
                                data-handicap="<?= htmlspecialchars($p['hcp']) ?>"
                                data-gender="<?= htmlspecialchars($p['gender']) ?>"
                                data-name="<?= htmlspecialchars($p['name']) ?>"
                                data-flight="<?= htmlspecialchars($p['flight'] ?? '') ?>"
                                data-tee="<?= htmlspecialchars($p['tee'] ?? '') ?>">
                            <?= htmlspecialchars($p['name']) ?> (Flight <?= htmlspecialchars($p['flight'] ?? 'N/A') ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="control-group" id="markerSelectGroup" style="display: none;">
                <label for="markerSelect">Marker:</label>
                <select id="markerSelect">
                    <option value="">-- Select Marker --</option>
                </select>
            </div>
            
            <!-- Individual Player Info -->
            <div id="individualPlayerInfo" style="display: none; margin-top: 20px; background: #f8f9fa; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h4 style="margin-top: 0; color: #495057;">Player Information</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div>
                        <strong>Name:</strong> <span id="individualPlayerName">-</span><br>
                        <strong>Gender:</strong> <span id="individualPlayerGender">-</span><br>
                        <strong>Handicap:</strong> <span id="individualPlayerHcp">-</span><br>
                        <strong>Slope:</strong> <span id="playerSlope">-</span>
                    </div>
                    <div>
                        <strong>Flight:</strong> <span id="individualPlayerFlight">-</span><br>
                        <strong>Tee:</strong> <span id="individualPlayerTee">-</span><br>
                        <strong>Marker:</strong> <span id="individualPlayerMarker">-</span>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
        

        <!-- Only show registration totals card when no scores are registered -->
        <?php if ($currentPairStatus === 'no_scores'): ?>
        <div class="summary-table-container">
            <table class="summary-table" id="scoreSummaryTable">
                <tr>
                    <th></th>
                    <th>Front 9</th>
                    <th>Back 9</th>
                    <th>Total</th>
                </tr>
                <tr>
                    <td>My sum</td>
                    <td><input type="number" id="grossFront9" min="0" tabindex="1" style="width: 7ch; max-width: 7ch; min-width: 7ch; text-align: center; font-size: 14px;"></td>
                    <td><input type="number" id="grossBack9" min="0" tabindex="2" style="width: 7ch; max-width: 7ch; min-width: 7ch; text-align: center; font-size: 14px;"></td>
                    <td id="grossTotalDisplay" style="width: 7ch; max-width: 7ch; min-width: 7ch; text-align: center; font-size: 14px; background: #f0f0f0;">0</td>
                </tr>
                <tr>
                    <td>Gross</td>
                    <td id="actualGrossFront9">0</td>
                    <td id="actualGrossBack9">0</td>
                    <td id="actualGrossTotal">0</td>
                </tr>
                <tr>
                    <td>Net</td>
                    <td id="actualNetFront9">0</td>
                    <td id="actualNetBack9">0</td>
                    <td id="actualNetTotal">0</td>
                </tr>
                <tr>
                    <td>Stableford</td>
                    <td id="actualStblfFront9">0</td>
                    <td id="actualStblfBack9">0</td>
                    <td id="actualStblfTotal">0</td>
                </tr>
            </table>
        </div>
        <?php endif; ?>

        <!-- Wrap the score entry table and check scores button -->
        <div id="scoreEntrySection">
            <!-- Only show Check Scores button when no scores are registered -->
            <?php if ($currentPairStatus === 'no_scores'): ?>
            <button id="newCheckBtn" class="check-btn" type="button">Check Scores</button>
            <!-- Only show score entry tables when no scores are registered -->
            <div class="score-inputs">
                <div class="score-group">
                    <!-- Score entry table(s) start here -->
                    <table id="front9Table">
                        <tr><th colspan="9">Holes 1-9</th></tr>
                        <tr><th colspan="3"></th><th colspan="3" style="text-align: center; background-color: #e9ecef;" class="individual-header">Player</th><th colspan="3" style="text-align: center; background-color: #fff3cd;" class="pairs-header">Player 2</th></tr>
                        <tr><th>Hole</th><th>Par</th><th>Index</th><th class="individual-header">Gross</th><th class="individual-header">Net</th><th class="individual-header">Stblf</th><th class="pairs-header">Gross</th><th class="pairs-header">Net</th><th class="pairs-header">Stblf</th></tr>
                        <tbody id="front9Rows"></tbody>
                    </table>
                    <table id="back9Table">
                        <tr><th colspan="9">Holes 10-18</th></tr>
                        <tr><th colspan="3"></th><th colspan="3" style="text-align: center; background-color: #e9ecef;" class="individual-header">Player</th><th colspan="3" style="text-align: center; background-color: #fff3cd;" class="pairs-header">Player 2</th></tr>
                        <tr><th>Hole</th><th>Par</th><th>Index</th><th class="individual-header">Gross</th><th class="individual-header">Net</th><th class="individual-header">Stblf</th><th class="pairs-header">Gross</th><th class="pairs-header">Net</th><th class="pairs-header">Stblf</th></tr>
                        <tbody id="back9Rows"></tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Player Info Section for Pairs -->
        <div id="playerInfo" style="display: none; margin-top: 20px; background: #f8f9fa; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <h4 style="margin-top: 0; color: #495057;">Flight Information</h4>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <strong>Club:</strong> <span id="clubName">-</span><br>
                    <strong>Player 1:</strong> <span id="player1Name">-</span> (<span id="player1Gender">-</span>) - HCP: <span id="player1Hcp">-</span> - Teebox: <span id="player1Teebox">-</span> - Slope: <span id="player1Slope">-</span>
                </div>
                <div>
                    <strong>Player 2:</strong> <span id="player2Name">-</span> (<span id="player2Gender">-</span>) - HCP: <span id="player2Hcp">-</span> - Teebox: <span id="player2Teebox">-</span> - Slope: <span id="player2Slope">-</span>
                </div>
            </div>
        </div>
        
        <!-- Save Scores Section removed - scores are auto-saved when matched -->
        
        <!-- Flight Verification Section -->
        <div id="flightVerificationSection" style="display: none; margin-top: 20px;">
            <!-- Flight verification info will be displayed here -->
        </div>
        
        <!-- Other Flights Scores -->
        <div id="otherFlightsSection" style="display: none; margin-top: 30px; background: #f8f9fa; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <h3 style="margin-top: 0; color: #495057;">Other Flights - Marked</h3>
            <div id="otherFlightsList"></div>
        </div>
        
        <!-- Add marker flight info section -->
        <div id="markerFlightSection"></div>
        
        <!-- Other Pair Information - Moved to bottom -->
        <?php if ($groupType === 'Pairs' && $otherPairData && count($otherPairData) >= 2): ?>
        <div class="pair-card" style="margin-top: 30px; border: 2px solid #6c757d;">
            <h4>Other Pair - <?= htmlspecialchars($otherPairClub) ?></h4>
            <div class="player-info">
                <div class="player-details">
                    <strong>Player 1:</strong> <?= htmlspecialchars($otherPairData[0]['name']) ?> 
                    (<?= htmlspecialchars($otherPairData[0]['gender']) ?>) - 
                    HCP: <?= htmlspecialchars($otherPairData[0]['handicap']) ?> - 
                    Slope: <?= htmlspecialchars($otherPairData[0]['slope']) ?> - 
                    Teebox: <?= htmlspecialchars($otherPairData[0]['teebox']) ?>
                </div>
                <div class="player-details">
                    <strong>Player 2:</strong> <?= htmlspecialchars($otherPairData[1]['name']) ?> 
                    (<?= htmlspecialchars($otherPairData[1]['gender']) ?>) - 
                    HCP: <?= htmlspecialchars($otherPairData[1]['handicap']) ?> - 
                    Slope: <?= htmlspecialchars($otherPairData[1]['slope']) ?> - 
                    Teebox: <?= htmlspecialchars($otherPairData[1]['teebox']) ?>
                </div>
            </div>
            
            <!-- Other Pair Status inside the card -->
            <div class="status-message">
                <?php if ($otherPairStatus === 'no_scores'): ?>
                    <p class="status-no-scores">❌ No scores registered yet</p>
                <?php elseif ($otherPairStatus === 'not_confirmed'): ?>
                    <p class="status-not-confirmed">⚠️ Scores registered, but not confirmed yet</p>
                    <?php if ($otherPairScores): ?>
                        <div class="scores-display">
                            <p><strong>Front 9:</strong> <?= $otherPairScores['front9_stableford'] ?? 'N/A' ?> | <strong>Back 9:</strong> <?= $otherPairScores['back9_stableford'] ?? 'N/A' ?> | <strong>Total:</strong> <?= $otherPairScores['total_stableford'] ?? 'N/A' ?></p>
                        </div>
                        <!-- Confirm Now Button -->
                        <button onclick="confirmOtherPairScores()" style="background: #28a745; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin-top: 15px; font-size: 16px; font-weight: bold;">
                            Confirm Now
                        </button>
                    <?php endif; ?>
                <?php elseif ($otherPairStatus === 'confirmed'): ?>
                    <p class="status-confirmed">✅ Scores registered and confirmed</p>
                    <?php if ($otherPairScores): ?>
                        <div class="scores-display">
                            <p><strong>Total Stableford:</strong> <?= $otherPairScores['total_stableford'] ?? 'N/A' ?></p>
                            <p><strong>Front 9:</strong> <?= $otherPairScores['front9_stableford'] ?? 'N/A' ?> | <strong>Back 9:</strong> <?= $otherPairScores['back9_stableford'] ?? 'N/A' ?></p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script>
        // Epholes data from PHP
        const epholes_par = <?php echo json_encode($epholes_par); ?>;
        const epholes_index = <?php echo json_encode($epholes_index); ?>;
        const teeboxes = <?php echo json_encode($teeboxes); ?>;
        const players = <?php echo json_encode($players); ?>;
        const groupType = '<?php echo $groupType; ?>';
        const isPairs = groupType === 'Pairs';
        console.log('groupType:', groupType);
        console.log('isPairs:', isPairs);
        const currentFlight = '<?php echo $flight; ?>';
        const markerFlight = <?php echo $markerFlight; ?>;
        const eventId = <?php echo $EventId; ?>;

        // Function to enable/disable data entry
        function setDataEntryEnabled(enabled) {
            // Enable/disable gross inputs
            document.querySelectorAll('.gross-input, .gross-input-pair').forEach(input => {
                input.disabled = !enabled;
                input.style.backgroundColor = enabled ? '' : '#f5f5f5';
                input.style.cursor = enabled ? '' : 'not-allowed';
            });
            
            // Front 9 and Back 9 inputs should always be enabled
            document.getElementById('grossFront9').disabled = false;
            document.getElementById('grossBack9').disabled = false;
            document.getElementById('grossFront9').style.backgroundColor = '';
            document.getElementById('grossBack9').style.backgroundColor = '';
            document.getElementById('grossFront9').style.cursor = '';
            document.getElementById('grossBack9').style.cursor = '';
            
            // Enable/disable check button based on whether we have scores entered
            updateCheckButtonState();
        }
        
        // Function to update check button state based on score entries
        function updateCheckButtonState() {
            const checkBtn = document.getElementById('newCheckBtn');
            if (!checkBtn) return;
            
            // Check if we have any scores entered
            const hasScores = Array.from(document.querySelectorAll('.gross-input, .gross-input-pair')).some(input => 
                input.value && input.value.trim() !== '' && parseInt(input.value) > 0
            );
            
            // Also check if Front 9 and Back 9 totals are entered
            const front9Total = document.getElementById('grossFront9').value;
            const back9Total = document.getElementById('grossBack9').value;
            const hasTotals = (front9Total && parseInt(front9Total) > 0) || (back9Total && parseInt(back9Total) > 0);
            
            let shouldEnable = hasScores || hasTotals;
            
            // For singles events, also check if marker is selected
            if (groupType !== 'Pairs') {
                const markerSelect = document.getElementById('markerSelect');
                const playerSelect = document.getElementById('playerSelect');
                const hasPlayer = playerSelect && playerSelect.value !== '';
                const hasMarker = markerSelect && markerSelect.value !== '';
                shouldEnable = shouldEnable && hasPlayer && hasMarker;
            }
            
            checkBtn.disabled = !shouldEnable;
            checkBtn.style.backgroundColor = shouldEnable ? '#0074d9' : '#ccc';
            checkBtn.style.cursor = shouldEnable ? 'pointer' : 'not-allowed';
        }
        
        // Initially disable gross inputs but keep Front 9 and Back 9 enabled
        setDataEntryEnabled(false);
        
        // For pairs events, enable the check button if we have current pair data
        if (isPairs && currentFlight && currentFlight !== '0' && currentFlight !== '') {
            setTimeout(() => {
                updateCheckButtonState();
            }, 500);
        }
        
        // Auto-load players for Pairs events
        function autoLoadPairsPlayers() {
            console.log('Auto-loading pairs players...');
            console.log('isPairs:', isPairs);
            console.log('currentFlight:', currentFlight);
            console.log('flightData:', <?php echo json_encode($flights); ?>);
            
            if (isPairs && currentFlight && currentFlight !== '0' && currentFlight !== '') {
                // Find the flight data
                const flightData = <?php echo json_encode($flights); ?>;
                const selectedFlight = flightData.find(f => f.flight == currentFlight);
                
                console.log('selectedFlight:', selectedFlight);
                console.log('Available flights:', flightData.map(f => f.flight));
                
                if (selectedFlight) {
                    const playersData = selectedFlight.players_data;
                    const clubName = selectedFlight.club_name;
                    const players = playersData.split('||');
                    
                    if (players.length >= 2) {
                        // Parse player 1 data
                        const player1Data = players[0].split('|');
                        const player2Data = players[1].split('|');
                        
                        // Display club name
                        document.getElementById('clubName').textContent = clubName || '-';
                        
                        // Display player information
                        document.getElementById('player1Name').textContent = player1Data[0] || '-';
                        document.getElementById('player1Gender').textContent = player1Data[1] || '-';
                        document.getElementById('player1Hcp').textContent = player1Data[2] || '-';
                        
                        document.getElementById('player2Name').textContent = player2Data[0] || '-';
                        document.getElementById('player2Gender').textContent = player2Data[1] || '-';
                        document.getElementById('player2Hcp').textContent = player2Data[2] || '-';
                        
                        // Populate current pair card
                        document.getElementById('currentPairClub').textContent = clubName || '-';
                        document.getElementById('currentPlayer1Name').textContent = player1Data[0] || '-';
                        document.getElementById('currentPlayer1Gender').textContent = player1Data[1] || '-';
                        document.getElementById('currentPlayer1Hcp').textContent = player1Data[2] || '-';
                        document.getElementById('currentPlayer1Tee').textContent = teebox1;
                        document.getElementById('currentPlayer2Name').textContent = player2Data[0] || '-';
                        document.getElementById('currentPlayer2Gender').textContent = player2Data[1] || '-';
                        document.getElementById('currentPlayer2Hcp').textContent = player2Data[2] || '-';
                        document.getElementById('currentPlayer2Tee').textContent = teebox2;
                        
                        // Show player info section
                        document.getElementById('playerInfo').style.display = 'block';
                        
                        // Calculate slopes for both players with default teebox values
                        const gender1 = player1Data[1] || 'M';
                        const gender2 = player2Data[1] || 'M';
                        const teebox1 = gender1 === 'F' ? 50 : 56;
                        const teebox2 = gender2 === 'F' ? 50 : 56;
                        
                        // Calculate slope for player 1
                        const handicap1 = parseFloat(player1Data[2]) || 0;
                        calculateSlopeForPlayer(handicap1, gender1, teebox1, 'player1Slope');
                        
                        // Calculate slope for player 2
                        const handicap2 = parseFloat(player2Data[2]) || 0;
                        calculateSlopeForPlayer(handicap2, gender2, teebox2, 'player2Slope');
                        
                        // Set teebox info
                        document.getElementById('player1Teebox').textContent = teebox1;
                        document.getElementById('player2Teebox').textContent = teebox2;
                        
                        // Enable data entry
                        setDataEntryEnabled(true);
                        
                        // Enable the check button
                        const checkBtn = document.getElementById('newCheckBtn');
                        if (checkBtn) {
                            checkBtn.disabled = false;
                            checkBtn.style.backgroundColor = '#0074d9';
                            checkBtn.style.cursor = 'pointer';
                        }
                        
                        // Setup single score per hole logic
                        setupSingleScorePerHole();
                    }
                }
            }
        }
        
        // Initialize pairs display based on groupType
        function initializePairsDisplay() {
            const pairsColumns = document.querySelectorAll('.pairs-column');
            const pairsInputs = document.querySelectorAll('.gross-input-pair, .net-input-pair, .stblf-input-pair');
            const pairsHeaders = document.querySelectorAll('.pairs-header');
            const individualHeaders = document.querySelectorAll('.individual-header');
            
            pairsColumns.forEach(col => {
                col.style.display = isPairs ? '' : 'none';
            });
            
            pairsInputs.forEach(input => {
                input.style.display = isPairs ? '' : 'none';
                if (!isPairs) {
                    input.value = '';
                }
            });
            
            // Update header display
            pairsHeaders.forEach(header => {
                header.style.display = isPairs ? '' : 'none';
            });
            
            individualHeaders.forEach(header => {
                header.style.display = isPairs ? 'none' : '';
            });
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            initializePairsDisplay();
            
            // Auto-load players for Pairs events
            if (isPairs) {
                console.log('Calling autoLoadPairsPlayers...');
                autoLoadPairsPlayers();
                
                // Always show other pair information for pairs events
                showOtherPairInfo();
            }
            
            // Check flight status for verification
            checkFlightStatus();
            
            // Setup single score per hole after tables are created
            setTimeout(() => {
                setupSingleScorePerHole();
            }, 100);
        });
        
        // Player dropdown logic
        const playerSelect = document.getElementById('playerSelect');
        if (playerSelect) {
            playerSelect.addEventListener('change', function() {
            const selectedValue = this.value;
            const isPairs = groupType === 'Pairs';
            
            if (isPairs) {
                // Handle flight selection for pairs
                if (selectedValue) {
                    const selectedOption = this.options[this.selectedIndex];
                    const playersData = selectedOption.getAttribute('data-players');
                    const clubName = selectedOption.getAttribute('data-club');
                    const players = playersData.split('||');
                    
                    if (players.length >= 2) {
                        // Parse player 1 data
                        const player1Data = players[0].split('|');
                        const player2Data = players[1].split('|');
                        
                        // Display club name
                        document.getElementById('clubName').textContent = clubName || '-';
                        
                        // Display player information
                        document.getElementById('player1Name').textContent = player1Data[0] || '-';
                        document.getElementById('player1Gender').textContent = player1Data[1] || '-';
                        document.getElementById('player1Hcp').textContent = player1Data[2] || '-';
                        
                        document.getElementById('player2Name').textContent = player2Data[0] || '-';
                        document.getElementById('player2Gender').textContent = player2Data[1] || '-';
                        document.getElementById('player2Hcp').textContent = player2Data[2] || '-';
                        
                        // Populate current pair card
                        document.getElementById('currentPairClub').textContent = clubName || '-';
                        document.getElementById('currentPlayer1Name').textContent = player1Data[0] || '-';
                        document.getElementById('currentPlayer1Gender').textContent = player1Data[1] || '-';
                        document.getElementById('currentPlayer1Hcp').textContent = player1Data[2] || '-';
                        document.getElementById('currentPlayer1Tee').textContent = teebox1;
                        document.getElementById('currentPlayer2Name').textContent = player2Data[0] || '-';
                        document.getElementById('currentPlayer2Gender').textContent = player2Data[1] || '-';
                        document.getElementById('currentPlayer2Hcp').textContent = player2Data[2] || '-';
                        document.getElementById('currentPlayer2Tee').textContent = teebox2;
                        
                        // Show player info section
                        document.getElementById('playerInfo').style.display = 'block';
                        
                        // Calculate slopes for both players with default teebox values
                        const gender1 = player1Data[1] || 'M';
                        const gender2 = player2Data[1] || 'M';
                        const teebox1 = gender1 === 'F' ? 50 : 56;
                        const teebox2 = gender2 === 'F' ? 50 : 56;
                        
                        // Calculate slope for player 1
                        const handicap1 = parseFloat(player1Data[2]) || 0;
                        calculateSlopeForPlayer(handicap1, gender1, teebox1, 'player1Slope');
                        
                        // Calculate slope for player 2
                        const handicap2 = parseFloat(player2Data[2]) || 0;
                        calculateSlopeForPlayer(handicap2, gender2, teebox2, 'player2Slope');
                        
                        // Set teebox info
                        document.getElementById('player1Teebox').textContent = teebox1;
                        document.getElementById('player2Teebox').textContent = teebox2;
                        
                        // Enable data entry
                        setDataEntryEnabled(true);
                        
                        // Setup single score per hole logic
                        setupSingleScorePerHole();
                    }
                } else {
                    // Hide player info when no flight selected
                    document.getElementById('playerInfo').style.display = 'none';
                    setDataEntryEnabled(false);
                }
            } else {
                // Handle individual player selection for singles
                const player = players.find(p => p.id === selectedValue);
                if (player) {
                    // Display individual player information
                    document.getElementById('individualPlayerName').textContent = player.name || '-';
                    document.getElementById('individualPlayerGender').textContent = player.gender || '-';
                    document.getElementById('individualPlayerHcp').textContent = player.hcp || '-';
                    document.getElementById('individualPlayerFlight').textContent = player.flight || '-';
                    document.getElementById('individualPlayerTee').textContent = player.tee || '-';
                    
                    // Show individual player info section
                    document.getElementById('individualPlayerInfo').style.display = 'block';
                    
                    // Show marker selection group
                    document.getElementById('markerSelectGroup').style.display = 'flex';
                    
                    // Load other players in the same flight as potential markers
                    loadMarkersForPlayer(player);
                    
                    // Calculate slope for individual player
                    const gender = player.gender || 'M';
                    const teebox = gender === 'F' ? 50 : 56;
                    const handicap = parseFloat(player.hcp) || 0;
                    calculateSlopeForPlayer(handicap, gender, teebox, 'playerSlope');
                    
                    // Enable data entry after player is selected
                    setDataEntryEnabled(true);
                } else {
                    // Hide individual player info when no player selected
                    document.getElementById('individualPlayerInfo').style.display = 'none';
                    document.getElementById('markerSelectGroup').style.display = 'none';
                    // Disable data entry when no player is selected
                    setDataEntryEnabled(false);
                }
            }
            
            // Clear all gross values when selection changes
            document.querySelectorAll('.gross-input').forEach(input => { input.value = ''; });
            document.querySelectorAll('.gross-input-pair').forEach(input => { input.value = ''; });
            document.getElementById('grossFront9').value = 0;
            document.getElementById('grossBack9').value = 0;
            // Recalculate net for all holes
            calculateNetAll();
        });
        }
        
        // Marker selection logic for singles
        const markerSelect = document.getElementById('markerSelect');
        if (markerSelect) {
            markerSelect.addEventListener('change', function() {
                const selectedMarkerId = this.value;
                const selectedMarker = players.find(p => p.id === selectedMarkerId);
                
                if (selectedMarker) {
                    document.getElementById('individualPlayerMarker').textContent = selectedMarker.name || '-';
                } else {
                    document.getElementById('individualPlayerMarker').textContent = '-';
                }
                
                // Update check button state when marker selection changes
                updateCheckButtonState();
            });
        }
        
        // Function to load potential markers for a player (other players in same flight)
        function loadMarkersForPlayer(player) {
            const markerSelect = document.getElementById('markerSelect');
            markerSelect.innerHTML = '<option value="">-- Select Marker --</option>';
            
            if (player && player.flight) {
                // Find other players in the same flight
                const otherPlayers = players.filter(p => 
                    p.id !== player.id && 
                    p.flight === player.flight
                );
                
                otherPlayers.forEach(marker => {
                    const option = document.createElement('option');
                    option.value = marker.id;
                    option.textContent = marker.name + ' (HCP: ' + marker.hcp + ')';
                    markerSelect.appendChild(option);
                });
                
                if (otherPlayers.length === 0) {
                    const option = document.createElement('option');
                    option.value = '';
                    option.textContent = 'No other players in this flight';
                    option.disabled = true;
                    markerSelect.appendChild(option);
                }
            }
        }
        
        // Function to calculate slope for a specific player
        function calculateSlopeForPlayer(handicap, gender, teebox, elementId) {
            fetch(`event-slope-update.php?handicap=${handicap}&gender=${gender}&teebox=${teebox}&name=${encodeURIComponent('Player')}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById(elementId).textContent = data.slope;
                        console.log(`Slope calculated for ${elementId}:`, data.slope);
                        
                        // Also update current pair card slopes
                        if (elementId === 'player1Slope') {
                            document.getElementById('currentPlayer1Slope').textContent = data.slope;
                        } else if (elementId === 'player2Slope') {
                            document.getElementById('currentPlayer2Slope').textContent = data.slope;
                        }
                        
                        // Don't trigger calculations immediately - wait for tables to be ready
                    } else {
                        console.error('Error getting slope:', data);
                    }
                })
                .catch(error => {
                    console.error('Error fetching slope:', error);
                    // Fallback to simplified calculation
                    let shots = Math.round(handicap * 0.8);
                    if (gender === "F" && shots > 36) shots = 28;
                    if (gender === "M" && shots > 28) shots = 28;
                    document.getElementById(elementId).textContent = shots;
                    console.log(`Fallback slope calculated for ${elementId}:`, shots);
                    
                    // Also update current pair card slopes
                    if (elementId === 'player1Slope') {
                        document.getElementById('currentPlayer1Slope').textContent = shots;
                    } else if (elementId === 'player2Slope') {
                        document.getElementById('currentPlayer2Slope').textContent = shots;
                    }
                    
                    // Don't trigger calculations immediately - wait for tables to be ready
                });
        }

        // Generate rows for holes 1-9 and 10-18
        function createRows(start, end, tbodyId) {
            const tbody = document.getElementById(tbodyId);
            for (let i = start; i <= end; i++) {
                const tr = document.createElement('tr');
                const tabindex = i === 1 ? 3 : ''; // Set tabindex=3 for H1 gross input
                tr.innerHTML = `<td>H${i}</td>
                    <td class="par-cell">${epholes_par[`h${i}`] ? epholes_par[`h${i}`] : '-'}</td>
                    <td class="index-cell">${epholes_index[`h${i}`] ? epholes_index[`h${i}`] : '-'}</td>
                    <td class="individual-header"><input type="number" min="1" max="9" class="gross-input" data-hole="${i}" ${tabindex ? `tabindex="${tabindex}"` : ''}></td>
                    <td class="individual-header"><input type="text" class="net-input" data-hole="${i}" style="background:#f0f0f0;" value="" readonly></td>
                    <td class="individual-header"><input type="text" class="stblf-input" data-hole="${i}" style="background:#f0f0f0;" value="" readonly></td>
                    <td class="pairs-header"><input type="number" min="1" max="9" class="gross-input-pair" data-hole="${i}" style="display:none;"></td>
                    <td class="pairs-header"><input type="text" class="net-input-pair" data-hole="${i}" style="background:#f0f0f0; display:none;" value="" readonly></td>
                    <td class="pairs-header"><input type="text" class="stblf-input-pair" data-hole="${i}" style="background:#f0f0f0; display:none;" value="" readonly></td>`;
                tbody.appendChild(tr);
                
                // Get references to the input fields
                const netInput = tr.querySelector('.net-input');
                const stblfInput = tr.querySelector('.stblf-input');
                const netInputPair = tr.querySelector('.net-input-pair');
                const stblfInputPair = tr.querySelector('.stblf-input-pair');
                
                // Debug: Check if fields are created with X values
                if (i === 1) {
                    console.log('Hole 1 fields created:', {
                        netInput: netInput,
                        stblfInput: stblfInput,
                        netInputPair: netInputPair,
                        stblfInputPair: stblfInputPair
                    });
                    
                    if (netInput) {
                        console.log('netInput.value:', netInput.value);
                        console.log('netInput.outerHTML:', netInput.outerHTML);
                        console.log('netInput.style:', netInput.style.cssText);
                    }
                }
                
                // Add event listeners to gross input fields
                const grossInput = tr.querySelector('.gross-input');
                const grossInputPair = tr.querySelector('.gross-input-pair');
                
                grossInput.addEventListener('input', () => {
                    console.log(`Hole ${i} Player 1 gross input:`, grossInput.value);
                    calculateNetAll();
                });
                
                grossInputPair.addEventListener('input', () => {
                    console.log(`Hole ${i} Player 2 gross input:`, grossInputPair.value);
                    calculateNetAll();
                });
            }
        }
        // Create the table rows first
        createRows(1, 9, 'front9Rows');
        createRows(10, 18, 'back9Rows');
        
        // Now that tables are created, we can safely calculate slopes
        console.log('Tables created, ready for slope calculations');
        
        // Function to trigger calculations when tables are ready
        function triggerCalculationsIfReady() {
            // Check if tables are ready by looking for at least one input field
            const firstInput = document.querySelector('.gross-input[data-hole="1"]');
            if (firstInput) {
                console.log('Tables are ready, triggering calculations');
                console.log('First input field found:', firstInput);
                console.log('epholes_index data:', epholes_index);
                calculateNetAll();
                calculateStblfAll();
            } else {
                console.log('Tables not ready yet, waiting...');
                setTimeout(triggerCalculationsIfReady, 100);
            }
        }
        
        // Don't trigger calculations automatically - wait for user input
        // setTimeout(triggerCalculationsIfReady, 100);

        // Set up tab navigation from Back 9 to H1 Gross
        document.getElementById('grossBack9').addEventListener('keydown', function(e) {
            if (e.key === 'Tab' && !e.shiftKey) {
                e.preventDefault();
                const h1GrossInput = document.querySelector('.gross-input[data-hole="1"]');
                if (h1GrossInput) {
                    h1GrossInput.focus();
                    h1GrossInput.select();
                }
            }
        });

        // Auto-advance Gross input with improved focus handling
        const grossInputs = Array.from(document.querySelectorAll('.gross-input, .gross-input-pair'));
        grossInputs.forEach((input, idx) => {
            // Add focus styling
            input.addEventListener('focus', function() {
                this.style.backgroundColor = '#e3f2fd';
                this.style.border = '2px solid #2196f3';
            });
            
            input.addEventListener('blur', function() {
                this.style.backgroundColor = '';
                this.style.border = '';
            });
            
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const next = grossInputs[idx + 1];
                    if (next) {
                        next.focus();
                        next.select();
                    }
                } else if (e.key === 'Tab') {
                    // Always handle tab navigation ourselves for consistent behavior
                    e.preventDefault();
                    const next = grossInputs[idx + 1];
                    if (next) {
                        next.focus();
                        next.select();
                    }
                }
            });
            
            // Auto-advance on input with validation
            input.addEventListener('input', function() {
                // Validate input: only allow single digits 1-9
                let value = this.value;
                
                // Remove any non-digit characters
                value = value.replace(/[^0-9]/g, '');
                
                // Ensure only single digit and between 1-9
                if (value.length > 1) {
                    value = value.slice(-1); // Take only the last digit
                }
                
                // Check if value is between 1-9
                if (value !== '' && (parseInt(value) < 1 || parseInt(value) > 9)) {
                    value = ''; // Clear invalid values
                }
                
                this.value = value;
                
                // Auto-advance if valid single digit entered
                if (this.value.length === 1 && parseInt(this.value) >= 1 && parseInt(this.value) <= 9) {
                    const next = grossInputs[idx + 1];
                    if (next) {
                        setTimeout(() => {
                            next.focus();
                            next.select();
                        }, 100);
                    }
                }
            });
        });

        // Ensure only one player can have a score per hole
        function setupSingleScorePerHole() {
            for (let h = 1; h <= 18; h++) {
                const grossInput = document.querySelector(`.gross-input[data-hole='${h}']`);
                const grossInputPair = document.querySelector(`.gross-input-pair[data-hole='${h}']`);
                
                if (grossInput && grossInputPair) {
                    // Player 1 input handler
                    grossInput.addEventListener('input', function() {
                        if (this.value !== '' && parseInt(this.value) > 0) {
                            // Clear player 2 score for this hole
                            grossInputPair.value = '';
                            // Recalculate net and stableford
                            calculateNetAll();
                            calculateStblfAll();
                        }
                    });
                    
                    // Player 2 input handler
                    grossInputPair.addEventListener('input', function() {
                        if (this.value !== '' && parseInt(this.value) > 0) {
                            // Clear player 1 score for this hole
                            grossInput.value = '';
                            // Recalculate net and stableford
                            calculateNetAll();
                            calculateStblfAll();
                        }
                    });
                }
            }
        }

        // Sum logic
        function updateSums() {
            // Sum gross for front 9, back 9, total (including both players)
            let sumFront9 = 0, sumBack9 = 0, sumTotal = 0;
            for (let i = 1; i <= 9; i++) {
                const val1 = document.querySelector(`.gross-input[data-hole='${i}']`).value;
                const val2 = document.querySelector(`.gross-input-pair[data-hole='${i}']`).value;
                sumFront9 += (Number(val1) || 0) + (Number(val2) || 0);
            }
            for (let i = 10; i <= 18; i++) {
                const val1 = document.querySelector(`.gross-input[data-hole='${i}']`).value;
                const val2 = document.querySelector(`.gross-input-pair[data-hole='${i}']`).value;
                sumBack9 += (Number(val1) || 0) + (Number(val2) || 0);
            }
            sumTotal = sumFront9 + sumBack9;
            // Update My sum Total display
            document.getElementById('grossTotalDisplay').textContent = (Number(document.getElementById('grossFront9').value)||0) + (Number(document.getElementById('grossBack9').value)||0);
            // Update summary sums
            document.getElementById('actualGrossFront9').textContent = sumFront9;
            document.getElementById('actualGrossBack9').textContent = sumBack9;
            document.getElementById('actualGrossTotal').textContent = sumTotal;
            // Actual Net (including both players)
            let netFront9 = 0, netBack9 = 0;
            for (let i = 1; i <= 9; i++) {
                const netVal1 = document.querySelector(`.net-input[data-hole='${i}']`).value;
                const netVal2 = document.querySelector(`.net-input-pair[data-hole='${i}']`).value;
                if (netVal1 !== '' && !isNaN(netVal1)) netFront9 += Number(netVal1);
                if (netVal2 !== '' && !isNaN(netVal2)) netFront9 += Number(netVal2);
            }
            for (let i = 10; i <= 18; i++) {
                const netVal1 = document.querySelector(`.net-input[data-hole='${i}']`).value;
                const netVal2 = document.querySelector(`.net-input-pair[data-hole='${i}']`).value;
                if (netVal1 !== '' && !isNaN(netVal1)) netBack9 += Number(netVal1);
                if (netVal2 !== '' && !isNaN(netVal2)) netBack9 += Number(netVal2);
            }
            document.getElementById('actualNetFront9').textContent = netFront9;
            document.getElementById('actualNetBack9').textContent = netBack9;
            document.getElementById('actualNetTotal').textContent = netFront9 + netBack9;
            // Actual Stblf (including both players)
            let stblfFront9 = 0, stblfBack9 = 0;
            for (let i = 1; i <= 9; i++) {
                const stblfVal1 = document.querySelector(`.stblf-input[data-hole='${i}']`).value;
                const stblfVal2 = document.querySelector(`.stblf-input-pair[data-hole='${i}']`).value;
                if (stblfVal1 !== '' && !isNaN(stblfVal1)) stblfFront9 += Number(stblfVal1);
                if (stblfVal2 !== '' && !isNaN(stblfVal2)) stblfFront9 += Number(stblfVal2);
            }
            for (let i = 10; i <= 18; i++) {
                const stblfVal1 = document.querySelector(`.stblf-input[data-hole='${i}']`).value;
                const stblfVal2 = document.querySelector(`.stblf-input-pair[data-hole='${i}']`).value;
                if (stblfVal1 !== '' && !isNaN(stblfVal1)) stblfBack9 += Number(stblfVal1);
                if (stblfVal2 !== '' && !isNaN(stblfVal2)) stblfBack9 += Number(stblfVal2);
            }
            document.getElementById('actualStblfFront9').textContent = stblfFront9;
            document.getElementById('actualStblfBack9').textContent = stblfBack9;
            document.getElementById('actualStblfTotal').textContent = stblfFront9 + stblfBack9;
        }
        document.querySelectorAll('.gross-input, .gross-input-pair').forEach(input => {
            input.addEventListener('input', updateSums);
            input.addEventListener('input', updateCheckButtonState);
            input.setAttribute('maxlength', '1');
        });
        document.querySelectorAll('.net-input, .net-input-pair').forEach(input => {
            input.setAttribute('maxlength', '3');
        });
        const grossFront9 = document.getElementById('grossFront9');
        const grossBack9 = document.getElementById('grossBack9');
        if (grossFront9) {
            grossFront9.addEventListener('input', updateSums);
            grossFront9.addEventListener('input', updateCheckButtonState);
        }
        if (grossBack9) {
            grossBack9.addEventListener('input', updateSums);
            grossBack9.addEventListener('input', updateCheckButtonState);
        }
        // Initial display
        updateSums();

        // New check functionality
        function checkScores() {
            // Get My sum values (Stableford)
            const mySumFront9 = Number(document.getElementById('grossFront9').value) || 0;
            const mySumBack9 = Number(document.getElementById('grossBack9').value) || 0;
            const mySumTotal = mySumFront9 + mySumBack9;
            
            // Get actual calculated Stableford values
            const actualStblfFront9 = Number(document.getElementById('actualStblfFront9').textContent) || 0;
            const actualStblfBack9 = Number(document.getElementById('actualStblfBack9').textContent) || 0;
            const actualStblfTotal = Number(document.getElementById('actualStblfTotal').textContent) || 0;
            
            // Check each section
            const front9Match = mySumFront9 === actualStblfFront9;
            const back9Match = mySumBack9 === actualStblfBack9;
            const totalMatch = mySumTotal === actualStblfTotal;
            
            // Create result message
            let message = 'Score Check Results:\n\n';
            message += `Front 9: My sum (${mySumFront9}) vs Stableford (${actualStblfFront9}) - ${front9Match ? '✓ Match' : '✗ Mismatch'}\n`;
            message += `Back 9: My sum (${mySumBack9}) vs Stableford (${actualStblfBack9}) - ${back9Match ? '✓ Match' : '✗ Mismatch'}\n`;
            message += `Total: My sum (${mySumTotal}) vs Stableford (${actualStblfTotal}) - ${totalMatch ? '✓ Match' : '✗ Mismatch'}\n\n`;
            
            if (front9Match && back9Match && totalMatch) {
                message += '🎉 All scores match! Saving scores...\n\n';
                
                // Show result first
                alert(message);
                
                // Save the scores to database
                saveScoresToDatabase(actualStblfFront9, actualStblfBack9, actualStblfTotal);
            } else {
                message += '⚠️ Some scores do not match. Please check your entries.';
                alert(message);
            }
            
            // Also log to console for debugging
            console.log('Score Check Results:', {
                front9: { mySum: mySumFront9, actual: actualStblfFront9, match: front9Match },
                back9: { mySum: mySumBack9, actual: actualStblfBack9, match: back9Match },
                total: { mySum: mySumTotal, actual: actualStblfTotal, match: totalMatch }
            });
        }
        
        // Add event listener for new check button
        document.addEventListener('DOMContentLoaded', function() {
            const newCheckBtn = document.getElementById('newCheckBtn');
            if (newCheckBtn) {
                newCheckBtn.addEventListener('click', checkScores);
            }
        });

        // Calculate Net for all holes
        function calculateNetAll() {
            console.log('calculateNetAll called');
            const isPairs = groupType === 'Pairs';
            console.log('isPairs:', isPairs);
            
            if (isPairs) {
                // For pairs, we need to get slopes from the player info display
                const slope1 = parseInt(document.getElementById('player1Slope').textContent) || 0;
                const slope2 = parseInt(document.getElementById('player2Slope').textContent) || 0;
                console.log('Slopes - player1:', slope1, 'player2:', slope2);
                
                for (let h = 1; h <= 18; h++) {
                    const grossInput = document.querySelector(`.gross-input[data-hole='${h}']`);
                    const netInput = document.querySelector(`.net-input[data-hole='${h}']`);
                    const grossInputPair = document.querySelector(`.gross-input-pair[data-hole='${h}']`);
                    const netInputPair = document.querySelector(`.net-input-pair[data-hole='${h}']`);
                    const index = parseInt(epholes_index[`h${h}`]) || 0;
                    
                    if (h === 1) {
                        console.log('Hole 1 fields found:', {
                            grossInput: grossInput,
                            netInput: netInput,
                            grossInputPair: grossInputPair,
                            netInputPair: netInputPair,
                            index: index
                        });
                    }
                    
                                        // Calculate for player 1 (individual column)
                    const gross = grossInput.value === '' ? null : parseInt(grossInput.value);
                    if (h === 1) console.log(`Hole 1 Player 1 - gross: ${gross}, slope1: ${slope1}, index: ${index}`);
                    if (gross === null || isNaN(gross) || gross === 0) {
                        netInput.value = '';
                        if (h === 1) console.log('Hole 1 Player 1: No gross score, cleared net');
                    } else {
                        let net = gross;
                        if (slope1 > index) net--;
                        if ((slope1 - 18) > index) net--;
                        netInput.value = net;
                        // Make the value more visible for debugging
                        netInput.style.color = '#000000';
                        netInput.style.fontWeight = 'bold';
                        netInput.style.fontSize = '14px';
                        
                        if (h === 1) {
                            console.log(`Hole 1 Player 1: Set net to ${net} (was ${gross}, slope ${slope1} > index ${index})`);
                            console.log('netInput.value after setting:', netInput.value);
                            console.log('netInput.style:', netInput.style.cssText);
                            console.log('netInput computed styles:', window.getComputedStyle(netInput));
                            console.log('netInput.outerHTML:', netInput.outerHTML);
                        }
                    }
                    
                    // Calculate for player 2 (pair column)
                    const grossPair = grossInputPair.value === '' ? null : parseInt(grossInputPair.value);
                    if (h === 1) console.log(`Hole 1 Player 2 - gross: ${grossPair}, slope2: ${slope2}, index: ${index}`);
                    if (grossPair === null || isNaN(grossPair) || grossPair === 0) {
                        netInputPair.value = '';
                        if (h === 1) console.log('Hole 1 Player 2: No gross score, cleared net');
                    } else {
                        let netPair = grossPair;
                        if (slope2 > index) netPair--;
                        if ((slope2 - 18) > index) netPair--;
                        netInputPair.value = netPair;
                        // Make the value more visible for debugging
                        netInputPair.style.color = '#000000';
                        netInputPair.style.fontWeight = 'bold';
                        netInputPair.style.fontSize = '14px';
                        
                        if (h === 1) {
                            console.log(`Hole 1 Player 2: Set net to ${netPair} (was ${grossPair}, slope ${slope2} > index ${index})`);
                            console.log('netInputPair.value after setting:', netInputPair.value);
                        }
                    }
                }
            } else {
                // For individual players, use the single slope
                const slope = parseInt(document.getElementById('playerSlope').textContent) || 0;
                for (let h = 1; h <= 18; h++) {
                    const grossInput = document.querySelector(`.gross-input[data-hole='${h}']`);
                    const netInput = document.querySelector(`.net-input[data-hole='${h}']`);
                    const index = parseInt(epholes_index[`h${h}`]) || 0;
                    
                    const gross = grossInput.value === '' ? null : parseInt(grossInput.value);
                    if (gross === null || isNaN(gross) || gross === 0) {
                        netInput.value = '';
                    } else {
                        let net = gross;
                        if (slope > index) net--;
                        if ((slope - 18) > index) net--;
                        netInput.value = net;
                    }
                }
            }
            updateSums();
        }
        function calculateStblfAll() {
            const isPairs = groupType === 'Pairs';
            
            for (let h = 1; h <= 18; h++) {
                const grossInput = document.querySelector(`.gross-input[data-hole='${h}']`);
                const netInput = document.querySelector(`.net-input[data-hole='${h}']`);
                const stblfInput = document.querySelector(`.stblf-input[data-hole='${h}']`);
                const grossInputPair = document.querySelector(`.gross-input-pair[data-hole='${h}']`);
                const netInputPair = document.querySelector(`.net-input-pair[data-hole='${h}']`);
                const stblfInputPair = document.querySelector(`.stblf-input-pair[data-hole='${h}']`);
                const par = parseInt(epholes_par[`h${h}`]) || 0;
                
                // Calculate for individual player
                const gross = grossInput.value === '' ? null : parseInt(grossInput.value);
                const net = netInput.value === '' ? null : parseInt(netInput.value);
                
                if (gross === null || net === null || isNaN(gross) || isNaN(net) || par === 0) {
                    stblfInput.value = '';
                } else {
                    // Stableford points based on net score vs par
                    const netVsPar = net - par;
                    if (netVsPar === 1) {
                        stblfInput.value = 1;      // Net = Par + 1
                    } else if (netVsPar === 0) {
                        stblfInput.value = 2;      // Net = Par
                    } else if (netVsPar === -1) {
                        stblfInput.value = 3;      // Net = Par - 1
                    } else if (netVsPar === -2) {
                        stblfInput.value = 4;      // Net = Par - 2
                    } else if (netVsPar === -3) {
                        stblfInput.value = 5;      // Net = Par - 3
                    } else if (netVsPar === -4) {
                        stblfInput.value = 6;      // Net = Par - 4
                    } else {
                        stblfInput.value = '';     // No points
                    }
                    
                    // Make the value more visible
                    stblfInput.style.color = '#000000';
                    stblfInput.style.fontWeight = 'bold';
                    stblfInput.style.fontSize = '14px';
                }
                
                // Calculate for pair player (only if pairs mode)
                if (isPairs) {
                    const grossPair = grossInputPair.value === '' ? null : parseInt(grossInputPair.value);
                    const netPair = netInputPair.value === '' ? null : parseInt(netInputPair.value);
                    
                    if (grossPair === null || netPair === null || isNaN(grossPair) || isNaN(netPair) || par === 0) {
                        stblfInputPair.value = '';
                    } else {
                        // Stableford points based on net score vs par
                        const netVsParPair = netPair - par;
                        if (netVsParPair === 1) {
                            stblfInputPair.value = 1;      // Net = Par + 1
                        } else if (netVsParPair === 0) {
                            stblfInputPair.value = 2;      // Net = Par
                        } else if (netVsParPair === -1) {
                            stblfInputPair.value = 3;      // Net = Par - 1
                        } else if (netVsParPair === -2) {
                            stblfInputPair.value = 4;      // Net = Par - 2
                        } else if (netVsParPair === -3) {
                            stblfInputPair.value = 5;      // Net = Par - 3
                        } else if (netVsParPair === -4) {
                            stblfInputPair.value = 6;      // Net = Par - 4
                        } else {
                            stblfInputPair.value = '';     // No points
                        }
                        
                        // Make the value more visible
                        stblfInputPair.style.color = '#000000';
                        stblfInputPair.style.fontWeight = 'bold';
                        stblfInputPair.style.fontSize = '14px';
                    }
                }
            }
            updateSums();
        }
        // Ensure net calculation for all holes is present and triggers on gross input or player change
        document.addEventListener('DOMContentLoaded', function() {
            // Add event listeners to existing elements
            document.querySelectorAll('.gross-input, .net-input, .gross-input-pair, .net-input-pair').forEach(input => {
                input.addEventListener('input', calculateNetAll);
                input.addEventListener('blur', calculateNetAll);
            });
            
            // Add event listener to player select if it exists
            const playerSelect = document.getElementById('playerSelect');
            if (playerSelect) {
                playerSelect.addEventListener('change', calculateNetAll);
            }
            
            document.querySelectorAll('.gross-input, .net-input, .gross-input-pair, .net-input-pair').forEach(input => {
                input.addEventListener('input', calculateStblfAll);
                input.addEventListener('blur', calculateStblfAll);
            });
            

            
            // Setup single score per hole after tables are created
            setTimeout(() => {
                setupSingleScorePerHole();
            }, 100);
            
            // Show save section if auto-login
            if (currentFlight && currentFlight !== '0' && currentFlight !== '') {
                if (!isPairs) {
                    // Auto-select the flight for non-Pairs events
                    const flightSelect = document.getElementById('playerSelect');
                    if (flightSelect) {
                        flightSelect.value = currentFlight;
                        // Trigger the change event
                        const event = new Event('change');
                        flightSelect.dispatchEvent(event);
                    }
                }
                showSaveSection();
                loadOtherFlights();
            }
            
            // Auto-focus on Front 9 input when page loads
            setTimeout(() => {
                const front9Input = document.getElementById('grossFront9');
                if (front9Input) {
                    front9Input.focus();
                    front9Input.select();
                }
            }, 500);
        });

        // Always show other pair information for pairs events
        function showOtherPairInfo() {
            if (currentFlight && currentFlight !== '0' && currentFlight !== '') {
                // Determine the other pair club
                const currentClub = '<?php echo $pairParam; ?>';
                const otherClub = (currentClub === 'El Paraiso') ? 'La Hacienda' : 'El Paraiso';
                
                // Fetch other pair data
                fetch(`event-get-flight-players.php?EventId=${eventId}&flight=${currentFlight}&club=${encodeURIComponent(otherClub)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.players.length >= 2) {
                            // Create other pair card
                            const otherPairCard = document.createElement('div');
                            otherPairCard.className = 'pair-card';
                            otherPairCard.style.marginTop = '20px';
                            otherPairCard.innerHTML = `
                                <h4>Other Pair - ${otherClub}</h4>
                                <div class="player-info">
                                    <div class="player-details">
                                        <strong>Player 1:</strong> ${data.players[0].name} 
                                        (${data.players[0].gender}) - 
                                        HCP: ${data.players[0].handicap} - 
                                        Teebox: ${data.players[0].gender === 'F' ? '50' : '56'}
                                    </div>
                                    <div class="player-details">
                                        <strong>Player 2:</strong> ${data.players[1].name} 
                                        (${data.players[1].gender}) - 
                                        HCP: ${data.players[1].handicap} - 
                                        Teebox: ${data.players[1].gender === 'F' ? '50' : '56'}
                                    </div>
                                </div>
                                <div class="status-message">
                                    <p class="status-no-scores">❌ No scores registered yet</p>
                                </div>
                            `;
                            
                            // Insert after current pair card
                            const currentPairCard = document.querySelector('.pair-card');
                            if (currentPairCard) {
                                currentPairCard.parentNode.insertBefore(otherPairCard, currentPairCard.nextSibling);
                            }
                            
                            // Check for existing scores for other pair
                            checkOtherPairScores(otherClub, otherPairCard);
                        }
                    })
                    .catch(error => {
                        console.error('Error loading other pair info:', error);
                    });
            }
        }
        
        // Check scores for other pair and update display
        function checkOtherPairScores(otherClub, otherPairCard) {
            fetch(`event-check-scorecard-scores.php?EventId=${eventId}&flight=${currentFlight}&club=${encodeURIComponent(otherClub)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.scores) {
                        const scores = data.scores;
                        const statusMessage = otherPairCard.querySelector('.status-message');
                        
                        if (scores.marked && scores.marked.trim() !== '') {
                            // Scores confirmed
                            statusMessage.innerHTML = `
                                <p class="status-confirmed">✅ Scores registered and confirmed</p>
                                <div class="scores-display">
                                    <p><strong>Total Stableford:</strong> ${scores.total_stableford || 'N/A'}</p>
                                    <p><strong>Front 9:</strong> ${scores.front9_stableford || 'N/A'} | <strong>Back 9:</strong> ${scores.back9_stableford || 'N/A'}</p>
                                </div>
                            `;
                        } else if (scores.total_stableford && scores.total_stableford > 0) {
                            // Scores not confirmed
                            statusMessage.innerHTML = `
                                <p class="status-not-confirmed">⚠️ Scores registered, but not confirmed yet</p>
                                <div class="scores-display">
                                    <p><strong>Front 9:</strong> ${scores.front9_stableford || 'N/A'} | <strong>Back 9:</strong> ${scores.back9_stableford || 'N/A'} | <strong>Total:</strong> ${scores.total_stableford || 'N/A'}</p>
                                </div>
                            `;
                        }
                        // If no scores, keep the default "No scores registered yet" message
                    }
                })
                .catch(error => {
                    console.error('Error checking other pair scores:', error);
                });
        }

        // Show save section with marker info and check existing scores
        function showSaveSection() {
            if (currentFlight && currentFlight !== '0' && currentFlight !== '' && markerFlight > 0) {
                // First check if scores already exist for this flight
                fetch(`check-existing-scores.php?event_id=${eventId}&flight=${currentFlight}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.exists) {
                            // Scores exist - show existing data instead of save button
                            displayExistingScores(data.scores);
                        } else {
                            // No scores exist - show save section with marker info
                            fetch(`event-get-flight-players.php?EventId=${eventId}&flight=${markerFlight}`)
                                .then(response => response.json())
                                .then(markerData => {
                                    if (markerData.success && markerData.players.length >= 2) {
                                        document.getElementById('markerNames').textContent = markerData.players[0] + ' & ' + markerData.players[1];
                                    } else {
                                        document.getElementById('markerNames').textContent = 'Flight ' + markerFlight + ' (Players not found)';
                                    }
                                })
                                .catch(error => {
                                    console.error('Error loading markers:', error);
                                    document.getElementById('markerNames').textContent = 'Flight ' + markerFlight + ' (Error loading)';
                                });
                            
                            // Save section removed - scores auto-saved when matched
                        }
                    })
                    .catch(error => {
                        console.error('Error checking existing scores:', error);
                        // Fallback removed - save section no longer exists
                    });
            }
        }
        
        // Display existing scores and suppress data entry
        function displayExistingScores(scores) {
            // Hide all score input fields/section
            const scoreEntrySection = document.getElementById('scoreEntrySection');
            if (scoreEntrySection) scoreEntrySection.style.display = 'none';
            const checkScoresBtn = document.getElementById('newCheckBtn');
            if (checkScoresBtn) checkScoresBtn.style.display = 'none';
            // Hide the summary table
            const scoreSummaryTable = document.getElementById('scoreSummaryTable');
            if (scoreSummaryTable) scoreSummaryTable.style.display = 'none';

            // Save section removed - scores are auto-saved when matched
            // Check if marker's flight also has scores
            checkMarkerFlightScores();
        }
        
        // For marker flight, show the same detailed score summary if it exists
        function checkMarkerFlightScores() {
            const markerSection = document.getElementById('markerFlightSection');
            if (markerFlight > 0) {
                fetch(`check-existing-scores.php?event_id=${eventId}&flight=${markerFlight}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.exists) {
                            // Show marker flight scores in the same format
                            const scores = data.scores;
                            const isMarked = scores.marked === 'YES' || scores.marked === 'Yes' || scores.marked === true;
                            
                            if (isMarked) {
                                // If marked, show confirmed message
                                markerSection.innerHTML = `
                                    <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin-top: 20px; border: 1px solid #b3d9ff;">
                                        <h4 style="margin-top: 0; color: #495057;">✅ Here are the confirmed and marked flight's scores!</h4>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; font-size: 14px;">
                                            <div>
                                                <div><strong>Flight ${scores.flight}</strong></div>
                                                <div>${scores.player1_name} (HCP: ${scores.player1_hcp}, Slope: ${scores.player1_slope})</div>
                                                <div>${scores.player2_name} (HCP: ${scores.player2_hcp}, Slope: ${scores.player2_slope})</div>
                                            </div>
                                            <div>
                                                <div><strong>${scores.club}</strong></div>
                                                <div>Stableford Front 9 <span style="font-size: 18px; font-weight: bold;">${scores.front9_stableford}</span> Back 9 <span style="font-size: 18px; font-weight: bold;">${scores.back9_stableford}</span> Total <span style="font-size: 18px; font-weight: bold;">${scores.total_stableford}</span></div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            } else {
                                // If not marked, show action icon and confirm button
                                markerSection.innerHTML = `
                                    <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin-top: 20px; border: 1px solid #b3d9ff;">
                                        <h4 style="margin-top: 0; color: #495057;">🔍 Check the scores and if OK Click confirm here</h4>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; font-size: 14px;">
                                            <div>
                                                <div><strong>Flight ${scores.flight}</strong></div>
                                                <div>${scores.player1_name} (HCP: ${scores.player1_hcp}, Slope: ${scores.player1_slope})</div>
                                                <div>${scores.player2_name} (HCP: ${scores.player2_hcp}, Slope: ${scores.player2_slope})</div>
                                            </div>
                                            <div>
                                                <div><strong>${scores.club}</strong></div>
                                                <div>Stableford Front 9 <span style="font-size: 18px; font-weight: bold;">${scores.front9_stableford}</span> Back 9 <span style="font-size: 18px; font-weight: bold;">${scores.back9_stableford}</span> Total <span style="font-size: 18px; font-weight: bold;">${scores.total_stableford}</span></div>
                                            </div>
                                        </div>
                                        <button onclick="confirmMarkerScores('${markerFlight}')" style="background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; margin-top: 10px;">Confirm Scores</button>
                                    </div>
                                `;
                            }
                        } else {
                            markerSection.innerHTML = '';
                        }
                    })
                    .catch(error => {
                        console.error('Error checking marker flight scores:', error);
                    });
            } else if (markerSection) {
                markerSection.innerHTML = '';
            }
        }

        // Check flight status and display verification info
        function checkFlightStatus() {
            const urlParams = new URLSearchParams(window.location.search);
            const flt = urlParams.get('flt');
            
            if (flt) {
                fetch(`check-flight-status.php?flt=${flt}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.exists) {
                            displayFlightVerification(data.data);
                        }
                    })
                    .catch(error => {
                        console.error('Error checking flight status:', error);
                    });
            }
        }
        
        // Display flight verification info
        function displayFlightVerification(flightData) {
            const container = document.getElementById('flightVerificationSection');
            if (!container) return;
            
            container.innerHTML = `
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 10px 0; border: 1px solid #dee2e6;">
                    <h4 style="margin-top: 0; color: #495057;">Flight ${flightData.flight} Verification</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 14px;">
                        <div><strong>Club:</strong> ${flightData.club}</div>
                        <div><strong>Flight:</strong> ${flightData.flight}</div>
                        <div><strong>Player 1:</strong> ${flightData.player1_name} (HCP: ${flightData.player1_hcp}, Slope: ${flightData.player1_slope})</div>
                        <div><strong>Player 2:</strong> ${flightData.player2_name} (HCP: ${flightData.player2_hcp}, Slope: ${flightData.player2_slope})</div>
                        <div><strong>Total Stableford:</strong> ${flightData.total_stableford}</div>
                        <div><strong>Status:</strong> ${flightData.marked ? '✅ Verified' : '⏳ Pending'}</div>
                    </div>
                    ${!flightData.marked ? `<button onclick="markAsVerified('${flightData.flight}')" style="background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; margin-top: 10px;">Mark as Verified</button>` : ''}
                </div>
            `;
            container.style.display = 'block';
        }
        
        // Mark flight as verified
        function markAsVerified(flight) {
            const urlParams = new URLSearchParams(window.location.search);
            const flt = urlParams.get('flt');
            const parts = flt.split('_');
            const eventId = parts[0];
            
            const formData = new FormData();
            formData.append('event_id', eventId);
            formData.append('flight', flight);
            
            fetch('mark-verified.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Flight marked as verified!');
                    location.reload(); // Refresh to show updated status
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error marking as verified:', error);
                alert('Error marking as verified');
            });
        }
        
        // Confirm marker scores and mark as verified
        function confirmMarkerScores(flight) {
            const formData = new FormData();
            formData.append('event_id', eventId);
            formData.append('flight', flight);
            
            fetch('mark-verified.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                return response.text().then(text => {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('Failed to parse JSON:', text);
                        throw new Error('Invalid JSON response: ' + text);
                    }
                });
            })
            .then(data => {
                console.log('Parsed data:', data);
                if (data.success) {
                    // Redirect to scores.php with flt parameter
                    const flt = eventId + '_' + flight;
                    window.location.href = 'scores.php?flt=' + flt;
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error confirming scores:', error);
                alert('Error confirming scores: ' + error.message);
            });
        }
        
        // Load other flights scores
        function loadOtherFlights() {
            fetch(`event-get-other-flights.php?EventId=${eventId}&currentFlight=${currentFlight}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.flights.length > 0) {
                        displayOtherFlights(data.flights);
                        document.getElementById('otherFlightsSection').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error loading other flights:', error);
                });
        }

        // Display other flights
        function displayOtherFlights(flights) {
            const container = document.getElementById('otherFlightsList');
            container.innerHTML = '';
            
            flights.forEach(flight => {
                const div = document.createElement('div');
                div.style.cssText = 'margin-bottom: 10px; padding: 10px; background: white; border-radius: 4px; border: 1px solid #ddd;';
                div.innerHTML = `
                    <strong>Flight ${flight.flight}</strong> - ${flight.player1_name} & ${flight.player2_name}<br>
                    <small>Stableford: ${flight.total_stableford} | Marked by: ${flight.marked_by_player1} & ${flight.marked_by_player2}</small>
                    <input type="checkbox" ${flight.marked ? 'checked' : ''} disabled style="margin-left: 10px;">
                `;
                container.appendChild(div);
            });
        }

        // Function to save scores to database
        function saveScoresToDatabase(front9Stableford, back9Stableford, totalStableford) {
            const isPairs = groupType === 'Pairs';
            let formData;
            
            if (isPairs) {
                // For pairs events
                const clubName = document.getElementById('clubName').textContent;
                formData = new FormData();
                formData.append('event_id', eventId);
                formData.append('flight', currentFlight);
                formData.append('club', clubName);
                formData.append('front9_stableford', front9Stableford);
                formData.append('back9_stableford', back9Stableford);
                formData.append('total_stableford', totalStableford);
            } else {
                // For singles events
                const playerSelect = document.getElementById('playerSelect');
                const markerSelect = document.getElementById('markerSelect');
                const selectedPlayer = players.find(p => p.id === playerSelect.value);
                const selectedMarker = players.find(p => p.id === markerSelect.value);
                
                if (!selectedPlayer) {
                    alert('❌ Please select a player first.');
                    return;
                }
                
                if (!selectedMarker) {
                    alert('❌ Please select a marker first.');
                    return;
                }
                
                formData = new FormData();
                formData.append('event_id', eventId);
                formData.append('flight', selectedPlayer.flight);
                formData.append('player_id', selectedPlayer.id);
                formData.append('player_name', selectedPlayer.name);
                formData.append('player_hcp', selectedPlayer.hcp);
                formData.append('marker_id', selectedMarker.id);
                formData.append('marker_name', selectedMarker.name);
                formData.append('front9_stableford', front9Stableford);
                formData.append('back9_stableford', back9Stableford);
                formData.append('total_stableford', totalStableford);
            }
            
            // Send data to update existing scores
            fetch('event-scorecard-update.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ Scores saved successfully!');
                    // Reload the page to show updated status
                    window.location.reload();
                } else {
                    alert('❌ Error saving scores: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error saving scores:', error);
                alert('❌ Error saving scores. Please try again.');
            });
        }

        // Function to confirm other pair scores
        function confirmOtherPairScores() {
            const otherPairClub = '<?php echo $otherPairClub; ?>';
            const currentFlight = '<?php echo $flight; ?>';
            const eventId = <?php echo $EventId; ?>;
            
            // Create form data for confirmation
            const formData = new FormData();
            formData.append('action', 'confirm_scores');
            formData.append('event_id', eventId);
            formData.append('flight', currentFlight);
            formData.append('club', otherPairClub);
            formData.append('marked', '<?php echo $markerFlight; ?>');
            
            // Send confirmation request
            fetch('event-scorecard-update.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Update the status message
                const statusMessage = document.querySelector('.status-message');
                if (statusMessage) {
                    statusMessage.innerHTML = '<p class="status-confirmed">✅ Scores registered and confirmed</p>';
                }
                
                // Show success message
                alert('Scores confirmed successfully!');
                
                // Reload the page to reflect the changes
                window.location.reload();
            })
            .catch(error => {
                console.error('Error confirming scores:', error);
                alert('Error confirming scores. Please try again.');
            });
        }

        // Save button functionality removed - scores are auto-saved when matched


    </script>
</body>
</html> 