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

$selected_event = $_GET['event_id'] ?? null;
$selected_config_id = $_GET['config_id'] ?? null;

// Fetch events
$events = $pdo->query("SELECT id, name FROM events ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Fetch event data if selected
$heats = [];
$categories = [];
$saved_configurations = [];

if ($selected_event) {
    // Fetch heats
    $stmt = $pdo->prepare("SELECT heat_number, heat_name FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
    $stmt->execute([$selected_event]);
    $heats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch categories
    $stmt = $pdo->prepare("
        SELECT id, category_name, is_main_category, use_for_ranking 
        FROM event_categories 
        WHERE event_id = ? AND (is_main_category = 1 OR use_for_ranking = 1)
        ORDER BY is_main_category DESC, category_name
    ");
    $stmt->execute([$selected_event]);
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Also get participant-assigned categories for backward compatibility
    $stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL ORDER BY category");
    $stmt->execute([$selected_event]);
    $participant_categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    foreach ($participant_categories as $cat) {
        if (!in_array($cat, array_column($categories, 'category_name'))) {
            $categories[] = [
                'id' => null,
                'category_name' => $cat,
                'is_main_category' => 0,
                'use_for_ranking' => 0
            ];
        }
    }
    
    // Fetch saved configurations
    $stmt = $pdo->prepare("
        SELECT id, name, view_type, heat_number, category, status, display_order, created_at, configuration
        FROM result_configurations 
        WHERE event_id = ? AND view_type = 'summary_table'
        ORDER BY display_order ASC, name ASC
    ");
    $stmt->execute([$selected_event]);
    $saved_configurations = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Load specific configuration if requested
$active_config = null;
if ($selected_config_id && $selected_event) {
    $stmt = $pdo->prepare("SELECT * FROM result_configurations WHERE id = ? AND event_id = ?");
    $stmt->execute([$selected_config_id, $selected_event]);
    $active_config = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Summary Table Manager</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    
    <!-- Bootstrap JS (required for modals) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <style>
        .manager-container {
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 1.5rem;
            height: calc(100vh - 100px);
        }
        
        .sidebar {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            overflow-y: auto;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .main-panel {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            overflow-y: auto;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .config-list-item {
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .config-list-item:hover {
            border-color: #0d6efd;
            background: #f8f9fa;
        }
        
        .config-list-item.active {
            border-color: #0d6efd;
            background: #e7f1ff;
            font-weight: 600;
        }
        
        .config-checkbox {
            flex-shrink: 0;
            margin: 0;
        }
        
        .config-checkbox input {
            cursor: pointer;
        }
        
        .config-content {
            flex: 1;
            min-width: 0;
            cursor: pointer;
        }
        
        .config-list-item .config-name {
            font-size: 0.9rem;
            margin-bottom: 0.25rem;
        }
        
        .config-list-item .config-meta {
            font-size: 0.75rem;
            color: #6c757d;
        }
        
        .settings-panel {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .settings-section {
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .settings-section:last-child {
            margin-bottom: 0;
        }
        
        .settings-section-title {
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            color: #495057;
            margin-bottom: 0.75rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #dee2e6;
        }
        
        .checkbox-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 0.5rem;
        }
        
        .checkbox-item {
            display: flex;
            align-items: center;
            padding: 0.4rem;
        }
        
        .checkbox-item input {
            margin-right: 0.5rem;
        }
        
        .checkbox-item label {
            margin-bottom: 0;
            font-size: 0.875rem;
            cursor: pointer;
        }
        
        .preview-container {
            border: 2px solid #dee2e6;
            border-radius: 8px;
            padding: 1.5rem;
            background: white;
            min-height: 500px;
        }
        
        .preview-container.loading {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
        }
        
        .action-toolbar {
            position: sticky;
            top: 0;
            background: white;
            padding: 1rem 0;
            margin-bottom: 1rem;
            border-bottom: 2px solid #dee2e6;
            z-index: 100;
        }
        
        .btn-preset {
            font-size: 0.8rem;
            padding: 0.35rem 0.75rem;
        }
        
        .heat-selector {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 0.5rem;
            background: white;
            position: relative;
            z-index: 10;
        }
        
        .heat-checkbox {
            display: flex;
            align-items: center;
            padding: 0.4rem;
            cursor: pointer;
            position: relative;
            z-index: 11;
            pointer-events: auto;
        }
        
        .heat-checkbox:hover {
            background: #f8f9fa;
        }
        
        .heat-checkbox label {
            cursor: pointer;
            user-select: none;
            margin-bottom: 0;
            flex: 1;
            pointer-events: auto;
        }
        
        .heat-checkbox input[type="checkbox"] {
            cursor: pointer;
            margin-right: 0.5rem;
            position: relative;
            z-index: 12;
            pointer-events: auto;
            width: 16px;
            height: 16px;
        }
        
        .badge-status {
            font-size: 0.7rem;
            padding: 0.2rem 0.5rem;
        }
        
        .quick-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .quick-actions button {
            flex: 1;
            font-size: 0.75rem;
            padding: 0.35rem;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <!-- Simple Navigation -->
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/v2/">
                <i class="fas fa-home me-2"></i>StyleScore
            </a>
            <div>
                <a href="/v2/admin/" class="btn btn-sm btn-outline-light me-2">
                    <i class="fas fa-arrow-left me-1"></i>Admin Panel
                </a>
                <a href="/v2/logout.php" class="btn btn-sm btn-outline-danger">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>
    
    <div class="container-fluid p-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h3 class="mb-1">
                    <i class="fas fa-table me-2"></i>Summary Table Manager
                </h3>
                <p class="text-muted mb-0">Professional summary table configuration and export</p>
            </div>
            <div>
                <a href="event_start_list.php?view_type=summary_table<?= $selected_event ? '&event_id='.$selected_event : '' ?>" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-arrow-left me-1"></i>Classic View
                </a>
            </div>
        </div>
        
        <!-- Event Selector -->
        <div class="mb-3">
            <select id="eventSelector" class="form-select form-select-lg" onchange="handleEventChange()">
                <option value="">-- Select Event --</option>
                <?php foreach ($events as $event): ?>
                    <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($event['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <?php if ($selected_event): ?>
        <div class="manager-container">
            <!-- Sidebar: Saved Configurations -->
            <div class="sidebar">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0"><i class="fas fa-save me-2"></i>Saved</h6>
                    <div>
                        <button class="btn btn-danger btn-sm me-1" id="bulkDeleteBtn" style="display: none;" onclick="bulkDeleteConfigs()">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                        <button class="btn btn-primary btn-sm" onclick="showNewConfigDialog()">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </div>
                
                <div id="configList">
                    <?php if (empty($saved_configurations)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-folder-open fa-2x mb-2"></i>
                            <p class="small mb-0">No saved configurations</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($saved_configurations as $config): ?>
                            <div class="config-list-item <?= $selected_config_id == $config['id'] ? 'active' : '' ?>" 
                                 data-config-id="<?= $config['id'] ?>">
                                <div class="form-check config-checkbox">
                                    <input class="form-check-input" type="checkbox" value="<?= $config['id'] ?>" 
                                           id="config_<?= $config['id'] ?>" onchange="updateBulkDeleteButton()">
                                </div>
                                <div class="config-content" onclick="loadConfiguration(<?= $config['id'] ?>)">
                                    <div class="config-name"><?= htmlspecialchars($config['name']) ?></div>
                                    <div class="config-meta">
                                        <?php if ($config['heat_number']): ?>
                                            <span class="badge bg-warning text-dark badge-status">Heat <?= $config['heat_number'] ?></span>
                                        <?php endif; ?>
                                        <?php if ($config['category'] && $config['category'] !== 'all'): ?>
                                            <span class="badge bg-info text-dark badge-status"><?= htmlspecialchars($config['category']) ?></span>
                                        <?php endif; ?>
                                        <span class="badge bg-<?= $config['status'] === 'active' ? 'success' : 'secondary' ?> badge-status">
                                            <?= ucfirst($config['status']) ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="quick-actions">
                                    <button class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation(); loadConfiguration(<?= $config['id'] ?>)">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-outline-success btn-sm" onclick="event.stopPropagation(); duplicateConfig(<?= $config['id'] ?>)">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                    <button class="btn btn-outline-danger btn-sm" onclick="event.stopPropagation(); deleteConfig(<?= $config['id'] ?>, '<?= htmlspecialchars($config['name'], ENT_QUOTES) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Main Panel -->
            <div class="main-panel">
                <!-- Action Toolbar -->
                <div class="action-toolbar">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <div class="btn-group me-2" role="group">
                                <button class="btn btn-primary" onclick="generatePreview()">
                                    <i class="fas fa-sync me-1"></i>Preview
                                </button>
                                <button class="btn btn-success" onclick="saveCurrentConfiguration()">
                                    <i class="fas fa-save me-1"></i>Save
                                </button>
                            </div>
                            <div class="btn-group" role="group">
                                <button class="btn btn-outline-danger" onclick="exportFormat('pdf')">
                                    <i class="fas fa-file-pdf me-1"></i>PDF
                                </button>
                                <button class="btn btn-outline-success" onclick="exportFormat('csv')">
                                    <i class="fas fa-file-csv me-1"></i>CSV
                                </button>
                                <button class="btn btn-outline-info" onclick="exportFormat('json')">
                                    <i class="fas fa-code me-1"></i>JSON
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4 text-end">
                            <button class="btn btn-outline-secondary btn-sm" onclick="resetToDefaults()">
                                <i class="fas fa-undo me-1"></i>Reset
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Settings Panel -->
                <div class="settings-panel">
                    <div class="row">
                        <!-- Filters Section -->
                        <div class="col-md-6">
                            <div class="settings-section">
                                <div class="settings-section-title">
                                    <i class="fas fa-filter me-2"></i>Filters
                                </div>
                                
                                <!-- Heat Selection -->
                                <div class="mb-3">
                                    <label class="form-label small fw-semibold">Heat Selection</label>
                                    <div class="heat-selector">
                                        <div class="heat-checkbox">
                                            <input type="checkbox" id="heat_all" value="all" checked>
                                            <label for="heat_all">All Heats</label>
                                        </div>
                                        <?php foreach ($heats as $heat): ?>
                                            <div class="heat-checkbox">
                                                <input type="checkbox" class="heat-option" id="heat_<?= $heat['heat_number'] ?>" value="<?= $heat['heat_number'] ?>">
                                                <label for="heat_<?= $heat['heat_number'] ?>">Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' - ' . htmlspecialchars($heat['heat_name']) : '' ?></label>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <!-- Category Filter -->
                                <div class="mb-3">
                                    <label class="form-label small fw-semibold">Category</label>
                                    <select id="categoryFilter" class="form-select form-select-sm">
                                        <option value="all">All Categories</option>
                                        <?php foreach ($categories as $cat): ?>
                                            <option value="<?= $cat['id'] ?: htmlspecialchars($cat['category_name']) ?>">
                                                <?= htmlspecialchars($cat['category_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <!-- Gender Filter -->
                                <div class="mb-3">
                                    <label class="form-label small fw-semibold">Gender</label>
                                    <select id="genderFilter" class="form-select form-select-sm">
                                        <option value="all">All Genders</option>
                                        <option value="M">Male</option>
                                        <option value="F">Female</option>
                                    </select>
                                </div>
                                
                                <!-- Heat Direction -->
                                <div class="mb-3">
                                    <label class="form-label small fw-semibold">Heat Layout</label>
                                    <select id="heatDirection" class="form-select form-select-sm">
                                        <option value="row" selected>Side by Side (Row)</option>
                                        <option value="column">Stacked (Column)</option>
                                    </select>
                                    <small class="text-muted">Controls how multiple heats are displayed</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Display Options Section -->
                        <div class="col-md-6">
                            <div class="settings-section">
                                <div class="settings-section-title">
                                    <i class="fas fa-eye me-2"></i>Display Options
                                </div>
                                
                                <!-- Sort Options -->
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <label class="form-label small fw-semibold">Sort By</label>
                                        <select id="sortBy" class="form-select form-select-sm">
                                            <option value="OverallAverage">Overall Average</option>
                                            <option value="OverallBest">Overall Best</option>
                                            <option value="rank">Rank</option>
                                            <option value="bib_number">BIB Number</option>
                                            <option value="last_name">Last Name</option>
                                        </select>
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label small fw-semibold">Direction</label>
                                        <select id="sortDirection" class="form-select form-select-sm">
                                            <option value="desc">Descending</option>
                                            <option value="asc">Ascending</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Event Settings -->
                                <div class="mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="col_event_settings">
                                        <label class="form-check-label small" for="col_event_settings">
                                            Show Event Settings Header
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Columns Section -->
                    <div class="settings-section mt-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div class="settings-section-title mb-0">
                                <i class="fas fa-columns me-2"></i>Columns
                            </div>
                            <div class="btn-group btn-group-sm" role="group">
                                <button class="btn btn-outline-secondary btn-preset" onclick="applyPreset('minimal')">Minimal</button>
                                <button class="btn btn-outline-secondary btn-preset" onclick="applyPreset('standard')">Standard</button>
                                <button class="btn btn-outline-secondary btn-preset" onclick="applyPreset('detailed')">Detailed</button>
                                <button class="btn btn-outline-secondary btn-preset" onclick="applyPreset('complete')">Complete</button>
                            </div>
                        </div>
                        
                        <!-- Basic Columns -->
                        <div class="mb-3">
                            <label class="form-label small fw-semibold text-muted">Basic Information</label>
                            <div class="checkbox-grid">
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_rank" checked>
                                    <label for="col_rank">Rank</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_bib" checked>
                                    <label for="col_bib">BIB Number</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_participant" checked>
                                    <label for="col_participant">Participant</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_category" checked>
                                    <label for="col_category">Category</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_club" checked>
                                    <label for="col_club">Club</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_gender">
                                    <label for="col_gender">Gender</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_country">
                                    <label for="col_country">Country</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_fis_code">
                                    <label for="col_fis_code">FIS Code</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_licence_code">
                                    <label for="col_licence_code">Licence Code</label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Scoring Columns -->
                        <div>
                            <label class="form-label small fw-semibold text-muted">Scoring Data</label>
                            <div class="checkbox-grid">
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_runs" checked>
                                    <label for="col_runs">Run Scores</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_judges">
                                    <label for="col_judges">Judge Breakdown</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_control_points">
                                    <label for="col_control_points">Control Points</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_figures">
                                    <label for="col_figures">Figures</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_heat_best" checked>
                                    <label for="col_heat_best">Heat Best</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_heat_average">
                                    <label for="col_heat_average">Heat Average</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_overall_best" checked>
                                    <label for="col_overall_best">Overall Best</label>
                                </div>
                                <div class="checkbox-item">
                                    <input type="checkbox" id="col_overall_average" checked>
                                    <label for="col_overall_average">Overall Average</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Preview Container -->
                <div id="previewContainer" class="preview-container loading">
                    <div>
                        <i class="fas fa-eye-slash fa-3x mb-3"></i>
                        <p>Click "Preview" to generate summary table</p>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="alert alert-info mt-4">
            <i class="fas fa-info-circle me-2"></i>
            Please select an event to begin creating summary tables.
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Save Configuration Modal -->
    <div class="modal fade" id="saveConfigModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-save me-2"></i>Save Configuration
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Configuration Name</label>
                        <input type="text" id="configName" class="form-control" placeholder="e.g. Event 3 - Heat 1 - Senior">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select id="configStatus" class="form-select">
                            <option value="active">Active</option>
                            <option value="draft">Draft</option>
                            <option value="public">Public</option>
                            <option value="private">Private</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Display Order</label>
                        <input type="number" id="configOrder" class="form-control" value="0" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="performSaveConfiguration()">
                        <i class="fas fa-save me-1"></i>Save
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const eventId = <?= $selected_event ? (int)$selected_event : 'null' ?>;
        let currentConfigId = <?= $selected_config_id ? (int)$selected_config_id : 'null' ?>;
        
        // Handle event change
        function handleEventChange() {
            const selectedEvent = document.getElementById('eventSelector').value;
            if (selectedEvent) {
                window.location.href = `?event_id=${selectedEvent}`;
            }
        }
        
        // Toggle checkbox helper
        function toggleCheckbox(id) {
            const checkbox = document.getElementById(id);
            if (checkbox && !checkbox.disabled) {
                checkbox.checked = !checkbox.checked;
                checkbox.dispatchEvent(new Event('change'));
            }
        }
        
        // Heat selection handlers
        function handleHeatAllChange() {
            const allChecked = document.getElementById('heat_all').checked;
            console.log('All Heats checkbox changed to:', allChecked);
            
            document.querySelectorAll('.heat-option').forEach(checkbox => {
                checkbox.checked = false;
                checkbox.disabled = allChecked;
            });
            
            console.log('Individual heats disabled:', allChecked);
        }
        
        function handleHeatChange() {
            const anyChecked = Array.from(document.querySelectorAll('.heat-option')).some(cb => cb.checked);
            console.log('Individual heat changed, any checked:', anyChecked);
            
            if (anyChecked) {
                document.getElementById('heat_all').checked = false;
                console.log('Unchecked "All Heats"');
            } else {
                document.getElementById('heat_all').checked = true;
                console.log('Checked "All Heats" (no individual heats selected)');
            }
        }
        
        // Get selected heats
        function getSelectedHeats() {
            if (document.getElementById('heat_all').checked) {
                console.log('Returning all heats (empty array)');
                return [];
            }
            const selected = Array.from(document.querySelectorAll('.heat-option:checked')).map(cb => cb.value);
            console.log('Selected heats:', selected);
            return selected;
        }
        
        // Collect current configuration
        function collectConfiguration() {
            const selectedHeats = getSelectedHeats();
            
            return {
                event_id: eventId,
                heat_numbers: selectedHeats,
                category: document.getElementById('categoryFilter').value,
                gender: document.getElementById('genderFilter').value,
                heat_direction: document.getElementById('heatDirection').value,
                sort_by: document.getElementById('sortBy').value,
                sort_direction: document.getElementById('sortDirection').value,
                show_event_settings: document.getElementById('col_event_settings').checked,
                show_rank: document.getElementById('col_rank').checked,
                show_bib: document.getElementById('col_bib').checked,
                show_participant: document.getElementById('col_participant').checked,
                show_category: document.getElementById('col_category').checked,
                show_club: document.getElementById('col_club').checked,
                show_gender: document.getElementById('col_gender').checked,
                show_country: document.getElementById('col_country').checked,
                show_fis_code: document.getElementById('col_fis_code').checked,
                show_licence_code: document.getElementById('col_licence_code').checked,
                show_runs: document.getElementById('col_runs').checked,
                show_judges: document.getElementById('col_judges').checked,
                show_control_points: document.getElementById('col_control_points').checked,
                show_figures: document.getElementById('col_figures').checked,
                show_heat_best: document.getElementById('col_heat_best').checked,
                show_heat_average: document.getElementById('col_heat_average').checked,
                show_overall_best: document.getElementById('col_overall_best').checked,
                show_overall_average: document.getElementById('col_overall_average').checked
            };
        }
        
        // Generate preview
        function generatePreview() {
            if (!eventId) return;
            
            // IMMEDIATELY CLEAR PREVIOUS CONTENT - prevent flickering
            const previewContainer = document.getElementById('previewContainer');
            previewContainer.innerHTML = '';
            previewContainer.className = 'preview-container loading';
            previewContainer.innerHTML = '<div><i class="fas fa-spinner fa-spin fa-2x mb-3"></i><p>Generating preview...</p></div>';
            
            const config = collectConfiguration();
            
            console.log('Configuration:', config);
            console.log('Heat Direction:', config.heat_direction);
            
            const params = new URLSearchParams({
                event_id: eventId,
                heat_numbers: config.heat_numbers.join(','),
                category: config.category,
                gender: config.gender,
                heat_direction: config.heat_direction,
                sort: config.sort_by,
                sort_direction: config.sort_direction,
                show_event_settings: config.show_event_settings,
                show_rank: config.show_rank,
                show_bib: config.show_bib,
                show_participant: config.show_participant,
                show_category: config.show_category,
                show_club: config.show_club,
                show_gender: config.show_gender,
                show_country: config.show_country,
                show_fis_code: config.show_fis_code,
                show_licence_code: config.show_licence_code,
                show_runs: config.show_runs,
                show_judges: config.show_judges,
                show_control_points: config.show_control_points,
                show_figures: config.show_figures,
                show_heat_best: config.show_heat_best,
                show_heat_average: config.show_heat_average,
                show_overall_best: config.show_overall_best,
                show_overall_average: config.show_overall_average
            });
            
            fetch(`../api/summary_table_api.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Clear again before inserting new content
                        previewContainer.innerHTML = '';
                        
                        let html = '<style>' + (data.table_badge_colors || '') + '</style>';
                        html += '<table class="table table-striped table-hover">';
                        html += data.table_head || '';
                        html += data.table_body || '';
                        html += '</table>';
                        previewContainer.classList.remove('loading');
                        previewContainer.innerHTML = html;
                    } else {
                        previewContainer.classList.remove('loading');
                        previewContainer.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i>Error: ' + (data.message || 'Unknown error') + '</div>';
                    }
                })
                .catch(error => {
                    previewContainer.classList.remove('loading');
                    previewContainer.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i>Error: ' + error.message + '</div>';
                });
        }
        
        // Save configuration
        function saveCurrentConfiguration() {
            const modal = new bootstrap.Modal(document.getElementById('saveConfigModal'));
            
            // Generate suggested name
            const eventName = document.getElementById('eventSelector').options[document.getElementById('eventSelector').selectedIndex].text;
            const selectedHeats = getSelectedHeats();
            const heatText = selectedHeats.length > 0 ? ' - Heat ' + selectedHeats.join(',') : '';
            const category = document.getElementById('categoryFilter').value;
            const categoryText = category !== 'all' ? ' - ' + category : '';
            
            document.getElementById('configName').value = 'Summary - ' + eventName + heatText + categoryText;
            
            modal.show();
        }
        
        function performSaveConfiguration() {
            const name = document.getElementById('configName').value.trim();
            if (!name) {
                alert('Please enter a configuration name');
                return;
            }
            
            const config = collectConfiguration();
            const selectedHeats = getSelectedHeats();
            
            const data = {
                action: currentConfigId ? 'update' : 'save',
                id: currentConfigId,
                name: name,
                event_id: eventId,
                view_type: 'summary_table',
                heat_number: selectedHeats.length === 1 ? selectedHeats[0] : null,
                category: config.category,
                status: document.getElementById('configStatus').value,
                display_order: parseInt(document.getElementById('configOrder').value) || 0,
                configuration: config
            };
            
            fetch('../api/result_configurations_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    bootstrap.Modal.getInstance(document.getElementById('saveConfigModal')).hide();
                    alert('Configuration saved successfully!');
                    window.location.reload();
                } else {
                    alert('Error: ' + (result.message || 'Unknown error'));
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        }
        
        // Load configuration
        function loadConfiguration(configId) {
            window.location.href = `?event_id=${eventId}&config_id=${configId}`;
        }
        
        // Setup heat selection listeners (always needed)
        function setupHeatListeners() {
            const heatAllCheckbox = document.getElementById('heat_all');
            if (heatAllCheckbox) {
                heatAllCheckbox.addEventListener('change', handleHeatAllChange);
            }
            
            document.querySelectorAll('.heat-option').forEach(checkbox => {
                checkbox.addEventListener('change', handleHeatChange);
            });
        }
        
        // Apply saved configuration to UI
        <?php if ($active_config && $active_config['configuration']): ?>
        document.addEventListener('DOMContentLoaded', function() {
            setupHeatListeners();
            try {
                const config = <?= $active_config['configuration'] ?>;
                applyConfigToUI(config);
                // Generate preview after UI is fully updated
                setTimeout(function() {
                    console.log('=== Generating preview after config load ===');
                    generatePreview();
                }, 100);
            } catch(e) {
                console.error('Error loading configuration:', e);
            }
        });
        <?php else: ?>
        // Initialize default state
        document.addEventListener('DOMContentLoaded', function() {
            setupHeatListeners();
            // Set initial state
            handleHeatAllChange();
        });
        <?php endif; ?>
        
        function applyConfigToUI(config) {
            if (!config) return;
            
            console.log('Applying config:', config);
            console.log('Config type:', typeof config);
            
            // CLEAR PREVIEW CONTAINER FIRST - prevent flickering
            const previewContainer = document.getElementById('previewContainer');
            previewContainer.innerHTML = '';
            previewContainer.classList.remove('loading');
            previewContainer.classList.add('loading');
            previewContainer.innerHTML = '<div><i class="fas fa-spinner fa-spin fa-2x mb-3"></i><p>Loading configuration...</p></div>';
            
            // Parse if it's a string
            if (typeof config === 'string') {
                try {
                    config = JSON.parse(config);
                    console.log('Parsed config:', config);
                } catch(e) {
                    console.error('Failed to parse config:', e);
                    previewContainer.classList.remove('loading');
                    previewContainer.innerHTML = '<div class="alert alert-danger">Failed to parse configuration</div>';
                    return;
                }
            }
            
            // RESET ALL HEAT CHECKBOXES FIRST
            document.querySelectorAll('.heat-option').forEach(cb => {
                cb.checked = false;
                cb.disabled = false;
            });
            
            // RESET ALL SELECTS TO DEFAULT
            document.getElementById('categoryFilter').value = 'all';
            document.getElementById('genderFilter').value = 'all';
            document.getElementById('heatDirection').value = 'row';
            document.getElementById('sortBy').value = 'OverallAverage';
            document.getElementById('sortDirection').value = 'desc';
            
            // Apply heat selection
            if (Array.isArray(config.heat_numbers) && config.heat_numbers.length > 0) {
                document.getElementById('heat_all').checked = false;
                config.heat_numbers.forEach(heatNum => {
                    const checkbox = document.querySelector(`.heat-option[value="${heatNum}"]`);
                    if (checkbox) {
                        checkbox.checked = true;
                        console.log('Checked heat:', heatNum);
                    }
                });
                // Enable individual heats
                document.querySelectorAll('.heat-option').forEach(cb => cb.disabled = false);
            } else {
                document.getElementById('heat_all').checked = true;
                handleHeatAllChange();
            }
            
            // Apply filters
            if (config.category) {
                document.getElementById('categoryFilter').value = config.category;
                console.log('Set category:', config.category);
            }
            if (config.gender) {
                document.getElementById('genderFilter').value = config.gender;
                console.log('Set gender:', config.gender);
            }
            if (config.heat_direction) {
                const heatDirSelect = document.getElementById('heatDirection');
                heatDirSelect.value = config.heat_direction;
                console.log('Set heat_direction:', config.heat_direction, '- Actual value:', heatDirSelect.value);
            }
            if (config.sort_by) {
                document.getElementById('sortBy').value = config.sort_by;
                console.log('Set sort_by:', config.sort_by);
            }
            if (config.sort_direction) {
                document.getElementById('sortDirection').value = config.sort_direction;
                console.log('Set sort_direction:', config.sort_direction);
            }
            
            // Apply checkboxes
            const checkboxFields = [
                'show_event_settings', 'show_rank', 'show_bib', 'show_participant', 'show_category',
                'show_club', 'show_gender', 'show_country', 'show_fis_code', 'show_licence_code',
                'show_runs', 'show_judges', 'show_control_points', 'show_figures',
                'show_heat_best', 'show_heat_average', 'show_overall_best', 'show_overall_average'
            ];
            
            checkboxFields.forEach(field => {
                const elementId = field.replace('show_', 'col_');
                const element = document.getElementById(elementId) || document.getElementById(field);
                if (element && typeof config[field] === 'boolean') {
                    element.checked = config[field];
                    console.log('Set checkbox', field, '(#' + element.id + ') to', config[field], '- actual checked:', element.checked);
                } else if (element) {
                    console.warn('Skipped', field, '- not boolean, value:', config[field], typeof config[field]);
                } else {
                    console.error('Element not found for', field, '- tried', elementId, 'and', field);
                }
            });
            
            console.log('Config applied successfully');
        }
        
        // Delete configuration
        function deleteConfig(configId, configName) {
            if (!confirm(`Delete configuration "${configName}"?`)) return;
            
            fetch('../api/result_configurations_api.php?action=delete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: configId })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Configuration deleted');
                    window.location.reload();
                } else {
                    alert('Error: ' + (result.message || 'Unknown error'));
                }
            })
            .catch(error => alert('Error: ' + error.message));
        }
        
        // Duplicate configuration
        function duplicateConfig(configId) {
            fetch(`../api/result_configurations_api.php?action=get&id=${configId}`)
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        const config = result.data;
                        const newData = {
                            action: 'save',
                            name: config.name + ' (Copy)',
                            event_id: config.event_id,
                            view_type: config.view_type,
                            heat_number: config.heat_number,
                            category: config.category,
                            status: 'draft',
                            display_order: 0,
                            configuration: JSON.parse(config.configuration || '{}')
                        };
                        
                        return fetch('../api/result_configurations_api.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(newData)
                        });
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        alert('Configuration duplicated');
                        window.location.reload();
                    }
                })
                .catch(error => alert('Error: ' + error.message));
        }
        
        // Export formats
        function exportFormat(format) {
            if (!eventId) return;
            
            const config = collectConfiguration();
            const params = new URLSearchParams({
                event_id: eventId,
                heat_numbers: config.heat_numbers.join(','),
                category: config.category,
                gender: config.gender,
                format: format
            });
            
            if (format === 'csv') {
                window.location.href = `../api/summary_table_api.php?${params.toString()}`;
            } else {
                window.open(`../api/summary_table_api.php?${params.toString()}`, '_blank');
            }
        }
        
        // Presets
        function applyPreset(preset) {
            const allCheckboxes = document.querySelectorAll('.checkbox-item input[type="checkbox"]');
            
            allCheckboxes.forEach(cb => {
                switch(preset) {
                    case 'minimal':
                        cb.checked = ['col_rank', 'col_bib', 'col_participant'].includes(cb.id);
                        break;
                    case 'standard':
                        cb.checked = ['col_rank', 'col_bib', 'col_participant', 'col_category', 'col_club', 
                                     'col_runs', 'col_heat_best', 'col_overall_best'].includes(cb.id);
                        break;
                    case 'detailed':
                        cb.checked = !['col_judges', 'col_control_points', 'col_fis_code', 'col_licence_code'].includes(cb.id);
                        break;
                    case 'complete':
                        cb.checked = true;
                        break;
                }
            });
        }
        
        // Reset to defaults
        function resetToDefaults() {
            if (!confirm('Reset all settings to default values?')) return;
            
            document.getElementById('heat_all').checked = true;
            handleHeatAllChange();
            document.getElementById('categoryFilter').value = 'all';
            document.getElementById('genderFilter').value = 'all';
            document.getElementById('heatDirection').value = 'row';
            document.getElementById('sortBy').value = 'OverallAverage';
            document.getElementById('sortDirection').value = 'desc';
            document.getElementById('showEventSettings').checked = false;
            
            applyPreset('standard');
        }
        
        // Update bulk delete button visibility
        function updateBulkDeleteButton() {
            const checkboxes = document.querySelectorAll('.config-checkbox input[type="checkbox"]:checked');
            const bulkBtn = document.getElementById('bulkDeleteBtn');
            if (checkboxes.length > 0) {
                bulkBtn.style.display = 'inline-block';
                bulkBtn.innerHTML = `<i class="fas fa-trash"></i> Delete (${checkboxes.length})`;
            } else {
                bulkBtn.style.display = 'none';
            }
        }
        
        // Bulk delete selected configurations
        function bulkDeleteConfigs() {
            const checkboxes = document.querySelectorAll('.config-checkbox input[type="checkbox"]:checked');
            const ids = Array.from(checkboxes).map(cb => cb.value);
            
            if (ids.length === 0) return;
            
            if (!confirm(`Delete ${ids.length} configuration(s)?`)) return;
            
            // Delete each configuration
            let deletePromises = ids.map(id => {
                return fetch('../api/result_configurations_api.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'delete', id: id })
                }).then(response => response.json());
            });
            
            Promise.all(deletePromises)
                .then(results => {
                    const allSuccess = results.every(r => r.success);
                    if (allSuccess) {
                        window.location.href = `?event_id=${eventId}`;
                    } else {
                        alert('Some configurations could not be deleted');
                        window.location.reload();
                    }
                })
                .catch(error => {
                    alert('Error: ' + error.message);
                });
        }
        
        // Show new config dialog
        function showNewConfigDialog() {
            currentConfigId = null;
            document.getElementById('configStatus').value = 'active';
            document.getElementById('configOrder').value = '0';
            saveCurrentConfiguration();
        }
    </script>
</body>
</html>
