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

// Debug: Check if this page is even executing
if (!isset($_SESSION['builder_load_count'])) {
    $_SESSION['builder_load_count'] = 0;
}
$_SESSION['builder_load_count']++;

// Prevent infinite loops
if ($_SESSION['builder_load_count'] > 3) {
    die("ERROR: Page loaded " . $_SESSION['builder_load_count'] . " times. Infinite loop detected. <a href='?reset=1'>Reset</a>");
}

if (isset($_GET['reset'])) {
    $_SESSION['builder_load_count'] = 0;
    header("Location: event_results_builder.php");
    exit;
}

try {
    include_once '../includes/auth.php';
} catch (Exception $e) {
    die("Auth error: " . $e->getMessage());
}

try {
    include_once '../includes/db.php';
} catch (Exception $e) {
    die("DB error: " . $e->getMessage());
}

$selected_event = $_GET['event_id'] ?? null;
$view_type = $_GET['view_type'] ?? 'summary_table';

// Fetch events
$events = [];
try {
    if (!isset($pdo)) {
        die("PDO not initialized");
    }
    $events = $pdo->query("SELECT id, name FROM events ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Error fetching events: " . $e->getMessage());
}

// Fetch heats for selected event
$heats = [];
$categories = [];
if ($selected_event) {
    try {
        $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);
    } catch (Exception $e) {
        error_log("Error fetching heats: " . $e->getMessage());
    }
    
    // Get categories
    try {
        $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);
    } catch (Exception $e) {
        error_log("Error fetching categories: " . $e->getMessage());
    }
}

// Fetch saved configurations
$saved_configurations = [];
if ($selected_event) {
    try {
        $stmt = $pdo->prepare("
            SELECT id, name, view_type, heat_number, category, status, display_order, created_at, configuration_json
            FROM result_configurations 
            WHERE event_id = ? AND view_type = ?
            ORDER BY display_order ASC, name ASC
        ");
        $stmt->execute([$selected_event, $view_type]);
        $saved_configurations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Error fetching configurations: " . $e->getMessage());
    }
}

function builder_get_bool_param(string $key, bool $default): bool {
    if (!isset($_GET[$key])) {
        return $default;
    }

    $value = strtolower((string)$_GET[$key]);
    if ($value === '') {
        return $default;
    }

    if (in_array($value, ['1', 'true', 'yes', 'on'], true)) {
        return true;
    }

    if (in_array($value, ['0', 'false', 'no', 'off'], true)) {
        return false;
    }

    return $default;
}

$heat_param = $_GET['heat_numbers'] ?? $_GET['heat_number'] ?? null;
if ($heat_param === null && isset($_GET['heatNumber'])) {
    $heat_param = $_GET['heatNumber'];
}

$initial_heat_numbers = [];
if ($heat_param !== null) {
    if (is_array($heat_param)) {
        $initial_heat_numbers = array_values(array_filter(array_map('trim', $heat_param), 'strlen'));
    } else {
        $initial_heat_numbers = array_values(array_filter(array_map('trim', explode(',', (string)$heat_param)), 'strlen'));
    }
}

$initial_category = $_GET['category'] ?? $_GET['category_filter'] ?? $_GET['categoryFilter'] ?? 'all';
$initial_gender = $_GET['gender'] ?? $_GET['gender_filter'] ?? $_GET['genderFilter'] ?? $_GET['gender_filter_main'] ?? 'all';

$initial_heat_direction = $_GET['heat_direction'] ?? 'row';
if (!in_array($initial_heat_direction, ['row', 'column'], true)) {
    $initial_heat_direction = 'row';
}

$available_sort_fields = ['rank', 'bib_number', 'last_name', 'overall_best'];
$initial_sort_by = $_GET['sort'] ?? $_GET['sort_by'] ?? 'rank';
if (!in_array($initial_sort_by, $available_sort_fields, true)) {
    $initial_sort_by = 'rank';
}

$initial_sort_direction = strtolower($_GET['sort_direction'] ?? $_GET['sort_dir'] ?? 'asc');
if (!in_array($initial_sort_direction, ['asc', 'desc'], true)) {
    $initial_sort_direction = 'asc';
}

$origin = $_GET['origin'] ?? null;
$auto_preview = ($origin === 'classic_summary') || builder_get_bool_param('auto_preview', false);
if ($view_type !== 'summary_table') {
    $auto_preview = false;
}

$initial_settings = [
    'origin' => $origin,
    'view_type' => $view_type,
    'event_id' => $selected_event,
    'heat_numbers' => $initial_heat_numbers,
    'category' => $initial_category,
    'gender' => $initial_gender,
    'heat_direction' => $initial_heat_direction,
    'sort_by' => $initial_sort_by,
    'sort_direction' => $initial_sort_direction,
    'show_rank' => builder_get_bool_param('show_rank', true),
    'show_bib' => builder_get_bool_param('show_bib', true),
    'show_participant' => builder_get_bool_param('show_participant', true),
    'show_category' => builder_get_bool_param('show_category', true),
    'show_club' => builder_get_bool_param('show_club', true),
    'show_gender' => builder_get_bool_param('show_gender', false),
    'show_country' => builder_get_bool_param('show_country', false),
    'show_fis_code' => builder_get_bool_param('show_fis_code', false),
    'show_licence_code' => builder_get_bool_param('show_licence_code', false),
    'show_runs' => builder_get_bool_param('show_runs', true),
    'show_judges' => builder_get_bool_param('show_judges', false),
    'show_control_points' => builder_get_bool_param('show_control_points', false),
    'show_figures' => builder_get_bool_param('show_figures', false),
    'show_heat_average' => builder_get_bool_param('show_heat_average', true),
    'show_heat_best' => builder_get_bool_param('show_heat_best', true),
    'show_overall_average' => builder_get_bool_param('show_overall_average', true),
    'show_overall_best' => builder_get_bool_param('show_overall_best', true),
    'show_event_settings' => builder_get_bool_param('show_event_settings', false),
    'show_colors' => builder_get_bool_param('show_colors', true),
    'compact_mode' => builder_get_bool_param('compact_mode', false),
];

$initial_settings['auto_step'] = $selected_event ? ($auto_preview ? 3 : 2) : 1;
$initial_settings['auto_preview'] = $auto_preview;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Results Builder - <?= $view_type === 'summary_table' ? 'Summary Tables' : 'Start Lists' ?></title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <!-- Debug: PHP is working, events count: <?= count($events) ?>, heats count: <?= count($heats) ?> -->
    <style>
        .wizard-container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .wizard-steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .wizard-steps::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #dee2e6;
            z-index: 0;
        }
        
        .wizard-step {
            flex: 1;
            text-align: center;
            position: relative;
            z-index: 1;
        }
        
        .wizard-step-circle {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid #dee2e6;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 0.5rem;
            font-weight: bold;
            transition: all 0.3s;
        }
        
        .wizard-step.active .wizard-step-circle {
            background: #0d6efd;
            border-color: #0d6efd;
            color: white;
        }
        
        .wizard-step.completed .wizard-step-circle {
            background: #198754;
            border-color: #198754;
            color: white;
        }
        
        .wizard-step-label {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .wizard-step.active .wizard-step-label {
            color: #0d6efd;
            font-weight: 600;
        }
        
        .wizard-content {
            background: white;
            border-radius: 8px;
            padding: 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .config-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .config-card:hover {
            border-color: #0d6efd;
            box-shadow: 0 2px 8px rgba(13, 110, 253, 0.15);
        }
        
        .config-card.selected {
            border-color: #0d6efd;
            background: #e7f1ff;
        }
        
        .column-selector {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 0.5rem;
        }
        
        .column-option {
            display: flex;
            align-items: center;
            padding: 0.5rem;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            background: white;
            transition: all 0.2s;
        }
        
        .column-option:hover {
            background: #f8f9fa;
        }
        
        .column-option input[type="checkbox"] {
            margin-right: 0.5rem;
        }
        
        .preset-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .quick-action-bar {
            position: sticky;
            bottom: 0;
            background: white;
            border-top: 1px solid #dee2e6;
            padding: 1rem;
            margin: -2rem -2rem 0 -2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .step-content {
            display: none;
        }
        
        .step-content.active {
            display: block;
        }
        
        .saved-configs-sidebar {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .tab-content-section {
            display: none;
        }
        
        .tab-content-section.active {
            display: block;
        }
        
        .config-tabs {
            border-bottom: 2px solid #dee2e6;
            margin-bottom: 1.5rem;
        }
        
        .config-tab {
            display: inline-block;
            padding: 0.75rem 1.5rem;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.2s;
            color: #6c757d;
        }
        
        .config-tab:hover {
            color: #0d6efd;
        }
        
        .config-tab.active {
            color: #0d6efd;
            border-bottom-color: #0d6efd;
            font-weight: 600;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <!-- Simple Navigation (menu.php causes redirect loop) -->
    <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 wizard-container">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="mb-1">
                    <i class="fas fa-magic me-2"></i>Results Builder
                </h3>
                <p class="text-muted mb-0">Create and manage summary tables and start lists with ease</p>
            </div>
            <div>
                <a href="event_start_list.php?view_type=<?= $view_type ?><?= $selected_event ? '&event_id='.$selected_event : '' ?>" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>Classic View
                </a>
            </div>
        </div>
        
        <!-- Wizard Steps -->
        <div class="wizard-steps">
            <div class="wizard-step active" data-step="1">
                <div class="wizard-step-circle">1</div>
                <div class="wizard-step-label">Select Event</div>
            </div>
            <div class="wizard-step" data-step="2">
                <div class="wizard-step-circle">2</div>
                <div class="wizard-step-label">Configure</div>
            </div>
            <div class="wizard-step" data-step="3">
                <div class="wizard-step-circle">3</div>
                <div class="wizard-step-label">Preview & Save</div>
            </div>
        </div>
        
        <!-- Wizard Content -->
        <div class="wizard-content">
            <!-- Step 1: Select Event -->
            <div class="step-content active" id="step1">
                <div class="row">
                    <div class="col-md-8">
                        <h5 class="mb-3"><i class="fas fa-calendar-alt me-2"></i>Choose Your Event</h5>
                        
                        <div class="mb-3">
                            <label class="form-label">Document Type</label>
                            <div class="btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="viewType" id="viewTypeSummary" value="summary_table" <?= $view_type === 'summary_table' ? 'checked' : '' ?>>
                                <label class="btn btn-outline-primary" for="viewTypeSummary">
                                    <i class="fas fa-table me-2"></i>Summary Table
                                </label>
                                
                                <input type="radio" class="btn-check" name="viewType" id="viewTypeStart" value="start_list" <?= $view_type === 'start_list' ? 'checked' : '' ?>>
                                <label class="btn btn-outline-primary" for="viewTypeStart">
                                    <i class="fas fa-list-ol me-2"></i>Start List
                                </label>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="eventSelect" class="form-label">Select Event</label>
                            <select id="eventSelect" class="form-select form-select-lg">
                                <option value="">-- Choose an event --</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($event['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div id="eventInfo" class="alert alert-info d-none">
                            <h6><i class="fas fa-info-circle me-2"></i>Event Information</h6>
                            <div id="eventInfoContent"></div>
                        </div>
                    </div>
                    
                    <!-- Saved Configurations Sidebar -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0"><i class="fas fa-history me-2"></i>Saved Configurations</h6>
                            </div>
                            <div class="card-body p-0">
                                <div class="saved-configs-sidebar" id="savedConfigsList">
                                    <?php if (empty($saved_configurations)): ?>
                                        <div class="p-3 text-center text-muted">
                                            <i class="fas fa-folder-open fa-2x mb-2"></i>
                                            <p class="mb-0">No saved configurations yet</p>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach ($saved_configurations as $config): ?>
                                            <div class="config-card" onclick="loadConfiguration(<?= $config['id'] ?>)">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div class="flex-grow-1">
                                                        <h6 class="mb-1"><?= htmlspecialchars($config['name']) ?></h6>
                                                        <div class="small text-muted">
                                                            <?php if ($config['category']): ?>
                                                                <span class="badge bg-light text-dark"><?= htmlspecialchars($config['category']) ?></span>
                                                            <?php endif; ?>
                                                            <?php if ($config['heat_number']): ?>
                                                                <span class="badge bg-warning text-dark">Heat <?= $config['heat_number'] ?></span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                    <span class="badge bg-<?= $config['status'] === 'active' ? 'success' : 'secondary' ?>">
                                                        <?= ucfirst($config['status']) ?>
                                                    </span>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Step 2: Configure -->
            <div class="step-content" id="step2">
                <h5 class="mb-3"><i class="fas fa-sliders-h me-2"></i>Configure Your Document</h5>
                
                <!-- Configuration Tabs -->
                <div class="config-tabs">
                    <span class="config-tab active" onclick="switchConfigTab('filters')">
                        <i class="fas fa-filter me-1"></i>Filters
                    </span>
                    <span class="config-tab" onclick="switchConfigTab('columns')">
                        <i class="fas fa-columns me-1"></i>Columns
                    </span>
                    <span class="config-tab" onclick="switchConfigTab('display')">
                        <i class="fas fa-eye me-1"></i>Display
                    </span>
                    <span class="config-tab" onclick="switchConfigTab('advanced')">
                        <i class="fas fa-cog me-1"></i>Advanced
                    </span>
                </div>
                
                <!-- Filters Tab -->
                <div class="tab-content-section active" id="tab-filters">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Heat Selection</label>
                            <select id="heatSelect" class="form-select" multiple size="6">
                                <option value="">All Heats</option>
                                <?php foreach ($heats as $heat): ?>
                                    <option value="<?= $heat['heat_number'] ?>">
                                        Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' - ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Hold Ctrl/Cmd for multiple</small>
                        </div>
                        
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Category Filter</label>
                            <select id="categorySelect" class="form-select">
                                <option value="all">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>">
                                        <?= htmlspecialchars($cat['category_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Gender Filter</label>
                            <select id="genderSelect" class="form-select">
                                <option value="all">All Genders</option>
                                <option value="M">Male</option>
                                <option value="F">Female</option>
                            </select>
                        </div>
                        
                        <div class="col-12" id="heatDirectionSection" style="display: none;">
                            <hr class="my-3">
                            <label class="form-label fw-semibold">Heat Direction</label>
                            <div class="btn-group" role="group">
                                <input type="radio" class="btn-check" name="heatDirection" id="heatDirectionRow" value="row" checked>
                                <label class="btn btn-outline-secondary" for="heatDirectionRow">
                                    <i class="fas fa-grip-horizontal me-1"></i>Row (Side by Side)
                                </label>
                                
                                <input type="radio" class="btn-check" name="heatDirection" id="heatDirectionColumn" value="column">
                                <label class="btn btn-outline-secondary" for="heatDirectionColumn">
                                    <i class="fas fa-grip-vertical me-1"></i>Column (Stacked)
                                </label>
                            </div>
                            <small class="text-muted d-block mt-2">Choose how multiple heats are displayed in the summary table</small>
                        </div>
                    </div>
                </div>
                
                <!-- Columns Tab -->
                <div class="tab-content-section" id="tab-columns">
                    <div class="preset-buttons">
                        <button class="btn btn-sm btn-outline-primary" onclick="selectPreset('minimal')">
                            <i class="fas fa-compress me-1"></i>Minimal
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="selectPreset('standard')">
                            <i class="fas fa-check me-1"></i>Standard
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="selectPreset('detailed')">
                            <i class="fas fa-expand me-1"></i>Detailed
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="selectPreset('complete')">
                            <i class="fas fa-th-large me-1"></i>Complete
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="selectPreset('none')">
                            <i class="fas fa-times me-1"></i>Clear All
                        </button>
                    </div>
                    
                    <div class="column-selector" id="columnSelector">
                        <!-- Basic Information -->
                        <div class="column-option">
                            <input type="checkbox" id="col_rank" checked>
                            <label for="col_rank" class="mb-0">Rank</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_bib" checked>
                            <label for="col_bib" class="mb-0">BIB Number</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_participant" checked>
                            <label for="col_participant" class="mb-0">Participant Name</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_category" checked>
                            <label for="col_category" class="mb-0">Category</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_club" checked>
                            <label for="col_club" class="mb-0">Club</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_gender">
                            <label for="col_gender" class="mb-0">Gender</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_country">
                            <label for="col_country" class="mb-0">Country</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_fis_code">
                            <label for="col_fis_code" class="mb-0">FIS Code</label>
                        </div>
                        <div class="column-option">
                            <input type="checkbox" id="col_licence_code">
                            <label for="col_licence_code" class="mb-0">Licence Code</label>
                        </div>
                        
                        <!-- Scoring Columns (Summary Table only) -->
                        <div id="scoringColumns" style="display: none; grid-column: 1 / -1;">
                            <hr class="my-3">
                            <h6 class="mb-2"><i class="fas fa-chart-line me-2"></i>Scoring Data</h6>
                            <div class="column-selector">
                                <div class="column-option">
                                    <input type="checkbox" id="col_runs" checked>
                                    <label for="col_runs" class="mb-0">Run Scores</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_judges">
                                    <label for="col_judges" class="mb-0">Judge Breakdown</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_control_points">
                                    <label for="col_control_points" class="mb-0">Control Points</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_figures">
                                    <label for="col_figures" class="mb-0">Figures</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_heat_average" checked>
                                    <label for="col_heat_average" class="mb-0">Heat Average</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_heat_best" checked>
                                    <label for="col_heat_best" class="mb-0">Heat Best</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_overall_average" checked>
                                    <label for="col_overall_average" class="mb-0">Overall Average</label>
                                </div>
                                <div class="column-option">
                                    <input type="checkbox" id="col_overall_best" checked>
                                    <label for="col_overall_best" class="mb-0">Overall Best</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Display Tab -->
                <div class="tab-content-section" id="tab-display">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Sort By</label>
                            <select id="sortBySelect" class="form-select">
                                <option value="rank">Rank</option>
                                <option value="bib_number">BIB Number</option>
                                <option value="last_name">Last Name</option>
                                <option value="overall_best">Overall Best Score</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Sort Direction</label>
                            <select id="sortDirectionSelect" class="form-select">
                                <option value="asc">Ascending</option>
                                <option value="desc">Descending</option>
                            </select>
                        </div>
                        
                        <div class="col-12" id="eventSettingsSection">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showEventSettings">
                                <label class="form-check-label" for="showEventSettings">
                                    <strong>Show Event Settings Header</strong>
                                    <small class="text-muted d-block">Display scoring format, judge info, and event configuration</small>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Advanced Tab -->
                <div class="tab-content-section" id="tab-advanced">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Advanced Settings</strong> - These options are for fine-tuning your document output
                    </div>
                    
                    <div class="row g-3">
                        <div class="col-12">
                            <h6><i class="fas fa-palette me-2"></i>Styling Options</h6>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showColors" checked>
                                <label class="form-check-label" for="showColors">
                                    Use Color Coding
                                </label>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="compactMode">
                                <label class="form-check-label" for="compactMode">
                                    Compact Mode (Smaller fonts)
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Step 3: Preview & Save -->
            <div class="step-content" id="step3">
                <h5 class="mb-3"><i class="fas fa-eye me-2"></i>Preview & Export</h5>
                
                <div class="row mb-3">
                    <div class="col-md-8">
                        <button class="btn btn-primary" onclick="generatePreview()">
                            <i class="fas fa-sync me-1"></i>Refresh Preview
                        </button>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="btn-group">
                            <button class="btn btn-outline-danger" onclick="exportPDF()">
                                <i class="fas fa-file-pdf me-1"></i>PDF
                            </button>
                            <button class="btn btn-outline-success" onclick="exportCSV()">
                                <i class="fas fa-file-csv me-1"></i>CSV
                            </button>
                            <button class="btn btn-outline-info" onclick="exportJSON()">
                                <i class="fas fa-code me-1"></i>JSON
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="previewContainer" class="border rounded p-3 bg-light" style="min-height: 400px;">
                    <div class="text-center text-muted">
                        <i class="fas fa-eye-slash fa-3x mb-3"></i>
                        <p>Click "Refresh Preview" to see your document</p>
                    </div>
                </div>
            </div>
            
            <!-- Quick Action Bar -->
            <div class="quick-action-bar">
                <div>
                    <button class="btn btn-outline-secondary" id="btnPrevious" onclick="previousStep()" disabled>
                        <i class="fas fa-arrow-left me-1"></i>Previous
                    </button>
                </div>
                
                <div>
                    <span class="text-muted me-2">Step <span id="currentStepNumber">1</span> of 3</span>
                </div>
                
                <div>
                    <button class="btn btn-outline-primary me-2" id="btnSaveConfig" onclick="saveConfiguration()" style="display: none;">
                        <i class="fas fa-save me-1"></i>Save Configuration
                    </button>
                    <button class="btn btn-primary" id="btnNext" onclick="nextStep()">
                        Next <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const initialSettings = <?= json_encode($initial_settings, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
        let currentStep = 1;
        let selectedEventId = <?= $selected_event ? (int)$selected_event : 'null' ?>;

        if (!selectedEventId && initialSettings && initialSettings.event_id) {
            const parsedEventId = parseInt(initialSettings.event_id, 10);
            selectedEventId = Number.isNaN(parsedEventId) ? initialSettings.event_id : parsedEventId;
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            try {
                const eventSelect = document.getElementById('eventSelect');
                if (eventSelect && selectedEventId) {
                    eventSelect.value = String(selectedEventId);
                }

                applyInitialSettings(initialSettings);

                if (eventSelect) {
                    eventSelect.addEventListener('change', handleEventChange);
                    if (!selectedEventId && eventSelect.value) {
                        const parsed = parseInt(eventSelect.value, 10);
                        selectedEventId = Number.isNaN(parsed) ? eventSelect.value : parsed;
                    }
                }

                document.querySelectorAll('input[name="viewType"]').forEach(radio => {
                    radio.addEventListener('change', handleViewTypeChange);
                });

                handleViewTypeChange();

                const targetStep = selectedEventId ? ((initialSettings && initialSettings.auto_step) ? initialSettings.auto_step : 2) : 1;
                goToStep(targetStep);

                if (selectedEventId && initialSettings && initialSettings.auto_preview) {
                    generatePreview();
                }
            } catch (error) {
                console.error('Initialization error:', error);
            }
        });
        
        function handleEventChange() {
            const eventId = document.getElementById('eventSelect').value;
            if (eventId) {
                selectedEventId = eventId;
                const viewType = document.querySelector('input[name="viewType"]:checked').value;
                window.location.href = `?event_id=${eventId}&view_type=${viewType}`;
            }
        }
        
        function handleViewTypeChange() {
            const viewType = document.querySelector('input[name="viewType"]:checked')?.value;
            const scoringColumns = document.getElementById('scoringColumns');
            const heatDirectionSection = document.getElementById('heatDirectionSection');
            
            if (!scoringColumns || !heatDirectionSection) return; // Elements not loaded yet
            
            if (viewType === 'summary_table') {
                scoringColumns.style.display = 'block';
                heatDirectionSection.style.display = 'block';
            } else {
                scoringColumns.style.display = 'none';
                heatDirectionSection.style.display = 'none';
            }
        }
        
        function goToStep(step) {
            if (step < 1 || step > 3) return;
            
            // Validate step 1
            if (step > 1 && !selectedEventId) {
                alert('Please select an event first');
                return;
            }
            
            currentStep = step;
            updateStepDisplay();
        }
        
        function nextStep() {
            goToStep(currentStep + 1);
        }
        
        function previousStep() {
            goToStep(currentStep - 1);
        }
        
        function updateStepDisplay() {
            // Update step indicators
            document.querySelectorAll('.wizard-step').forEach((step, index) => {
                const stepNum = index + 1;
                step.classList.remove('active', 'completed');
                
                if (stepNum === currentStep) {
                    step.classList.add('active');
                } else if (stepNum < currentStep) {
                    step.classList.add('completed');
                }
            });
            
            // Update content
            document.querySelectorAll('.step-content').forEach((content, index) => {
                content.classList.toggle('active', index + 1 === currentStep);
            });
            
            // Update buttons
            document.getElementById('btnPrevious').disabled = currentStep === 1;
            document.getElementById('btnNext').style.display = currentStep === 3 ? 'none' : 'block';
            document.getElementById('btnSaveConfig').style.display = currentStep === 3 ? 'block' : 'none';
            document.getElementById('currentStepNumber').textContent = currentStep;
        }
        
        function switchConfigTab(tabName) {
            document.querySelectorAll('.config-tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content-section').forEach(section => section.classList.remove('active'));
            
            event.target.closest('.config-tab').classList.add('active');
            document.getElementById('tab-' + tabName).classList.add('active');
        }
        
        function selectPreset(preset) {
            const checkboxes = document.querySelectorAll('#columnSelector input[type="checkbox"]');
            
            checkboxes.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 = !cb.id.includes('judges') && !cb.id.includes('control_points');
                        break;
                    case 'complete':
                        cb.checked = true;
                        break;
                    case 'none':
                        cb.checked = false;
                        break;
                }
            });
        }

        function setCheckboxState(elementId, value) {
            if (typeof value !== 'boolean') {
                return;
            }
            const element = document.getElementById(elementId);
            if (element) {
                element.checked = value;
            }
        }

        function applyInitialSettings(settings) {
            if (!settings || typeof settings !== 'object') {
                return;
            }

            if (settings.view_type) {
                const viewRadio = document.querySelector(`input[name="viewType"][value="${settings.view_type}"]`);
                if (viewRadio) {
                    viewRadio.checked = true;
                }
            }

            if (settings.event_id && !selectedEventId) {
                const parsedId = parseInt(settings.event_id, 10);
                selectedEventId = Number.isNaN(parsedId) ? settings.event_id : parsedId;
            }

            const eventSelect = document.getElementById('eventSelect');
            if (eventSelect && settings.event_id) {
                eventSelect.value = String(settings.event_id);
            }

            const heatSelect = document.getElementById('heatSelect');
            if (heatSelect && Array.isArray(settings.heat_numbers) && settings.heat_numbers.length > 0) {
                const heatValues = settings.heat_numbers.map(value => String(value));
                Array.from(heatSelect.options).forEach(option => {
                    option.selected = heatValues.includes(option.value);
                });
            }

            const categorySelect = document.getElementById('categorySelect');
            if (categorySelect && settings.category !== undefined && settings.category !== null) {
                const desiredCategory = String(settings.category).trim();
                if (categorySelect.querySelector(`option[value="${desiredCategory}"]`)) {
                    categorySelect.value = desiredCategory;
                } else {
                    const matchOption = Array.from(categorySelect.options).find(option => option.text.trim().toLowerCase() === desiredCategory.toLowerCase());
                    if (matchOption) {
                        categorySelect.value = matchOption.value;
                    } else if (desiredCategory.toLowerCase() === 'all') {
                        categorySelect.value = 'all';
                    }
                }
            }

            const genderSelect = document.getElementById('genderSelect');
            if (genderSelect && settings.gender !== undefined && settings.gender !== null) {
                const rawGender = String(settings.gender).trim();
                let desiredGender = rawGender;
                if (rawGender.toLowerCase() === 'all') {
                    desiredGender = 'all';
                } else if (rawGender.length === 1) {
                    desiredGender = rawGender.toUpperCase();
                }

                if (genderSelect.querySelector(`option[value="${desiredGender}"]`)) {
                    genderSelect.value = desiredGender;
                } else if (desiredGender === 'all') {
                    genderSelect.value = 'all';
                }
            }

            if (settings.heat_direction) {
                const heatDirectionRadio = document.querySelector(`input[name="heatDirection"][value="${settings.heat_direction}"]`);
                if (heatDirectionRadio) {
                    heatDirectionRadio.checked = true;
                }
            }

            if (settings.sort_by) {
                const sortSelect = document.getElementById('sortBySelect');
                if (sortSelect && sortSelect.querySelector(`option[value="${settings.sort_by}"]`)) {
                    sortSelect.value = settings.sort_by;
                }
            }

            if (settings.sort_direction) {
                const sortDirectionSelect = document.getElementById('sortDirectionSelect');
                if (sortDirectionSelect && sortDirectionSelect.querySelector(`option[value="${settings.sort_direction}"]`)) {
                    sortDirectionSelect.value = settings.sort_direction;
                }
            }

            setCheckboxState('col_rank', settings.show_rank);
            setCheckboxState('col_bib', settings.show_bib);
            setCheckboxState('col_participant', settings.show_participant);
            setCheckboxState('col_category', settings.show_category);
            setCheckboxState('col_club', settings.show_club);
            setCheckboxState('col_gender', settings.show_gender);
            setCheckboxState('col_country', settings.show_country);
            setCheckboxState('col_fis_code', settings.show_fis_code);
            setCheckboxState('col_licence_code', settings.show_licence_code);
            setCheckboxState('col_runs', settings.show_runs);
            setCheckboxState('col_judges', settings.show_judges);
            setCheckboxState('col_control_points', settings.show_control_points);
            setCheckboxState('col_figures', settings.show_figures);
            setCheckboxState('col_heat_average', settings.show_heat_average);
            setCheckboxState('col_heat_best', settings.show_heat_best);
            setCheckboxState('col_overall_average', settings.show_overall_average);
            setCheckboxState('col_overall_best', settings.show_overall_best);
            setCheckboxState('showEventSettings', settings.show_event_settings);
            setCheckboxState('showColors', settings.show_colors);
            setCheckboxState('compactMode', settings.compact_mode);
        }
        
        function generatePreview() {
            const viewType = document.querySelector('input[name="viewType"]:checked').value;
            const heatSelect = document.getElementById('heatSelect');
            const selectedHeats = Array.from(heatSelect.selectedOptions).map(opt => opt.value).filter(v => v !== '');
            const category = document.getElementById('categorySelect').value;
            const gender = document.getElementById('genderSelect').value;
            const heatDirection = document.querySelector('input[name="heatDirection"]:checked')?.value || 'row';
            
            // Collect all settings
            const settings = {
                event_id: selectedEventId,
                view_type: viewType,
                heat_numbers: selectedHeats.join(','),
                category: category,
                gender: gender,
                heat_direction: heatDirection,
                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,
                sort_by: document.getElementById('sortBySelect').value,
                sort_direction: document.getElementById('sortDirectionSelect').value
            };
            
            // Add summary table specific settings
            if (viewType === 'summary_table') {
                settings.show_runs = document.getElementById('col_runs').checked;
                settings.show_judges = document.getElementById('col_judges').checked;
                settings.show_control_points = document.getElementById('col_control_points').checked;
                settings.show_figures = document.getElementById('col_figures').checked;
                settings.show_heat_average = document.getElementById('col_heat_average').checked;
                settings.show_heat_best = document.getElementById('col_heat_best').checked;
                settings.show_overall_average = document.getElementById('col_overall_average').checked;
                settings.show_overall_best = document.getElementById('col_overall_best').checked;
            }
            
            // Build API URL
            const apiUrl = viewType === 'summary_table' ? '../api/summary_table_api.php' : '../api/start_list_api.php';
            const params = new URLSearchParams(settings);
            
            // Fetch preview
            document.getElementById('previewContainer').innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading preview...</p></div>';
            
            fetch(`${apiUrl}?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        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>';
                        document.getElementById('previewContainer').innerHTML = html;
                    } else {
                        document.getElementById('previewContainer').innerHTML = '<div class="alert alert-danger">Error: ' + (data.message || 'Unknown error') + '</div>';
                    }
                })
                .catch(error => {
                    document.getElementById('previewContainer').innerHTML = '<div class="alert alert-danger">Error loading preview: ' + error.message + '</div>';
                });
        }
        
        function saveConfiguration() {
            const configName = prompt('Enter a name for this configuration:');
            if (!configName) return;
            
            // Collect all settings (same as generatePreview)
            const viewType = document.querySelector('input[name="viewType"]:checked').value;
            const heatSelect = document.getElementById('heatSelect');
            const selectedHeats = Array.from(heatSelect.selectedOptions).map(opt => opt.value).filter(v => v !== '');
            
            const configData = {
                action: 'save',
                name: configName,
                event_id: selectedEventId,
                view_type: viewType,
                heat_number: selectedHeats.length === 1 ? selectedHeats[0] : null,
                category: document.getElementById('categorySelect').value,
                status: 'active',
                display_order: 0,
                configuration: {
                    heat_numbers: selectedHeats,
                    gender: document.getElementById('genderSelect').value,
                    heat_direction: document.querySelector('input[name="heatDirection"]:checked')?.value || 'row',
                    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 || false,
                    show_judges: document.getElementById('col_judges')?.checked || false,
                    show_control_points: document.getElementById('col_control_points')?.checked || false,
                    show_figures: document.getElementById('col_figures')?.checked || false,
                    show_heat_average: document.getElementById('col_heat_average')?.checked || false,
                    show_heat_best: document.getElementById('col_heat_best')?.checked || false,
                    show_overall_average: document.getElementById('col_overall_average')?.checked || false,
                    show_overall_best: document.getElementById('col_overall_best')?.checked || false,
                    sort_by: document.getElementById('sortBySelect').value,
                    sort_direction: document.getElementById('sortDirectionSelect').value
                }
            };
            
            // Save to database via API
            fetch('../api/result_configurations_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(configData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Configuration saved successfully!');
                    window.location.reload();
                } else {
                    alert('Error saving configuration: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                alert('Error saving configuration: ' + error.message);
            });
        }
        
        function loadConfiguration(configId) {
            // Load configuration from database and populate fields
            alert('Loading configuration #' + configId + ' - Feature coming soon!');
        }
        
        function exportPDF() {
            const viewType = document.querySelector('input[name="viewType"]:checked').value;
            const apiUrl = viewType === 'summary_table' ? '../api/summary_table_api.php' : '../api/start_list_api.php';
            const params = new URLSearchParams({ event_id: selectedEventId, format: 'pdf' });
            window.open(`${apiUrl}?${params.toString()}`, '_blank');
        }
        
        function exportCSV() {
            const viewType = document.querySelector('input[name="viewType"]:checked').value;
            const apiUrl = viewType === 'summary_table' ? '../api/summary_table_api.php' : '../api/start_list_api.php';
            const params = new URLSearchParams({ event_id: selectedEventId, format: 'csv' });
            window.location.href = `${apiUrl}?${params.toString()}`;
        }
        
        function exportJSON() {
            const viewType = document.querySelector('input[name="viewType"]:checked').value;
            const apiUrl = viewType === 'summary_table' ? '../api/summary_table_api.php' : '../api/start_list_api.php';
            const params = new URLSearchParams({ event_id: selectedEventId, format: 'json' });
            window.open(`${apiUrl}?${params.toString()}`, '_blank');
        }
    </script>
</body>
</html>
