<?php
/*
Configuration Management:
getSavedConfigurations($event_id) - Get all configurations for an event
getConfiguration($config_id) - Get specific configuration by ID
updateConfiguration($config_id, $config_data) - Update existing configuration
deleteConfiguration($config_id) - Delete configuration
duplicateConfiguration($config_id, $new_name) - Duplicate configuration with new name
Preview Functions:
previewConfiguration($config) - Generate preview data
generateConfigurationPreviewHTML($preview_data) - Generate HTML preview
New AJAX Endpoints:
action=get_configurations - Get all configurations for an event
action=get_config - Get specific configuration
action=update_config - Update configuration
action=delete_config - Delete configuration
action=duplicate_config - Duplicate configuration
action=preview_config - Preview configuration (supports both saved configs and form data)

Usage Examples:

// Get all configurations
fetch('ajax_generate_results.php?action=get_configurations&event_id=123');

// Preview configuration
fetch('ajax_generate_results.php?action=preview_config&config_id=456&format=html');

// Update configuration
fetch('ajax_generate_results.php', {
    method: 'POST',
    body: new URLSearchParams({
        action: 'update_config',
        config_id: '456',
        config_name: 'Updated Results',
        event_id: '123',
        // ... other config data
    })
});

// Delete configuration
fetch('ajax_generate_results.php?action=delete_config&config_id=456');

// Duplicate configuration
fetch('ajax_generate_results.php?action=duplicate_config&config_id=456&new_name=Copy of Results');



*/
include '../includes/auth.php';
include '../includes/db.php';

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    if (isset($_POST['action']) && $_POST['action'] === 'get_event_heats') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                $heats_stmt = $pdo->prepare("
                    SELECT DISTINCT 
                        ep.heat_number
                        
                    FROM event_participants ep
                    WHERE ep.event_id = ? 
                   ORDER BY ep.heat_number
                ");
                $heats_stmt->execute([$event_id]);
                $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'heats' => $heats]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event ID']);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'get_categories') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                $categories_stmt = $pdo->prepare("
                    SELECT DISTINCT 
                        COALESCE(p.category, 'No Category') as category, 
                        COALESCE(p.gender, 'U') as gender, 
                        MIN(YEAR(COALESCE(p.date_of_birth, '1900-01-01'))) as min_year, 
                        MAX(YEAR(COALESCE(p.date_of_birth, '2030-01-01'))) as max_year,
                        COUNT(*) as participant_count
                    FROM event_participants ep
                    JOIN participants p ON ep.participant_id = p.id
                    WHERE ep.event_id = ?
                    GROUP BY COALESCE(p.category, 'No Category'), COALESCE(p.gender, 'U')
                    ORDER BY COALESCE(p.category, 'No Category'), COALESCE(p.gender, 'U')
                ");
                $categories_stmt->execute([$event_id]);
                $categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'categories' => $categories]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event ID']);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'save_result_config') {
        $config_data = [
            'event_id' => $_POST['event_id'],
            'config_name' => $_POST['config_name'],
            'selected_heats' => $_POST['selected_heats'],
            'categories' => $_POST['categories'],
            'gender' => $_POST['gender'],
            'year_from' => $_POST['year_from'],
            'year_to' => $_POST['year_to'],
            'scoring_method' => $_POST['scoring_method'],
            'count_best_runs' => $_POST['count_best_runs'],
            'count_from_heats' => $_POST['count_from_heats'],
            'display_columns' => $_POST['display_columns'],
            'sort_by' => $_POST['sort_by'],
            'sort_order' => $_POST['sort_order']
        ];
        
        try {
            // Check if config with same name exists
            $check_stmt = $pdo->prepare("SELECT id FROM result_configurations WHERE event_id = ? AND config_name = ?");
            $check_stmt->execute([$config_data['event_id'], $config_data['config_name']]);
            
            if ($check_stmt->fetch()) {
                // Update existing
                $stmt = $pdo->prepare("UPDATE result_configurations SET config_data = ?, updated_at = NOW() WHERE event_id = ? AND config_name = ?");
                $stmt->execute([json_encode($config_data), $config_data['event_id'], $config_data['config_name']]);
            } else {
                // Insert new
                $stmt = $pdo->prepare("INSERT INTO result_configurations (event_id, config_name, config_data, created_at) VALUES (?, ?, ?, NOW())");
                $stmt->execute([$config_data['event_id'], $config_data['config_name'], json_encode($config_data)]);
            }
            
            echo json_encode(['success' => true, 'message' => 'Configuration saved successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'load_saved_configs') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                $configs_stmt = $pdo->prepare("
                    SELECT id, config_name, config_data, created_at, updated_at
                    FROM result_configurations
                    WHERE event_id = ?
                    ORDER BY updated_at DESC
                ");
                $configs_stmt->execute([$event_id]);
                $configs = $configs_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                foreach ($configs as &$config) {
                    $config['config_data'] = json_decode($config['config_data'], true);
                }
                
                echo json_encode(['success' => true, 'configs' => $configs]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event ID']);
        }
        exit;
    }
    
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

// Get events for dropdown
$events_stmt = $pdo->prepare("SELECT id, name, date FROM events ORDER BY date DESC, name");
$events_stmt->execute();
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Final Results Configuration</title>
    <!-- style skin holder -->
<link id="bootswatch-theme"
      href="/v2/assets/bootswatch/<?= btTheme('nameCode') ?>/bootstrap.min.css"
      rel="stylesheet">
<link rel="stylesheet" href="/v2/assets/css/backgrounds.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    
    <style>
        .config-section {
            
            
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .heat-checkbox {
            margin: 0.25rem;
        }
        
        .category-item {
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 0.75rem;
            margin: 0.25rem;
            background: white;
        }
        
        .preview-table {
            font-size: 0.9rem;
        }
        
        .scoring-method-info {
            background: #e3f2fd;
            border: 1px solid #90caf9;
            border-radius: 6px;
            padding: 0.75rem;
            margin-top: 0.5rem;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,.3);
            border-radius: 50%;
            border-top-color: #007bff;
            animation: spin 1s ease-in-out infinite;
        }
        
        .config-item {
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .config-item:hover {
            background-color: #f8f9fa;
        }
        
        .config-item.selected {
            border-color: #0d6efd !important;
            background-color: #e7f1ff;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>

<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <div class="row">
            <div class="col-12">
                <!-- Header -->
                <div class="border-0 shadow-none card bg-primary text-white mb-4">
                    <div class="border-0 shadow-none card-header">
                        <h2 class="card-title mb-0">
                            <i class="fas fa-trophy me-2"></i>Final Results Configuration
                        </h2>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Select Event</label>
                                <select class="form-select" id="eventSelect">
                                    <option value="">Choose an event</option>
                                    <?php foreach ($events as $event): ?>
                                        <option value="<?= $event['id'] ?>">
                                            <?= htmlspecialchars($event['name']) ?> 
                                            (<?= date('M d, Y', strtotime($event['date'])) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Configuration Name</label>
                                <input type="text" class="form-control" id="configName" placeholder="e.g., Overall Results, Junior Category">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Configuration Form -->
                <div id="configForm" style="display: none;">
                    <div class="row">
                        <div class="col-lg-8">
                            <!-- Heat Selection -->
                            <div class="border-0 shadow-none card config-section">
                                <h5><i class="fas fa-fire me-2"></i>Heat Selection</h5>
                                <p class="text-muted">Choose which heats to include in the final results calculation</p>
                                <div id="heatSelection">
                                    <!-- Dynamic content -->
                                </div>
                            </div>
                            
                            <!-- Category & Filters -->
                            <div class="border-0 shadow-none card config-section">
                                <h5><i class="fas fa-filter me-2"></i>Participant Filters</h5>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Categories</label>
                                        <div id="categorySelection">
                                            <!-- Dynamic content -->
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Gender</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="genderMale" value="M" checked>
                                            <label class="form-check-label" for="genderMale">Male</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="genderFemale" value="F" checked>
                                            <label class="form-check-label" for="genderFemale">Female</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="genderOther" value="O" checked>
                                            <label class="form-check-label" for="genderOther">Other/Not Specified</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">Birth Year From</label>
                                        <input type="number" class="form-control" id="yearFrom" min="1900" max="2030" placeholder="e.g., 1990">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Birth Year To</label>
                                        <input type="number" class="form-control" id="yearTo" min="1900" max="2030" placeholder="e.g., 2010">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Scoring Method -->
                            <div class="border-0 shadow-none card config-section">
                                <h5><i class="fas fa-calculator me-2"></i>Scoring Method</h5>
                                
                                <div class="mb-3">
                                    <select class="form-select" id="scoringMethod">
                                        <option value="best_single">Best Single Run</option>
                                        <option value="best_average">Best Average from X runs</option>
                                        <option value="best_x_from_n">Best X runs from N heats</option>
                                        <option value="total_points">Total Points (all runs)</option>
                                        <option value="average_all">Average of All Runs</option>
                                    </select>
                                </div>
                                
                                <div id="scoringOptions">
                                    <!-- Dynamic options based on scoring method -->
                                </div>
                                
                                <div class="scoring-method-info" id="scoringInfo">
                                    <!-- Dynamic explanation -->
                                </div>
                            </div>
                            
                            <!-- Display Options -->
                            <div class="border-0 shadow-none card config-section">
                                <h5><i class="fas fa-table me-2"></i>Display Options</h5>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Columns to Display</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colPosition" checked>
                                            <label class="form-check-label" for="colPosition">Position</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colBipNumber" checked>
                                            <label class="form-check-label" for="colBipNumber">BIB Number</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colName" checked>
                                            <label class="form-check-label" for="colName">Name</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colCategory">
                                            <label class="form-check-label" for="colCategory">Category</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colClub">
                                            <label class="form-check-label" for="colClub">Club</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colFisCode">
                                            <label class="form-check-label" for="colFisCode">FIS Code</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colLicenceCode">
                                            <label class="form-check-label" for="colLicenceCode">Licence Code</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colGender">
                                            <label class="form-check-label" for="colGender">Gender</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colAge">
                                            <label class="form-check-label" for="colAge">Age</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colFinalScore" checked>
                                            <label class="form-check-label" for="colFinalScore">Final Score</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colSummary">
                                            <label class="form-check-label" for="colSummary">
                                                Summary Statistics
                                                <small class="text-muted d-block">Total runs, best score, average score, heats participated</small>
                                            </label>
                                        </div>
                                        <div class="form-check">
    <input class="form-check-input" type="checkbox" id="colIndividualHeats">
    <label class="form-check-label" for="colIndividualHeats">
        Individual Heat Columns
        <small class="text-muted d-block">Shows each heat in separate columns: H1(R1 R2 R3 R4) H1Avg | H2(R1 R2 R3 R4) H2Avg</small>
    </label>
</div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="colIndividualRuns">
                                            <label class="form-check-label" for="colIndividualRuns">
                                                Individual Run Scores
                                                <small class="text-muted d-block">Detailed breakdown of each run (H1R1: 85.50, H2R1: 88.20, etc.)</small>
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Sort Results By</label>
                                        <select class="form-select mb-2" id="sortBy">
                                            <option value="final_score">Final Score</option>
                                            <option value="name">Name</option>
                                            <option value="bib_number">BIB Number</option>
                                            <option value="category">Category</option>
                                        </select>
                                        
                                        <select class="form-select mb-3" id="sortOrder">
                                            <option value="DESC">Highest to Lowest</option>
                                            <option value="ASC">Lowest to Highest</option>
                                        </select>
                                        
                                        <div class="border-0 shadow-none card bg-light">
                                            <div class="border-0 shadow-none card-body p-3">
                                                <h6 class="card-title mb-2">
                                                    <i class="fas fa-info-circle me-1"></i>Column Descriptions
                                                </h6>
                                                <ul class="list-unstyled mb-0 small">
                                                    <li><strong>Summary Statistics:</strong> Shows total runs across all heats, best score achieved, average score, and list of heats participated in</li>
                                                    <li class="mt-1"><strong>Individual Runs:</strong> Lists all runs with format "H1R1: 85.50" (Heat 1, Run 1: Score 85.50)</li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <!-- Saved Configurations -->
                            <div class="border-0 shadow-none card mb-3">
                                <div class="border-0 shadow-none card-header">
                                    <h6 class="mb-0"><i class="fas fa-save me-2"></i>Saved Configurations</h6>
                                </div>
                                <div class="border-0 shadow-none card-body">
                                    <div id="savedConfigs">
                                        <p class="text-muted text-center">No saved configurations</p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Actions -->
                            <div class="border-0 shadow-none card">
                                <div class="border-0 shadow-none card-header">
                                    <h6 class="mb-0"><i class="fas fa-cogs me-2"></i>Actions</h6>
                                </div>
                                <div class="border-0 shadow-none card-body">
                                    <div class="d-grid gap-2">
                                        <button class="btn btn-success" id="saveConfigBtn">
                                            <i class="fas fa-save me-2"></i>Save Configuration
                                        </button>
                                        
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-primary" id="previewBtn">
                                                <i class="fas fa-eye me-2"></i>Preview Results
                                            </button>
                                            <button class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                                                <span class="visually-hidden">Toggle Dropdown</span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="#" onclick="previewConfiguration()">
                                                    <i class="fas fa-search me-2"></i>Preview Configuration
                                                </a></li>
                                                <li><a class="dropdown-item" href="#" onclick="previewResults()">
                                                    <i class="fas fa-table me-2"></i>Preview Results Table
                                                </a></li>
                                            </ul>
                                        </div>
                                        
                                        <button class="btn btn-info" id="generateBtn">
                                            <i class="fas fa-trophy me-2"></i>Generate Final Results
                                        </button>
                                        
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-secondary" id="exportBtn">
                                                <i class="fas fa-download me-2"></i>Export Results
                                            </button>
                                            <button class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                                                <span class="visually-hidden">Toggle Dropdown</span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="#" onclick="exportResults('csv')">
                                                    <i class="fas fa-file-csv me-2"></i>Export as CSV
                                                </a></li>
                                                <li><a class="dropdown-item" href="#" onclick="exportResults('excel')">
                                                    <i class="fas fa-file-excel me-2"></i>Export as Excel
                                                </a></li>
                                                <li><a class="dropdown-item" href="#" onclick="exportResults('pdf')">
                                                    <i class="fas fa-file-pdf me-2"></i>Export as PDF
                                                </a></li>
                                            </ul>
                                        </div>
                                        
                                        <hr class="my-2">
                                        
                                        <div class="btn-group w-100" role="group">
                                            <button class="btn btn-outline-warning btn-sm" onclick="editSelectedConfig()">
                                                <i class="fas fa-edit me-1"></i>Edit
                                            </button>
                                            <button class="btn btn-outline-info btn-sm" onclick="duplicateSelectedConfig()">
                                                <i class="fas fa-copy me-1"></i>Duplicate
                                            </button>
                                            <button class="btn btn-outline-danger btn-sm" onclick="deleteSelectedConfig()">
                                                <i class="fas fa-trash me-1"></i>Delete
                                            </button>
                                        </div>
                                        
                                        <button class="btn btn-outline-primary btn-sm w-100" onclick="refreshConfigs()">
                                            <i class="fas fa-sync me-2"></i>Refresh Configurations
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Preview Section -->
                <div id="previewSection" style="display: none;">
                    <div class="border-0 shadow-none card mt-4">
                        <div class="border-0 shadow-none card-header">
                            <h5 class="mb-0"><i class="fas fa-eye me-2"></i>Results Preview</h5>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <div id="previewContainer">
                                <!-- Dynamic preview content -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentEventId = null;
        let selectedConfigId = null;
        
        document.addEventListener('DOMContentLoaded', function() {
            const eventSelect = document.getElementById('eventSelect');
            const configForm = document.getElementById('configForm');
            const scoringMethod = document.getElementById('scoringMethod');
            
            // Event selection handler
            eventSelect.addEventListener('change', function() {
                currentEventId = this.value;
                if (currentEventId) {
                    configForm.style.display = 'block';
                    loadEventData(currentEventId);
                    loadSavedConfigs(currentEventId);
                } else {
                    configForm.style.display = 'none';
                }
            });
            
            // Scoring method change handler
            scoringMethod.addEventListener('change', updateScoringOptions);
            
            // Button handlers
            document.getElementById('saveConfigBtn').addEventListener('click', saveConfiguration);
            document.getElementById('previewBtn').addEventListener('click', previewResults);
            document.getElementById('generateBtn').addEventListener('click', generateResults);
            document.getElementById('exportBtn').addEventListener('click', function() {
                exportResults('csv');
            });
            
            // Initialize
            updateScoringOptions();
        });
        
        function loadEventData(eventId) {
            console.log('Loading event data for event ID:', eventId);
            
            // Show loading for heats
            document.getElementById('heatSelection').innerHTML = '<div class="text-center"><span class="loading-spinner"></span> Loading heats...</div>';
            
            // Show loading for categories
            document.getElementById('categorySelection').innerHTML = '<div class="text-center"><span class="loading-spinner"></span> Loading categories...</div>';
            
            // Load heats
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ajax=1&action=get_event_heats&event_id=${eventId}`
            })
            .then(response => response.json())
            .then(data => {
                console.log('Heats response:', data);
                if (data.success) {
                    renderHeats(data.heats);
                } else {
                    document.getElementById('heatSelection').innerHTML = `<div class="alert alert-warning">Error loading heats: ${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading heats:', error);
                document.getElementById('heatSelection').innerHTML = '<div class="alert alert-danger">Error loading heats</div>';
            });
            
            // Load categories
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ajax=1&action=get_categories&event_id=${eventId}`
            })
            .then(response => response.json())
            .then(data => {
                console.log('Categories response:', data);
                if (data.success) {
                    renderCategories(data.categories);
                } else {
                    document.getElementById('categorySelection').innerHTML = `<div class="alert alert-warning">Error loading categories: ${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading categories:', error);
                document.getElementById('categorySelection').innerHTML = '<div class="alert alert-danger">Error loading categories</div>';
            });
        }
        
        function renderHeats(heats) {
            const container = document.getElementById('heatSelection');
            
            if (!heats || heats.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No heats found for this event</div>';
                return;
            }
            
            let html = '<div class="d-flex gap-2 mb-2">';
            html += '<button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllHeats(true)">Select All</button>';
            html += '<button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllHeats(false)">Deselect All</button>';
            html += '</div><div class="row">';
            
            heats.forEach(heat => {
                const heatName = heat.heat_name ? ` - ${heat.heat_name}` : '';
                const participantCount = heat.participant_count ? ` (${heat.participant_count} participants)` : '';
                
                html += `
                    <div class="col-md-4 col-sm-6">
                        <div class="form-check heat-checkbox">
                            <input class="form-check-input heat-select" type="checkbox" id="heat${heat.heat_number}" value="${heat.heat_number}" checked>
                            <label class="form-check-label" for="heat${heat.heat_number}">
                                Heat ${heat.heat_number}${heatName}${participantCount}
                            </label>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            container.innerHTML = html;
        }
        
        function renderCategories(categories) {
            const container = document.getElementById('categorySelection');
            
            if (!categories || categories.length === 0) {
                container.innerHTML = '<div class="alert alert-info">No categories found for this event</div>';
                return;
            }
            
            let html = '<div class="d-flex gap-2 mb-2">';
            html += '<button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllCategories(true)">Select All</button>';
            html += '<button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllCategories(false)">Deselect All</button>';
            html += '</div>';
            
            categories.forEach(cat => {
                const genderDisplay = cat.gender === 'M' ? 'Male' : cat.gender === 'F' ? 'Female' : 'Other';
                const yearRange = cat.min_year && cat.max_year ? ` (${cat.min_year}-${cat.max_year})` : '';
                
                html += `
                    <div class="form-check">
                        <input class="form-check-input category-select" type="checkbox" id="cat_${cat.category}_${cat.gender}" value="${cat.category}" data-gender="${cat.gender}" checked>
                        <label class="form-check-label" for="cat_${cat.category}_${cat.gender}">
                            <strong>${cat.category}</strong> - ${genderDisplay} - ${cat.participant_count} participants
                            <small class="text-muted">${yearRange}</small>
                        </label>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        function updateScoringOptions() {
            const method = document.getElementById('scoringMethod').value;
            const optionsContainer = document.getElementById('scoringOptions');
            const infoContainer = document.getElementById('scoringInfo');
            
            let optionsHtml = '';
            let infoHtml = '';
            
            switch (method) {
                case 'best_single':
                    infoHtml = '<strong>Best Single Run:</strong> Takes the highest score from any run across all selected heats.';
                    break;
                    
                case 'best_average':
                    optionsHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">Number of runs to average</label>
                                <input type="number" class="form-control" id="avgRunCount" min="2" max="10" value="3">
                            </div>
                        </div>
                    `;
                    infoHtml = '<strong>Best Average:</strong> Calculates the average of the specified number of best runs from all attempts.';
                    break;
                    
                case 'best_x_from_n':
                    optionsHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">Count best X runs</label>
                                <input type="number" class="form-control" id="bestXRuns" min="1" max="10" value="2">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">From N heats</label>
                                <input type="number" class="form-control" id="fromNHeats" min="1" max="20" value="3">
                            </div>
                        </div>
                    `;
                    infoHtml = '<strong>Best X from N:</strong> Takes the best X runs from the specified N heats and averages them.';
                    break;
                    
                case 'total_points':
                    infoHtml = '<strong>Total Points:</strong> Sums all scores from all runs in selected heats.';
                    break;
                    
                case 'average_all':
                    infoHtml = '<strong>Average All:</strong> Calculates the average of all runs from selected heats.';
                    break;
            }
            
            optionsContainer.innerHTML = optionsHtml;
            infoContainer.innerHTML = infoHtml;
        }
        
        function selectAllHeats(select) {
            document.querySelectorAll('.heat-select').forEach(checkbox => {
                checkbox.checked = select;
            });
        }
        
        function selectAllCategories(select) {
            document.querySelectorAll('.category-select').forEach(checkbox => {
                checkbox.checked = select;
            });
        }
        
        function saveConfiguration() {
            const configName = document.getElementById('configName').value.trim();
            if (!configName) {
                alert('Please enter a configuration name');
                return;
            }
            
            if (!currentEventId) {
                alert('Please select an event');
                return;
            }
            
            const config = gatherConfiguration();
            
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    ajax: '1',
                    action: 'save_result_config',
                    ...config
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Configuration saved successfully!');
                    loadSavedConfigs(currentEventId);
                } else {
                    alert('Error saving configuration: ' + data.message);
                }
            });
        }
        
        function gatherConfiguration() {
            const selectedHeats = Array.from(document.querySelectorAll('.heat-select:checked')).map(cb => cb.value);
            const selectedCategories = Array.from(document.querySelectorAll('.category-select:checked')).map(cb => cb.value);
            const selectedGenders = [];
            
            if (document.getElementById('genderMale').checked) selectedGenders.push('M');
            if (document.getElementById('genderFemale').checked) selectedGenders.push('F');
            if (document.getElementById('genderOther').checked) selectedGenders.push('O');
            
             const displayColumns = [];
    document.querySelectorAll('input[id^="col"]:checked').forEach(cb => {
        let columnName = cb.id.replace('col', '').toLowerCase();
        // Handle special case for Individual Heats
        if (columnName === 'individualheats') {
            columnName = 'individualheats';
        }
        displayColumns.push(columnName);
    });
            
            return {
                event_id: currentEventId,
                config_name: document.getElementById('configName').value,
                selected_heats: JSON.stringify(selectedHeats),
                categories: JSON.stringify(selectedCategories),
                gender: JSON.stringify(selectedGenders),
                year_from: document.getElementById('yearFrom').value || '',
                year_to: document.getElementById('yearTo').value || '',
                scoring_method: document.getElementById('scoringMethod').value,
                count_best_runs: document.getElementById('avgRunCount')?.value || document.getElementById('bestXRuns')?.value || '',
                count_from_heats: document.getElementById('fromNHeats')?.value || '',
                display_columns: JSON.stringify(displayColumns),
                sort_by: document.getElementById('sortBy').value,
                sort_order: document.getElementById('sortOrder').value
            };
        }
        
        function loadSavedConfigs(eventId) {
            fetch(window.location.href, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ajax=1&action=load_saved_configs&event_id=${eventId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderSavedConfigs(data.configs);
                } else {
                    console.error('Error loading saved configs:', data.message);
                }
            })
            .catch(error => {
                console.error('Error loading saved configs:', error);
            });
        }
        
        function renderSavedConfigs(configs) {
            const container = document.getElementById('savedConfigs');
            
            if (configs.length === 0) {
                container.innerHTML = '<p class="text-muted text-center">No saved configurations</p>';
                return;
            }
            
            let html = '';
            configs.forEach(config => {
                html += `
                    <div class="border rounded p-2 mb-2 config-item" data-config-id="${config.id}" onclick="selectConfig(${config.id}, this)">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <strong>${config.config_name}</strong><br>
                                <small class="text-muted">
                                    Updated: ${new Date(config.updated_at).toLocaleDateString()}
                                </small>
                            </div>
                            <div class="btn-group-vertical">
                                <button class="btn btn-sm btn-outline-primary" onclick="event.stopPropagation(); loadConfig(${config.id})" title="Load Configuration">
                                    <i class="fas fa-play"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-info" onclick="event.stopPropagation(); previewConfig(${config.id})" title="Preview Configuration">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        function selectConfig(configId, element) {
            // Remove previous selection
            document.querySelectorAll('.config-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // Add selection to clicked item
            element.classList.add('selected');
            selectedConfigId = configId;
        }
        
        function previewConfiguration() {
            const config = gatherConfiguration();
            
            fetch('ajax_generate_results.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'preview_config',
                    format: 'html',
                    ...config
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showPreviewModal('Configuration Preview', data.html);
                } else {
                    alert('Error previewing configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error previewing configuration');
            });
        }
        
        function previewConfig(configId) {
            fetch(`ajax_generate_results.php?action=preview_config&config_id=${configId}&format=html`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showPreviewModal('Configuration Preview', data.html);
                } else {
                    alert('Error previewing configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error previewing configuration');
            });
        }
        
        function editSelectedConfig() {
            if (!selectedConfigId) {
                alert('Please select a configuration to edit');
                return;
            }
            
            fetch(`ajax_generate_results.php?action=get_config&config_id=${selectedConfigId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadConfigurationIntoForm(data.configuration);
                } else {
                    alert('Error loading configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading configuration');
            });
        }
        
        function duplicateSelectedConfig() {
            if (!selectedConfigId) {
                alert('Please select a configuration to duplicate');
                return;
            }
            
            const newName = prompt('Enter name for the duplicated configuration:');
            if (!newName) return;
            
            fetch('ajax_generate_results.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'duplicate_config',
                    config_id: selectedConfigId,
                    new_name: newName
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Configuration duplicated successfully!');
                    loadSavedConfigs(currentEventId);
                } else {
                    alert('Error duplicating configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error duplicating configuration');
            });
        }
        
        function deleteSelectedConfig() {
            if (!selectedConfigId) {
                alert('Please select a configuration to delete');
                return;
            }
            
            if (!confirm('Are you sure you want to delete this configuration? This action cannot be undone.')) {
                return;
            }
            
            fetch(`ajax_generate_results.php?action=delete_config&config_id=${selectedConfigId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Configuration deleted successfully!');
                    selectedConfigId = null;
                    loadSavedConfigs(currentEventId);
                } else {
                    alert('Error deleting configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error deleting configuration');
            });
        }
        
        function loadConfig(configId) {
            fetch(`ajax_generate_results.php?action=get_config&config_id=${configId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadConfigurationIntoForm(data.configuration);
                    selectedConfigId = configId;
                } else {
                    alert('Error loading configuration: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading configuration');
            });
        }
        
        function loadConfigurationIntoForm(config) {
            const configData = config.config_data;
            
            // Load basic info
            document.getElementById('configName').value = configData.config_name || '';
            
            // Load selected heats
            const selectedHeats = JSON.parse(configData.selected_heats || '[]');
            document.querySelectorAll('.heat-select').forEach(checkbox => {
                checkbox.checked = selectedHeats.includes(checkbox.value);
            });
            
            // Load selected categories
            const selectedCategories = JSON.parse(configData.categories || '[]');
            document.querySelectorAll('.category-select').forEach(checkbox => {
                checkbox.checked = selectedCategories.includes(checkbox.value);
            });
            
            // Load gender selections
            const selectedGenders = JSON.parse(configData.gender || '[]');
            document.getElementById('genderMale').checked = selectedGenders.includes('M');
            document.getElementById('genderFemale').checked = selectedGenders.includes('F');
            document.getElementById('genderOther').checked = selectedGenders.includes('O');
            
            // Load year range
            document.getElementById('yearFrom').value = configData.year_from || '';
            document.getElementById('yearTo').value = configData.year_to || '';
            
            // Load scoring method
            document.getElementById('scoringMethod').value = configData.scoring_method || 'best_single';
            updateScoringOptions();
            
            // Load scoring options
            setTimeout(() => {
                if (document.getElementById('avgRunCount')) {
                    document.getElementById('avgRunCount').value = configData.count_best_runs || '';
                }
                if (document.getElementById('bestXRuns')) {
                    document.getElementById('bestXRuns').value = configData.count_best_runs || '';
                }
                if (document.getElementById('fromNHeats')) {
                    document.getElementById('fromNHeats').value = configData.count_from_heats || '';
                }
            }, 100);
            
            // Load display columns
            const displayColumns = JSON.parse(configData.display_columns || '[]');
            document.querySelectorAll('input[id^="col"]').forEach(checkbox => {
                const columnName = checkbox.id.replace('col', '').toLowerCase();
                checkbox.checked = displayColumns.includes(columnName);
            });
            
            // Load sort options
            document.getElementById('sortBy').value = configData.sort_by || 'final_score';
            document.getElementById('sortOrder').value = configData.sort_order || 'DESC';
        }
        
        function refreshConfigs() {
            if (currentEventId) {
                loadSavedConfigs(currentEventId);
            }
        }
        
        function previewResults() {
    const config = gatherConfiguration();

    const params = new URLSearchParams({
        action: 'generate',
        format: 'html',
        ...config
    });

    fetch(`ajax_generate_results.php?${params}`)
        .then(response => response.json()) // ✅ expect JSON
        .then(data => {
            if (data.success && data.html) {
                document.getElementById('resultModalBody').innerHTML = data.html;
            } else {
                document.getElementById('resultModalBody').innerHTML = '<div class="text-danger">⚠ Failed to load results.</div>';
            }
            new bootstrap.Modal(document.getElementById('resultModal')).show();
        })
        .catch(error => {
            console.error(error);
            document.getElementById('resultModalBody').innerHTML = '<div class="text-danger">⚠ AJAX error.</div>';
            new bootstrap.Modal(document.getElementById('resultModal')).show();
        });
}
        
        function generateResults() {
            const config = gatherConfiguration();
            
            const params = new URLSearchParams({
                action: 'generate',
                ...config
            });
            
            window.open(`ajax_generate_results.php?${params}`, '_blank');
        }
        
        function exportResults(format = 'csv') {
            const config = gatherConfiguration();
            
            const params = new URLSearchParams({
                action: 'generate',
                export: format,
                ...config
            });
            
            window.open(`ajax_generate_results.php?${params}`, '_blank');
        }
        
        function showPreviewModal(title, content) {
            // Create modal if it doesn't exist
            let modal = document.getElementById('previewModal');
            if (!modal) {
                const modalHtml = `
                    <div class="modal fade" id="previewModal" tabindex="-1">
                        <div class="modal-dialog modal-xl">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="previewModalTitle"></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body" id="previewModalBody">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                document.body.insertAdjacentHTML('beforeend', modalHtml);
                modal = document.getElementById('previewModal');
            }
            
            document.getElementById('previewModalTitle').textContent = title;
            document.getElementById('previewModalBody').innerHTML = content;
            
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
        }
    </script>
    <div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" 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="resultModalLabel">Generated Results</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="resultModalBody">
        <!-- HTML results will be injected here -->
      </div>
    </div>
  </div>
</div>

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