<?php
include '../includes/auth.php';
include '../includes/db.php';

$event_id = $_GET['id'] ?? null;
if (!$event_id) {
    header('Location: events.php');
    exit;
}

$message = '';

// Check if redirected from event creation
if (isset($_GET['created']) && $_GET['created'] == '1') {
    $message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <strong>Event created successfully!</strong> 
                    Now configure the detailed settings below to complete your event setup.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>';
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $date = $_POST['date'];
    $location = $_POST['location'];
    $sport_discipline = $_POST['sport_discipline'];
    $description = $_POST['description'];
    $max_participants = $_POST['max_participants'];
    $entry_fee = $_POST['entry_fee'];
    $contact_email = $_POST['contact_email'];
    $contact_phone = $_POST['contact_phone'];
    $scoring_mode = $_POST['scoring_mode'];
    $runs_per_heat = $_POST['runs_per_heat'];
    $heats_total = $_POST['heats_total'];
    $registration_deadline = $_POST['registration_deadline'];
    $status = $_POST['status'];
    $scoring_format = $_POST['scoring_format'] ?? null;

    $stmt = $pdo->prepare("UPDATE events SET 
                           name = ?, date = ?, location = ?, sport_discipline = ?, description = ?, 
                           max_participants = ?, entry_fee = ?, contact_email = ?, contact_phone = ?, 
                           scoring_mode = ?, runs_per_heat = ?, heats_total = ?, registration_deadline = ?, status = ?, scoring_format = ?
                           WHERE id = ?");
    
    if ($stmt->execute([$name, $date, $location, $sport_discipline, $description, $max_participants, $entry_fee, $contact_email, $contact_phone, $scoring_mode, $runs_per_heat, $heats_total, $registration_deadline, $status, $scoring_format, $event_id])) {
        $message = '<div class="alert alert-success alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> Event updated successfully! 
                        <a href="events.php" class="alert alert-link">Back to Events</a>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } else {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> Failed to update event. Please try again.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    }
}

// Fetch existing event data
$stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
$stmt->execute([$event_id]);
$event = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$event) {
    header('Location: events.php');
    exit;
}

// Get participant count
$participant_count_stmt = $pdo->prepare("SELECT COUNT(*) FROM event_participants WHERE event_id = ?");
$participant_count_stmt->execute([$event_id]);
$participant_count = $participant_count_stmt->fetchColumn();

// Load sports from figure_sports table
$sports_stmt = $pdo->prepare("SELECT sport_name FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
$sports_stmt->execute();
$available_sports = $sports_stmt->fetchAll(PDO::FETCH_COLUMN);

// Load scoring formats grouped by sport with round data and unique aggregations
$formats_stmt = $pdo->prepare("
    SELECT sf.format_id, sf.name, sf.sport,
           GROUP_CONCAT(DISTINCT sfr.runs ORDER BY sfr.round_name) as round_runs,
           GROUP_CONCAT(DISTINCT sfr.aggregation ORDER BY sfr.round_name) as aggregations,
           COUNT(DISTINCT sfr.id) as total_rounds
    FROM scoring_formats sf
    LEFT JOIN scoring_format_rounds sfr ON sf.format_id = sfr.format_id
    WHERE sf.is_active = 1
    GROUP BY sf.format_id, sf.name, sf.sport
    ORDER BY sf.sport, sf.name
");
$formats_stmt->execute();
$scoring_formats = $formats_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get all unique aggregation methods for dynamic scoring mode options
$aggregation_stmt = $pdo->prepare("
    SELECT DISTINCT aggregation 
    FROM scoring_format_rounds 
    WHERE aggregation IS NOT NULL AND aggregation != ''
    ORDER BY aggregation
");
$aggregation_stmt->execute();
$available_aggregations = $aggregation_stmt->fetchAll(PDO::FETCH_COLUMN);

// Group formats by sport for JavaScript
$formats_by_sport = [];
foreach ($scoring_formats as $format) {
    $formats_by_sport[$format['sport']][] = $format;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Event - <?= htmlspecialchars($event['name']) ?> - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        
        .required::after {
            content: ' *';
            color: #dc3545;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <!-- Help Button and Modal -->
    <div class="position-fixed end-0 top-0 p-3  help_f_button" style="z-index: 1055;">
        <button type="button" class="btn btn-info btn-lg rounded-circle shadow" title="Help / Guide" data-bs-toggle="modal" data-bs-target="#helpModal" style="width:56px; height:56px;">
            <i class="fas fa-question"></i>
        </button>
    </div>
    <!-- Help Modal -->
    <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-edit me-2"></i>Edit Event Help</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0" style="height:80vh;">
                    <iframe src="../help/event_edit_help.html" style="width:100%;height:100%;border:0;" title="Edit Event Help"></iframe>
                </div>
            </div>
        </div>
    </div>
    <div class="container-fluid container-StyleScore p-4">
                    <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <div class="row justify-content-center">
            <div class="col-xl-10">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h1 class="h2 mb-1">
                            <i class="fas fa-edit text-success me-2"></i>Edit Event
                        </h1>
                        <p class="text-muted mb-0">Update event details and configuration settings</p>
                    </div>
                    <div>
                        <a href="events.php" class="btn btn-outline-primary">
                            <i class="fas fa-list me-1"></i>All Events
                        </a>
                    </div>
                </div>

                <?php echo $message; ?>

                <!-- Event Info Badge -->
                <div class="alert alert-info mb-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-1"><i class="fas fa-calendar-alt me-2"></i>Event Information</h6>
                            <small>Created: <?= date('M d, Y', strtotime($event['created_at'] ?? 'now')) ?> | Participants: <?= $participant_count ?></small>
                        </div>
                        <div class="col-md-4 text-end">
                            <?php if ($participant_count > 0): ?>
                                <span class="badge bg-success">Active Event</span>
                            <?php else: ?>
                                <span class="badge bg-secondary">Draft Event</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <!-- Edit Form -->
                <form method="post" class="needs-validation" novalidate>
                    <div class="row g-4">
                        <!-- Basic Information -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-info-circle text-success me-2"></i>Basic Information
                                </h5>
                                
                                <div class="mb-3">
                                    <label for="name" class="form-label fw-bold required">Event Name</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           value="<?= htmlspecialchars($event['name']) ?>" required>
                                    <div class="invalid-feedback">Please provide a valid event name.</div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="date" class="form-label fw-bold required">Event Date</label>
                                        <input type="date" class="form-control" id="date" name="date" 
                                               value="<?= htmlspecialchars($event['date']) ?>" required>
                                        <div class="invalid-feedback">Please provide a valid date.</div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="registration_deadline" class="form-label fw-bold">Registration Deadline</label>
                                        <input type="date" class="form-control" id="registration_deadline" name="registration_deadline" 
                                               value="<?= htmlspecialchars($event['registration_deadline'] ?? '') ?>">
                                        <div class="form-text">Optional deadline for registration</div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="location" class="form-label fw-bold required">Location</label>
                                    <input type="text" class="form-control" id="location" name="location" 
                                           value="<?= htmlspecialchars($event['location']) ?>" 
                                           placeholder="e.g., Central Skate Park, New York" required>
                                    <div class="invalid-feedback">Please provide a valid location.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label fw-bold">Description</label>
                                    <textarea class="form-control" id="description" name="description" rows="3" 
                                              placeholder="Brief description of the event, rules, or special notes..."><?= htmlspecialchars($event['description'] ?? '') ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Sport & Format Configuration -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-trophy text-success me-2"></i>Sport & Format
                                </h5>
                                
                                <?php if ($participant_count > 0): ?>
                                    <div class="alert alert-warning mb-3">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <strong>Warning:</strong> This event has participants. Changing sport or format may affect scoring.
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <label for="sport_discipline" class="form-label fw-bold required">Sport Discipline</label>
                                    <select class="form-select" id="sport_discipline" name="sport_discipline" required>
                                        <option value="">Select Sport</option>
                                        
                                        <!-- Dynamic Sports from Database -->
                                        <optgroup label="Available Sports">
                                            <?php foreach ($available_sports as $sport): ?>
                                                <option value="<?= htmlspecialchars($sport) ?>" 
                                                        <?= $event['sport_discipline'] === $sport ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars(ucwords(str_replace('_', ' ', $sport))) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    </select>
                                    <div class="invalid-feedback">Please select a sport discipline.</div>
                                    <div class="form-text">
                                        Sports are loaded from the figures database. 
                                        <a href="figures_management.php" target="_blank">Manage sports</a>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="scoring_format" class="form-label fw-bold">Scoring Format</label>
                                    <select class="form-select" id="scoring_format" name="scoring_format">
                                        <option value="">Select Format</option>
                                        
                                        <!-- Dynamic Formats grouped by sport -->
                                        <?php foreach ($scoring_formats as $format): ?>
                                            <option value="<?= $format['format_id'] ?>" 
                                                    data-sport="<?= htmlspecialchars($format['sport']) ?>"
                                                    data-runs="<?= htmlspecialchars($format['round_runs'] ?? '') ?>"
                                                    data-aggregations="<?= htmlspecialchars($format['aggregations'] ?? '') ?>"
                                                    data-total-rounds="<?= $format['total_rounds'] ?? 0 ?>"
                                                    <?= $event['scoring_format'] == $format['format_id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($format['name']) ?> (<?= htmlspecialchars($format['sport']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text">
                                        <i class="fas fa-filter me-1"></i>Formats are automatically filtered by selected sport discipline. 
                                        <a href="scoring_formats.php" target="_blank">Manage formats</a>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="status" class="form-label fw-bold">Event Status</label>
                                        <select class="form-select" id="status" name="status">
                                            <option value="draft" <?= $event['status'] === 'draft' ? 'selected' : '' ?>>Draft</option>
                                            <option value="open" <?= $event['status'] === 'open' ? 'selected' : '' ?>>Open for Registration</option>
                                            <option value="live" <?= $event['status'] === 'live' ? 'selected' : '' ?>>Live Event</option>
                                            <option value="completed" <?= $event['status'] === 'completed' ? 'selected' : '' ?>>Completed</option>
                                            <option value="cancelled" <?= $event['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="max_participants" class="form-label fw-bold">Max Participants</label>
                                        <input type="number" class="form-control" id="max_participants" name="max_participants" 
                                               value="<?= htmlspecialchars($event['max_participants'] ?? '') ?>" min="1">
                                        <div class="form-text">Leave empty for unlimited</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Scoring Configuration -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-calculator text-success me-2"></i>Scoring Configuration
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="scoring_mode" class="form-label fw-bold">Scoring Mode</label>
                                        <select class="form-select" id="scoring_mode" name="scoring_mode">
                                            <option value="">Select Mode</option>
                                            
                                            <!-- Standard Modes -->
                                            <optgroup label="Standard Modes">
                                                <option value="average" <?= $event['scoring_mode'] === 'average' ? 'selected' : '' ?>>Average</option>
                                                <option value="best" <?= $event['scoring_mode'] === 'best' ? 'selected' : '' ?>>Best</option>
                                                <option value="total" <?= $event['scoring_mode'] === 'total' ? 'selected' : '' ?>>Total</option>
                                                <option value="as_per_format" <?= $event['scoring_mode'] === 'as_per_format' ? 'selected' : '' ?>>As Per Format</option>
                                            </optgroup>
                                            
                                            <!-- Format-Specific Modes (populated dynamically) -->
                                            <optgroup label="Format-Specific Modes" id="format-specific-modes">
                                                <!-- Populated by JavaScript based on selected format -->
                                            </optgroup>
                                        </select>
                                        <div class="form-text">Automatically selected based on format</div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="runs_per_heat" class="form-label fw-bold">Runs Per Heat</label>
                                        <input type="number" class="form-control" id="runs_per_heat" name="runs_per_heat" 
                                               value="<?= $event['runs_per_heat'] ?? '2' ?>" min="1" max="10">
                                        <div class="form-text">Auto-populated from format</div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="heats_total" class="form-label fw-bold">Total Heats</label>
                                        <input type="number" class="form-control" id="heats_total" name="heats_total" 
                                               value="<?= $event['heats_total'] ?? '1' ?>" min="1" max="20">
                                        <div class="form-text">Auto-populated from format</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Contact & Financial -->
                        <div class="col-lg-6">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-address-book text-success me-2"></i>Contact & Financial
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="contact_email" class="form-label fw-bold">Contact Email</label>
                                        <input type="email" class="form-control" id="contact_email" name="contact_email" 
                                               value="<?= htmlspecialchars($event['contact_email'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="contact_phone" class="form-label fw-bold">Contact Phone</label>
                                        <input type="text" class="form-control" id="contact_phone" name="contact_phone" 
                                               value="<?= htmlspecialchars($event['contact_phone'] ?? '') ?>">
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="entry_fee" class="form-label fw-bold">Entry Fee ($)</label>
                                    <input type="number" class="form-control" id="entry_fee" name="entry_fee" 
                                           value="<?= htmlspecialchars($event['entry_fee'] ?? '0') ?>" min="0" step="0.01">
                                    <div class="form-text">Set to 0 for free events</div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Actions -->
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="text-muted">
                                    <small><i class="fas fa-info-circle me-1"></i>Changes will be saved to the database</small>
                                </div>
                                <div>
                                    <a href="events.php" class="btn btn-outline-secondary me-2">
                                        <i class="fas fa-times me-1"></i>Cancel
                                    </a>
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-save me-1"></i>Update Event
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

                <!-- Danger Zone -->
                <?php if ($participant_count == 0): ?>
                <div class="mt-4">
                    <div class="form-section p-4 border-danger">
                        <h5 class="text-danger mb-3"><i class="fas fa-exclamation-triangle me-2"></i>Danger Zone</h5>
                        <p class="text-muted mb-3">Permanently delete this event. This action cannot be undone.</p>
                        <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                            <i class="fas fa-trash me-1"></i>Delete Event
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>


                          

<script>
// Bootstrap form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// Scoring format filtering based on sport discipline
document.addEventListener('DOMContentLoaded', function() {
    const sportSelect = document.querySelector('select[name="sport_discipline"]');
    const formatSelect = document.getElementById('scoring_format');
    const scoringModeSelect = document.getElementById('scoring_mode');
    const runsPerHeatInput = document.getElementById('runs_per_heat');
    const totalHeatsInput = document.getElementById('heats_total');
    const allFormatOptions = Array.from(formatSelect.querySelectorAll('option'));
    const allScoringModeOptions = Array.from(scoringModeSelect.querySelectorAll('option'));
    
    // Store original options structure
    const originalScoringModeHTML = scoringModeSelect.innerHTML;
    
    // Sport-specific scoring mode configurations
    const sportScoringModes = {
        'freestyle_scooter': ['best', 'average', 'as_per_format'],
        'street_scooter': ['best', 'average', 'as_per_format'], 
        'park_scooter': ['best', 'average', 'as_per_format'],
        'alpine_skiing': ['best', 'total', 'as_per_format'],
        'freestyle_skiing': ['best', 'average', 'as_per_format'],
        'figure_skating': ['total', 'average', 'as_per_format'],
        'speed_skating': ['best', 'total', 'as_per_format'],
        'ice_hockey': ['total', 'as_per_format'],
        'inline_skating': ['best', 'average', 'as_per_format'],
        'skateboarding': ['best', 'average', 'as_per_format'],
        'bmx': ['best', 'average', 'as_per_format'],
        'default': ['average', 'best', 'total', 'as_per_format']
    };
    
    function populateScoringModeOptions() {
        const selectedSport = sportSelect.value;
        const selectedFormat = formatSelect.value;
        const currentSelection = scoringModeSelect.value;
        
        // Start with original HTML structure
        scoringModeSelect.innerHTML = originalScoringModeHTML;
        
        // If a format is selected, add its specific aggregation options
        if (selectedFormat) {
            const selectedOption = formatSelect.options[formatSelect.selectedIndex];
            const aggregations = selectedOption.dataset.aggregations;
            
            if (aggregations) {
                const aggValues = aggregations.split(',').map(a => a.trim());
                const formatSpecificGroup = scoringModeSelect.querySelector('optgroup[label="Format-Specific Modes"]');
                
                // Add unique aggregation options from the selected format
                aggValues.forEach(agg => {
                    if (agg && !['average', 'best', 'total', 'as_per_format'].includes(agg.toLowerCase())) {
                        // Check if option already exists
                        const existingOption = formatSpecificGroup.querySelector(`option[value="${agg}"]`);
                        if (!existingOption) {
                            const newOption = document.createElement('option');
                            newOption.value = agg;
                            newOption.textContent = agg.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                            formatSpecificGroup.appendChild(newOption);
                        }
                    }
                });
            }
        }
        
        // Filter options based on sport
        if (selectedSport) {
            const sportKey = selectedSport.toLowerCase().replace(/[\s-]/g, '_');
            const availableModes = sportScoringModes[sportKey] || sportScoringModes.default;
            
            // Hide options not relevant to this sport
            const allOptions = scoringModeSelect.querySelectorAll('option');
            allOptions.forEach(option => {
                const optionValue = option.value;
                
                // Skip the empty option
                if (optionValue === '') return;
                
                const isStandardMode = ['average', 'best', 'total', 'as_per_format'].includes(optionValue);
                
                if (isStandardMode && !availableModes.includes(optionValue)) {
                    option.style.display = 'none';
                } else {
                    option.style.display = '';
                }
            });
        }
        
        // Restore selection if it still exists
        if (currentSelection) {
            const optionExists = Array.from(scoringModeSelect.options).some(opt => opt.value === currentSelection && opt.style.display !== 'none');
            if (optionExists) {
                scoringModeSelect.value = currentSelection;
            }
        }
    }
    
    function filterScoringFormats() {
        const selectedSport = sportSelect.value;
        const currentSelection = formatSelect.value;
        
        console.log('Filtering scoring formats for sport:', selectedSport);
        console.log('Total available format options:', allFormatOptions.length);
        
        // Clear current options except the first one
        formatSelect.innerHTML = '<option value="">Select Format</option>';
        
        if (selectedSport) {
            // Filter and add matching options
            let hasMatchingOptions = false;
            let matchCount = 0;
            
            allFormatOptions.forEach(option => {
                if (option.value && option.dataset.sport) {
                    const optionSport = option.dataset.sport.toLowerCase().trim();
                    const selectedSportNorm = selectedSport.toLowerCase().trim();
                    
                    console.log('Comparing format sport:', optionSport, 'with selected sport:', selectedSportNorm);
                    
                    // Check for exact match first, then partial matches
                    let isMatch = false;
                    
                    // Exact match
                    if (optionSport === selectedSportNorm) {
                        isMatch = true;
                        console.log('Exact match found:', option.textContent);
                    }
                    // Handle variations like "snowboard" vs "snowboarding"
                    else if (selectedSportNorm === 'snowboard' && 
                             (optionSport.includes('snowboard') || optionSport.includes('snow'))) {
                        isMatch = true;
                        console.log('Snowboard variant match found:', option.textContent);
                    }
                    // Handle other sport variations
                    else if (optionSport.includes(selectedSportNorm) || selectedSportNorm.includes(optionSport)) {
                        // Additional check to avoid false positives
                        if (selectedSportNorm.length >= 4 && optionSport.length >= 4) {
                            isMatch = true;
                            console.log('Partial match found:', option.textContent);
                        }
                    }
                    
                    if (isMatch) {
                        const newOption = option.cloneNode(true);
                        if (newOption.value === currentSelection) {
                            newOption.selected = true;
                        }
                        formatSelect.appendChild(newOption);
                        hasMatchingOptions = true;
                        matchCount++;
                    }
                }
            });
            
            console.log('Found', matchCount, 'matching formats for', selectedSport);
            
            // Show message if no formats found for the selected sport
            if (!hasMatchingOptions) {
                const noFormatsOption = document.createElement('option');
                noFormatsOption.value = '';
                noFormatsOption.textContent = 'No scoring formats available for ' + selectedSport.replace('_', ' ');
                noFormatsOption.disabled = true;
                noFormatsOption.style.fontStyle = 'italic';
                noFormatsOption.style.color = '#6c757d';
                formatSelect.appendChild(noFormatsOption);
                
                console.log('No specific formats found for sport:', selectedSport);
                
                // Optionally add a link to create new format
                const createFormatOption = document.createElement('option');
                createFormatOption.value = '';
                createFormatOption.textContent = '→ Create new format for ' + selectedSport.replace('_', ' ');
                createFormatOption.disabled = true;
                createFormatOption.style.fontStyle = 'italic';
                createFormatOption.style.color = '#0d6efd';
                formatSelect.appendChild(createFormatOption);
            }
            
            // Add visual feedback
            formatSelect.classList.add('border-success');
            setTimeout(() => {
                formatSelect.classList.remove('border-success');
            }, 1500);
        } else {
            // If no sport selected, show all formats
            allFormatOptions.forEach(option => {
                if (option.value) {
                    const newOption = option.cloneNode(true);
                    if (newOption.value === currentSelection) {
                        newOption.selected = true;
                    }
                    formatSelect.appendChild(newOption);
                }
            });
        }
        
        // Update the help text to show filtering status
        const helpText = formatSelect.parentElement.querySelector('.form-text');
        if (helpText && selectedSport) {
            helpText.innerHTML = `<i class="fas fa-filter me-1 text-success"></i>Showing formats for <strong>${selectedSport.replace('_', ' ')}</strong> only. 
                                 <a href="scoring_formats.php" target="_blank">Manage formats</a>`;
        } else if (helpText) {
            helpText.innerHTML = `<i class="fas fa-filter me-1"></i>Formats are automatically filtered by selected sport discipline. 
                                 <a href="scoring_formats.php" target="_blank">Manage formats</a>`;
        }
        
        // Trigger change event to update other dependent fields
        formatSelect.dispatchEvent(new Event('change'));
    }
    
    function populateFieldsFromFormat() {
        const selectedOption = formatSelect.options[formatSelect.selectedIndex];
        
        if (selectedOption && selectedOption.value) {
            const runs = selectedOption.dataset.runs;
            const aggregations = selectedOption.dataset.aggregations;
            const totalRounds = selectedOption.dataset.totalRounds;
            
            // First populate new aggregation options
            populateScoringModeOptions();
            
            // Populate Runs Per Heat (use first run value or most common)
            if (runs) {
                const runValues = runs.split(',').map(r => parseInt(r.trim())).filter(r => !isNaN(r));
                if (runValues.length > 0) {
                    // Use the most common run value or the first one
                    const mostCommonRuns = runValues.sort((a,b) => 
                        runValues.filter(v => v === a).length - runValues.filter(v => v === b).length
                    ).pop();
                    runsPerHeatInput.value = mostCommonRuns;
                }
            }
            
            // Populate Total Heats (use round count)
            if (totalRounds && parseInt(totalRounds) > 0) {
                totalHeatsInput.value = totalRounds;
            }
            
            // Intelligently select scoring mode based on aggregation
            if (aggregations) {
                const aggValues = aggregations.split(',').map(a => a.trim().toLowerCase());
                let recommendedMode = '';
                
                // Check if all aggregations are the same
                const uniqueAggs = [...new Set(aggValues)];
                
                // Enhanced logic for automatic scoring mode selection
                if (uniqueAggs.length === 1) {
                    // Single aggregation method across all rounds
                    const singleAgg = uniqueAggs[0];
                    
                    // Try to match with standard modes first with improved pattern matching
                    if (singleAgg.includes('average') || singleAgg.includes('mean') || 
                        singleAgg.includes('avg') || singleAgg === 'average of 2' || 
                        singleAgg === 'average of 3') {
                        recommendedMode = 'average';
                    } else if (singleAgg.includes('best') || singleAgg.includes('max') || 
                              singleAgg.includes('highest') || singleAgg === 'best run' || 
                              singleAgg.includes('best from') || singleAgg.includes('best of')) {
                        recommendedMode = 'best';
                    } else if (singleAgg.includes('sum') || singleAgg.includes('total') || 
                              singleAgg.includes('cumulative') || singleAgg.includes('combined')) {
                        recommendedMode = 'total';
                    } else {
                        // For specific aggregation methods, try to find exact match first
                        const availableOptions = Array.from(scoringModeSelect.options);
                        const exactMatch = availableOptions.some(opt => opt.value === singleAgg);
                        
                        if (exactMatch) {
                            recommendedMode = singleAgg;
                        } else {
                            // Default to "as_per_format" for unrecognized single aggregations
                            recommendedMode = 'as_per_format';
                        }
                    }
                } else {
                    // Multiple different aggregation methods
                    // Analyze the pattern to make intelligent decision
                    const hasAverage = aggValues.some(agg => agg.includes('average') || agg.includes('mean'));
                    const hasBest = aggValues.some(agg => agg.includes('best') || agg.includes('max'));
                    const hasTotal = aggValues.some(agg => agg.includes('sum') || agg.includes('total'));
                    
                    if (hasAverage && !hasBest && !hasTotal) {
                        recommendedMode = 'average';
                    } else if (hasBest && !hasAverage && !hasTotal) {
                        recommendedMode = 'best';
                    } else if (hasTotal && !hasAverage && !hasBest) {
                        recommendedMode = 'total';
                    } else {
                        // Mixed aggregation methods - use "as_per_format"
                        recommendedMode = 'as_per_format';
                    }
                }
                
                // Auto-select the recommended mode if available
                const availableOptions = Array.from(scoringModeSelect.options);
                const modeExists = availableOptions.some(opt => 
                    opt.value === recommendedMode && 
                    opt.style.display !== 'none' && 
                    !opt.disabled
                );
                
                if (modeExists) {
                    scoringModeSelect.value = recommendedMode;
                    
                    // Trigger visual feedback
                    scoringModeSelect.classList.add('border-success');
                    setTimeout(() => {
                        scoringModeSelect.classList.remove('border-success');
                    }, 1500);
                } else {
                    // Fallback hierarchy: as_per_format -> best -> average -> total
                    const fallbackModes = ['as_per_format', 'best', 'average', 'total'];
                    for (const fallbackMode of fallbackModes) {
                        const fallbackExists = availableOptions.some(opt => 
                            opt.value === fallbackMode && 
                            opt.style.display !== 'none' && 
                            !opt.disabled
                        );
                        if (fallbackExists) {
                            scoringModeSelect.value = fallbackMode;
                            break;
                        }
                    }
                }
            } else {
                // No aggregation data available - make educated guess based on sport and rounds
                let defaultMode = 'average'; // Default fallback
                
                if (totalRounds && parseInt(totalRounds) === 1) {
                    defaultMode = 'best'; // Single round typically uses best score
                } else if (totalRounds && parseInt(totalRounds) > 1) {
                    defaultMode = 'average'; // Multiple rounds typically use average
                }
                
                // Apply sport-specific defaults if no aggregation data
                const selectedSport = sportSelect.value.toLowerCase();
                if (selectedSport.includes('freestyle') || selectedSport.includes('park') || selectedSport.includes('street')) {
                    defaultMode = 'best';
                } else if (selectedSport.includes('figure') || selectedSport.includes('dance')) {
                    defaultMode = 'total';
                }
                
                const availableOptions = Array.from(scoringModeSelect.options);
                const defaultExists = availableOptions.some(opt => 
                    opt.value === defaultMode && 
                    opt.style.display !== 'none' && 
                    !opt.disabled
                );
                
                if (defaultExists) {
                    scoringModeSelect.value = defaultMode;
                }
            }
        }
    }
    
    // Event listeners for coordinated updates
    sportSelect.addEventListener('change', function() {
        console.log('Sport changed to:', this.value);
        populateScoringModeOptions();
        filterScoringFormats();
    });
    
    // Populate fields and update scoring modes when format changes
    formatSelect.addEventListener('change', function() {
        console.log('Format changed to:', this.value);
        populateFieldsFromFormat();
    });
    
    // Auto-trigger when sport changes to update format-dependent scoring modes
    sportSelect.addEventListener('change', function() {
        // Small delay to ensure format filtering is complete
        setTimeout(() => {
            if (formatSelect.value) {
                populateFieldsFromFormat();
            }
        }, 100);
    });
    
    // Initial setup on page load
    console.log('Initializing form...');
    populateScoringModeOptions();
    
    // Filter formats based on current sport selection
    if (sportSelect.value) {
        console.log('Initial sport value:', sportSelect.value);
        filterScoringFormats();
    }
    
    // Initial population if format is already selected
    if (formatSelect.value) {
        console.log('Initial format value:', formatSelect.value);
        // Small delay to ensure all elements are ready
        setTimeout(() => {
            populateFieldsFromFormat();
        }, 200);
    }
});

function confirmDelete() {
    if (confirm('Are you sure you want to delete this event? This action cannot be undone.')) {
        window.location.href = 'event_delete.php?id=<?= $event_id ?>';
    }
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<?php include 'footer.php'; ?>
</body>
</html>