<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$message = '';

// Handle event selection
$selected_event_id = $_GET['event_id'] ?? '';
$heats_total = 0;
$heat_settings = [];
$event_categories = [];

// Handle saving settings (only for selected event)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['event_id']) && isset($_POST['save_settings'])) {
    $event_id = intval($_POST['event_id']);
    
    // First, deactivate all heats and runs for this event
    $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0 WHERE event_id = ?")->execute([$event_id]);
    
    if (isset($_POST['heat_name'])) {
        foreach ($_POST['heat_name'] as $heat_number => $name) {
            $heat_name = trim($name);
            $scoring_type = $_POST['scoring_type'][$heat_number] ?? 'Points';
            $runs_count = intval($_POST['runs_count'][$heat_number] ?? 1);
            $runs_scoring_method = $_POST['runs_scoring_method'][$heat_number] ?? 'best_from_all';
            $time_start = $_POST['time_start'][$heat_number] ?? null;
            $estimate_time_per_participant = intval($_POST['estimate_time_per_participant'][$heat_number] ?? 0);
            
            // Handle multiple categories
            $categories = isset($_POST['categories'][$heat_number]) ? $_POST['categories'][$heat_number] : [];
            $categories_json = json_encode($categories);
            
            // Handle format-related settings
            $format_name = $_POST['format_name'][$heat_number] ?? ($event_data['format_name'] ?? '');
            $discipline = $_POST['discipline'][$heat_number] ?? ($event_data['discipline'] ?? '');
            $difficulty_level = $_POST['difficulty_level'][$heat_number] ?? '';
            $course_length = intval($_POST['course_length'][$heat_number] ?? 0);
            $time_limit = intval($_POST['time_limit'][$heat_number] ?? 0);
            $weather_dependent = isset($_POST['weather_dependent'][$heat_number]) ? 1 : 0;
            $format_description = $_POST['format_description'][$heat_number] ?? '';
            $scoring_method = $_POST['scoring_method'][$heat_number] ?? 'standard';
            $required_figures = isset($_POST['required_figures'][$heat_number]) ? 
                                json_encode($_POST['required_figures'][$heat_number]) : '[]';
            $judges_required = intval($_POST['judges_required'][$heat_number] ?? 5);
            $scale_min = floatval($_POST['scale_min'][$heat_number] ?? ($event_data['scale_min'] ?? 0));
            $scale_max = floatval($_POST['scale_max'][$heat_number] ?? ($event_data['scale_max'] ?? 100));
            $precision_decimal = intval($_POST['precision_decimal'][$heat_number] ?? ($event_data['precision_decimal'] ?? 0));
            
            // Handle flow settings - only process if not disabled
            $flow_type = $_POST['flow_type'][$heat_number] ?? 'none';
            $flow_source_heat = null;
            $flow_participants_per_category = 0;
            
            if ($flow_type !== 'none') {
                $flow_source_heat = $_POST['flow_source_heat'][$heat_number] ?: null;
                $flow_participants_per_category = intval($_POST['flow_participants_per_category'][$heat_number] ?? 0);
                
                // Validate flow settings
                if ($flow_participants_per_category < 1) {
                    $flow_participants_per_category = 0;
                    $flow_type = 'none'; // Reset to none if invalid
                }
                
                if ($flow_type === 'promotion' && !$flow_source_heat) {
                    $flow_type = 'none'; // Reset to none if no source heat selected
                }
            }
            
            $is_active = isset($_POST['is_active']) && $_POST['is_active'] == $heat_number ? 1 : 0;
            $active_run = 0;
            
            // If heat is active, set the active run
            if ($is_active && isset($_POST['active_run'][$heat_number])) {
                $active_run = intval($_POST['active_run'][$heat_number]);
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO event_heat_settings (
                    event_id, heat_number, heat_name, scoring_type, runs_count, runs_scoring_method,
                    time_start, estimate_time_per_participant, categories, 
                    flow_type, flow_source_heat, flow_participants_per_category,
                    is_active, active_run,
                    format_name, discipline, difficulty_level, course_length, time_limit,
                    weather_dependent, format_description, scoring_method, required_figures,
                    judges_required, scale_min, scale_max, precision_decimal
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                    heat_name = VALUES(heat_name),
                    scoring_type = VALUES(scoring_type),
                    runs_count = VALUES(runs_count),
                    runs_scoring_method = VALUES(runs_scoring_method),
                    time_start = VALUES(time_start),
                    estimate_time_per_participant = VALUES(estimate_time_per_participant),
                    categories = VALUES(categories),
                    flow_type = VALUES(flow_type),
                    flow_source_heat = VALUES(flow_source_heat),
                    flow_participants_per_category = VALUES(flow_participants_per_category),
                    is_active = VALUES(is_active),
                    active_run = VALUES(active_run),
                    format_name = VALUES(format_name),
                    discipline = VALUES(discipline),
                    difficulty_level = VALUES(difficulty_level),
                    course_length = VALUES(course_length),
                    time_limit = VALUES(time_limit),
                    weather_dependent = VALUES(weather_dependent),
                    format_description = VALUES(format_description),
                    scoring_method = VALUES(scoring_method),
                    required_figures = VALUES(required_figures),
                    judges_required = VALUES(judges_required),
                    scale_min = VALUES(scale_min),
                    scale_max = VALUES(scale_max),
                    precision_decimal = VALUES(precision_decimal),
                    updated_at = CURRENT_TIMESTAMP
            ");
            
            $stmt->execute([
                $event_id, $heat_number, $heat_name, $scoring_type, $runs_count, $runs_scoring_method,
                $time_start, $estimate_time_per_participant, $categories_json,
                $flow_type, $flow_source_heat, $flow_participants_per_category,
                $is_active, $active_run,
                $format_name, $discipline, $difficulty_level, $course_length, $time_limit,
                $weather_dependent, $format_description, $scoring_method, $required_figures,
                $judges_required, $scale_min, $scale_max, $precision_decimal
            ]);
        }
        $message = '<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>Heat settings saved successfully!</div>';
    }
}

// Handle deactivate request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['deactivate_heat'])) {
    $event_id = intval($_POST['event_id']);
    $pdo->prepare("UPDATE event_heat_settings SET is_active = 0, active_run = 0 WHERE event_id = ?")->execute([$event_id]);
    $message = '<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>All heats have been deactivated.</div>';
}

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

// Load selected event settings
if ($selected_event_id) {
    $event = $pdo->prepare("
        SELECT e.*, sf.name as format_name, sf.sport as discipline, sf.mode as format_mode,
               sfj.scale_min, sfj.scale_max, sfj.scale_type, sfj.precision_decimal,
               GROUP_CONCAT(DISTINCT sfmc.config_value ORDER BY sfmc.config_key SEPARATOR ', ') as format_config
        FROM events e
        LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
        LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
        LEFT JOIN scoring_format_mode_config sfmc ON sf.format_id = sfmc.format_id
        WHERE e.id = ?
        GROUP BY e.id
    ");
    $event->execute([$selected_event_id]);
    $event_data = $event->fetch(PDO::FETCH_ASSOC);
    $heats_total = intval($event_data['heats_total']);

    // Load event categories (main categories only)
    $categories_stmt = $pdo->prepare("
        SELECT id, category_name 
        FROM event_categories 
        WHERE event_id = ? AND is_main_category = 1 
        ORDER BY category_name
    ");
    $categories_stmt->execute([$selected_event_id]);
    $event_categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get participant counts per heat
    $participant_counts_stmt = $pdo->prepare("
        SELECT heat_number, COUNT(*) as participant_count 
        FROM event_participants 
        WHERE event_id = ? 
        GROUP BY heat_number
    ");
    $participant_counts_stmt->execute([$selected_event_id]);
    $heat_participant_counts = [];
    foreach ($participant_counts_stmt->fetchAll(PDO::FETCH_ASSOC) as $count_row) {
        $heat_participant_counts[$count_row['heat_number']] = $count_row['participant_count'];
    }

    // Load heat settings with new fields
    $settings = $pdo->prepare("
        SELECT heat_number, heat_name, scoring_type, runs_count, runs_scoring_method,
               time_start, estimate_time_per_participant, categories, flow_type, flow_source_heat,
               flow_participants_per_category, is_active, active_run,
               format_name, discipline, difficulty_level, course_length, time_limit,
               weather_dependent, format_description, scoring_method, required_figures,
               judges_required, scale_min, scale_max, precision_decimal
        FROM event_heat_settings 
        WHERE event_id = ?
        ORDER BY heat_number
    ");
    $settings->execute([$selected_event_id]);
    foreach ($settings->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $row['categories'] = json_decode($row['categories'] ?: '[]', true);
        $row['required_figures'] = json_decode($row['required_figures'] ?: '[]', true);
        $row['participant_count'] = $heat_participant_counts[$row['heat_number']] ?? 0;
        $heat_settings[$row['heat_number']] = $row;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Configure Heats</title>
    <!-- style skin holder -->
    <?php include_once '../includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>
    
        
<div class="container-fluid container-StyleScore p-4">
        <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
	<div class="row justify-content-center">
            <div class="col-12">	
	
        <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-fire me-2 text-warning"></i>Heat Configuration</h2>
                <div class="btn-group">
                        <?php if ($selected_event_id): ?>
                                <a href="heats_configure.php?event_id=<?= $selected_event_id ?>" class="btn btn-outline-primary">
                                        <i class="fas fa-users me-1"></i>Manage Participants
                                </a>
                                <a href="heat_flow_preview.php?event_id=<?= $selected_event_id ?>" class="btn btn-outline-info">
                                        <i class="fas fa-sitemap me-1"></i>Preview Flow
                                </a>
                        <?php endif; ?>
                        <button type="button" class="btn btn-outline-secondary ms-2" data-bs-toggle="modal" data-bs-target="#helpModal">
                                <i class="fas fa-circle-question me-1"></i>Help
                        </button>
                </div>
        </div>

        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-circle-question me-2 text-info"></i>Configure Heats — Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/heats_configure_help.html" style="border:0;width:100%;height:100%;" title="Configure Heats Help"></iframe>
                    </div>
                </div>
            </div>
        </div>
    
    <?= $message ?>

    <!-- Event Selection -->
    <form method="get" class="card p-2 mb-3 shadow-sm load-event-selection">
        <div class="d-flex align-items-center gap-2">
            <label class="form-label mb-0 fw-semibold text-primary">
                <i class="fas fa-calendar-alt me-1"></i>Select Event
            </label>
            <select class="form-select form-select-sm flex-grow-1" name="event_id" id="event_id" onchange="this.form.submit()">
                <option value="">-- Select Event --</option>
                <?php foreach ($events as $ev): ?>
                    <option value="<?= $ev['id'] ?>" <?= $ev['id'] == $selected_event_id ? 'selected' : '' ?>>
                        <?= htmlspecialchars($ev['name']) ?> (<?= $ev['heats_total'] ?> heats)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>

    <!-- Heat Settings -->
    <?php if ($selected_event_id && $heats_total): ?>
        <!-- Event Summary -->
    <div class="border-0 shadow-none card card-body mb-3 py-2">
            <h6 class="mb-2 text-info"><i class="fas fa-info-circle me-1"></i>Event Summary</h6>
            <div class="row g-2 small">
                <div class="col-md-3">
                    <strong>Total Heats:</strong> <?= $heats_total ?>
                </div>
                <div class="col-md-3">
                    <strong>Main Categories:</strong> <?= count($event_categories) ?>
                </div>
                <div class="col-md-3">
                    <?php 
                    $active_heat = array_filter($heat_settings, function($h) { return $h['is_active']; });
                    if ($active_heat): 
                        $active = array_values($active_heat)[0];
                    ?>
                        <strong>Active Heat:</strong> 
                        <span class="badge bg-success small">
                            <i class="fas fa-fire me-1"></i>
                            Heat <?= $active['heat_number'] ?> - Run <?= $active['active_run'] ?>
                        </span>
                    <?php else: ?>
                        <strong>Status:</strong> 
                        <span class="badge bg-secondary small">No Active Heat</span>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <strong>Categories:</strong>
                    <?php if (empty($event_categories)): ?>
                        <a href="event_categories.php?event_id=<?= $selected_event_id ?>" class="btn btn-sm btn-warning py-0 px-2">
                            <i class="fas fa-plus me-1"></i>Add
                        </a>
                    <?php else: ?>
                        <span class="badge bg-success small"><?= count($event_categories) ?> Ready</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Deactivate Section -->
        <?php if ($active_heat): ?>
            <div class="alert alert-danger py-2 mb-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1 text-danger">
                            <i class="fas fa-power-off me-1"></i>
                            Deactivate Current Heat
                        </h6>
                        <small class="text-muted">
                            Stop all heat activity and set event to inactive state
                        </small>
                    </div>
                    <form method="post">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="deactivate_heat" value="1">
                        <button type="submit" class="btn btn-outline-danger btn-sm" 
                                onclick="return confirm('Are you sure you want to deactivate the current heat? This will stop all scoring activity.')">
                            <i class="fas fa-stop me-1"></i>Deactivate
                        </button>
                    </form>
                </div>
            </div>
        <?php endif; ?>

        <!-- Heat Flow Visualization -->
        <?php if (!empty($heat_settings) && $heats_total > 0): ?>
            <div class="border-0 shadow-none card card-body bg-body-tertiary mb-4">
                <h6><i class="fas fa-sitemap me-2 text-primary"></i>Heat Flow Chain</h6>
                
                <?php
                // Build flow chains based on actual connections
                $processed_heats = [];
                $flow_chains = [];
                
                for ($h = 1; $h <= $heats_total; $h++) {
                    if (in_array($h, $processed_heats)) continue;
                    
                    $current_chain = [];
                    $heat_to_process = $h;
                    
                    // Start a new chain with current heat
                    while ($heat_to_process && !in_array($heat_to_process, $processed_heats)) {
                        $setting = $heat_settings[$heat_to_process] ?? [];
                        
                        // Get category names for display
                        $heat_categories = $setting['categories'] ?? [];
                        $category_names = [];
                        if (empty($heat_categories)) {
                            $category_names = ['All Categories'];
                        } else {
                            foreach ($event_categories as $cat) {
                                if (in_array($cat['id'], $heat_categories)) {
                                    $category_names[] = $cat['category_name'];
                                }
                            }
                        }
                        
                        $current_chain[] = [
                            'heat_number' => $heat_to_process,
                            'heat_name' => $setting['heat_name'] ?? '',
                            'flow_type' => $setting['flow_type'] ?? 'none',
                            'flow_participants_per_category' => $setting['flow_participants_per_category'] ?? 0,
                            'flow_source_heat' => $setting['flow_source_heat'] ?? null,
                            'is_active' => $setting['is_active'] ?? false,
                            'categories' => $category_names,
                            'participant_count' => $heat_participant_counts[$heat_to_process] ?? 0,
                            'time_start' => $setting['time_start'] ?? '',
                            'estimate_time_per_participant' => $setting['estimate_time_per_participant'] ?? 0
                        ];
                        
                        $processed_heats[] = $heat_to_process;
                        
                        // Find next heat that flows from this one
                        $next_heat = null;
                        for ($next = $heat_to_process + 1; $next <= $heats_total; $next++) {
                            $next_setting = $heat_settings[$next] ?? [];
                            if (($next_setting['flow_source_heat'] ?? null) == $heat_to_process) {
                                $next_heat = $next;
                                break;
                            }
                        }
                        
                        $heat_to_process = $next_heat;
                    }
                    
                    if (!empty($current_chain)) {
                        $flow_chains[] = $current_chain;
                    }
                }
                ?>
                
                <?php foreach ($flow_chains as $chain_idx => $chain): ?>
                    <div class="mb-3 p-3 rounded shadow-sm bg-info-subtle">
                        <?php if ($chain_idx > 0): ?>
                            <div class="text-center position-relative mb-2">
                                <hr class="my-2">
                                <small class="text-muted bg-light px-2">
                                    <i class="fas fa-stream me-1"></i>Chain <?= $chain_idx + 1 ?>
                                </small>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Horizontal Chain Layout -->
                        <div class="d-flex align-items-center gap-2 overflow-auto" style="min-height: 120px;">
                            <?php foreach ($chain as $idx => $heat): ?>
                                <!-- Heat Node -->
                                <div class="border-0 shadow-none card border-0 shadow-sm p-2" style="min-width: 200px; max-width: 220px; position: relative;">
                                    <!-- Heat Header -->
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <div class="fw-bold small">
                                            <i class="fas fa-fire me-1"></i>
                                            Heat <?= $heat['heat_number'] ?>
                                            <?php if (!empty($heat['heat_name'])): ?>
                                                <div class="text-muted" style="font-size: 0.75rem;">
                                                    <?= htmlspecialchars($heat['heat_name']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($heat['is_active']): ?>
                                            <span class="badge bg-success-subtle text-success border border-success-subtle">Active</span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Compact Info -->
                                    <div class="mb-2 small text-center">
                                        <div class="badge text-bg-light">
                                            <i class="fas fa-users me-1"></i><?= $heat['participant_count'] ?> participants
                                        </div>
                                    </div>
                                    
                                    <!-- Time Display -->
                                    <?php if ($heat['time_start']): ?>
                                        <div class="mb-2">
                                            <div class="border-0 shadow-none card bg-light border-0 p-1">
                                                <div class="small text-center">
                                                    <i class="fas fa-clock me-1 text-primary"></i>
                                                    <strong>Start:</strong> <?= $heat['time_start'] ?>
                                                    <?php if ($heat['estimate_time_per_participant'] > 0 && $heat['participant_count'] > 0): ?>
                                                        <?php
                                                        $total_seconds = $heat['estimate_time_per_participant'] * $heat['participant_count'];
                                                        $total_minutes = ceil($total_seconds / 60);
                                                        $start_datetime = new DateTime($heat['time_start']);
                                                        $finish_datetime = clone $start_datetime;
                                                        $finish_datetime->add(new DateInterval('PT' . $total_minutes . 'M'));
                                                        ?>
                                                        <div class="text-muted">
                                                            <i class="fas fa-hourglass me-1"></i>
                                                            Duration: ~<?= $total_minutes ?>min
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <!-- Flow/Assignment Type -->
                                    <div class="text-center mb-2">
                                        <?php if ($heat['flow_type'] !== 'none'): ?>
                                            <?php if ($heat['flow_type'] === 'promotion'): ?>
                                                <span class="badge bg-warning-subtle text-warning border border-warning-subtle">
                                                    <i class="fas fa-arrow-up me-1"></i>Auto Promotion
                                                </span>
                                            <?php elseif ($heat['flow_type'] === 'qualifying'): ?>
                                                <span class="badge bg-info-subtle text-info border border-info-subtle">
                                                    <i class="fas fa-filter me-1"></i>Auto Qualifying
                                                </span>
                                            <?php endif; ?>
                                            <div class="small text-muted mt-1">
                                                From Heat <?= $heat['flow_source_heat'] ?> • Top <?= $heat['flow_participants_per_category'] ?>
                                            </div>
                                        <?php else: ?>
                                            <?php
                                            $has_incoming_flow = false;
                                            if (!empty($heat_settings)) {
                                                foreach ($heat_settings as $other_heat) {
                                                    if (($other_heat['flow_source_heat'] ?? null) == $heat['heat_number']) {
                                                        $has_incoming_flow = true;
                                                        break;
                                                    }
                                                }
                                            }
                                            ?>
                                            <?php if (!$has_incoming_flow): ?>
                                                <span class="badge bg-success-subtle text-success border border-success-subtle">
                                                    <i class="fas fa-play me-1"></i>Starting Heat
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-warning-subtle text-warning border border-warning-subtle">
                                                    <i class="fas fa-hand-paper me-1"></i>Manual Assignment
                                                </span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Categories -->
                                    <div class="text-center">
                                        
                                            
                                            <?php if (count($heat['categories']) <= 2): ?>
                                                <span class="badge text-bg-secondary small"><i class="fas fa-tags me-1"></i><?= implode('</span> <span class="badge text-bg-secondary small"><i class="fas fa-tags me-1"></i>', $heat['categories']) ?></span>
                                            <?php else: ?>
                                                <?= count($heat['categories']) ?> Categories
                                            <?php endif; ?>
                                        
                                    </div>
                                    
                                    <!-- Config Button -->
                                    <div class="position-absolute" style="top: 0.5rem; right: 0.5rem;">
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-secondary" 
                                                    onclick="openHeatModal(<?= $heat['heat_number'] ?>)"
                                                    title="Configure Heat">
                                                <i class="fas fa-cog"></i>
                                            </button>
                                            <a href="heat_management_modal.php?event_id=<?= $selected_event_id ?>&heat_id=<?= $heat['heat_number'] ?>&standalone=1" 
                                               class="btn btn-primary"
                                               target="_blank"
                                               title="Heat Management">
                                                <i class="fas fa-sliders-h"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Flow Arrow -->
                                <?php if ($idx < count($chain) - 1): ?>
                                    <?php 
                                    $next_heat = $chain[$idx + 1];
                                    $has_flow_connection = ($next_heat['flow_source_heat'] == $heat['heat_number']);
                                    ?>
                                    
                                    <div class="d-flex flex-column align-items-center justify-content-center px-2" style="min-width: 60px;">
                                        <?php if ($has_flow_connection): ?>
                                            <?php if ($next_heat['flow_type'] === 'promotion'): ?>
                                                <i class="fas fa-arrow-up text-warning fa-lg"></i>
                                                <small class="text-warning text-center mt-1" style="font-size: 0.7rem; line-height: 1;">Promotion</small>
                                            <?php elseif ($next_heat['flow_type'] === 'qualifying'): ?>
                                                <i class="fas fa-filter text-info fa-lg"></i>
                                                <small class="text-info text-center mt-1" style="font-size: 0.7rem; line-height: 1;">Qualifying</small>
                                            <?php else: ?>
                                                <i class="fas fa-arrow-right text-success fa-lg"></i>
                                                <small class="text-success text-center mt-1" style="font-size: 0.7rem; line-height: 1;">Flow</small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <i class="fas fa-ellipsis-h text-muted fa-lg"></i>
                                            <small class="text-muted text-center mt-1" style="font-size: 0.7rem; line-height: 1;">Next</small>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Chain Summary -->
                        <div class="mt-3">
                            <small class="text-muted">
                                <?php 
                                $chain_flow_heats = array_filter($chain, function($h) { return $h['flow_type'] !== 'none'; });
                                $chain_start_heats = array_filter($chain, function($h) use ($heat_settings) { 
                                    if ($h['flow_type'] !== 'none') return false;
                                    if (!empty($heat_settings)) {
                                        foreach ($heat_settings as $other_heat) {
                                            if (($other_heat['flow_source_heat'] ?? null) == $h['heat_number']) {
                                                return false;
                                            }
                                        }
                                    }
                                    return true;
                                });
                                $total_participants = array_sum(array_column($chain, 'participant_count'));
                                ?>
                                <i class="fas fa-info-circle me-1"></i>
                                <strong>Chain Summary:</strong> 
                                <?= count($chain) ?> heats • 
                                <?= count($chain_flow_heats) ?> auto-flow • 
                                <?= count($chain_start_heats) ?> starting • 
                                <?= $total_participants ?> total participants
                            </small>
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <!-- Flow Statistics -->
                <div class="mt-3 pt-3 border-top">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <i class="fas fa-fire text-warning me-2"></i>
                                <strong><?= $heats_total ?></strong> Total Heats
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <i class="fas fa-stream text-info me-2"></i>
                                <strong><?= count($flow_chains) ?></strong> Flow Chain<?= count($flow_chains) > 1 ? 's' : '' ?>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <?php 
                                $auto_flow_count = 0;
                                if (!empty($heat_settings)) {
                                    foreach ($heat_settings as $setting) {
                                        if (($setting['flow_type'] ?? 'none') !== 'none') {
                                            $auto_flow_count++;
                                        }
                                    }
                                }
                                ?>
                                <i class="fas fa-route text-success me-2"></i>
                                <strong><?= $auto_flow_count ?></strong> Auto Flow
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="summary-stat">
                                <?php 
                                $starting_count = 0;
                                if (!empty($heat_settings)) {
                                    foreach ($heat_settings as $h_num => $setting) {
                                        if (($setting['flow_type'] ?? 'none') === 'none') {
                                            // Check if any other heat flows from this one
                                            $has_outgoing = false;
                                            foreach ($heat_settings as $other_setting) {
                                                if (($other_setting['flow_source_heat'] ?? null) == $h_num) {
                                                    $has_outgoing = true;
                                                    break;
                                                }
                                            }
                                            if (!$has_outgoing) {
                                                $starting_count++;
                                            }
                                        }
                                    }
                                }
                                ?>
                                <i class="fas fa-play text-primary me-2"></i>
                                <strong><?= $starting_count ?></strong> Starting
                            </div>
                        </div>
                    </div>
                    
                    <!-- Flow Examples -->
                    <?php if (count($flow_chains) > 1): ?>
                        <div class="mt-3">
                            <h6 class="text-muted mb-2">
                                <i class="fas fa-sitemap me-1"></i>Flow Structure:
                            </h6>
                            <?php foreach ($flow_chains as $chain_idx => $chain): ?>
                                <div class="flow-example mb-1">
                                    <small class="text-info">
                                        <strong>Chain <?= $chain_idx + 1 ?>:</strong>
                                         <?php foreach ($chain as $idx => $heat): ?>
                                            <?= !empty($heat['heat_name']) ? $heat['heat_name'] : "Heat {$heat['heat_number']}" ?>
                                            <span class="text-muted">(<?= implode(', ', array_slice($heat['categories'], 0, 2)) ?><?= count($heat['categories']) > 2 ? '...' : '' ?>)</span>
                                            <?php if ($idx < count($chain) - 1): ?>
                                                <?php 
                                                $next_heat = $chain[$idx + 1];
                                                $has_flow = ($next_heat['flow_source_heat'] ?? null) == $heat['heat_number'];
                                                ?>
                                                <?= $has_flow ? ' → ' : ' | ' ?>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

    <!-- Configure Heats Section -->
    <div class="border-0 shadow-none card p-4 shadow-sm mb-4">
        <h5 class="mb-4">
            <i class="fas fa-cogs me-2 text-success"></i>
            Configure <?= $heats_total ?> Heat<?= $heats_total > 1 ? 's' : '' ?>
            <button type="button" class="btn btn-sm btn-outline-info ms-3" onclick="sortHeatsByFlow()">
                <i class="fas fa-sort me-1"></i>Sort by Flow Order
            </button>
        </h5>
        
        <?php 
        // Create an array to sort heats by flow order
        $heat_order = [];
        $processed_for_order = [];
        
        // First, add all starting heats (no incoming flow)
        for ($h = 1; $h <= $heats_total; $h++) {
            $setting = $heat_settings[$h] ?? [];
            $has_incoming = false;
            
            // Check if any other heat flows to this one
            foreach ($heat_settings as $other_setting) {
                if (($other_setting['flow_source_heat'] ?? null) == $h) {
                    $has_incoming = true;
                    break;
                }
            }
            
            // If no incoming flow and not a flow destination, it's a starting heat
            if (($setting['flow_type'] ?? 'none') === 'none' && !$has_incoming) {
                $heat_order[] = $h;
                $processed_for_order[] = $h;
            }
        }
        
        // Then add heats with flow connections in order
        $remaining_iterations = $heats_total;
        while (count($processed_for_order) < $heats_total && $remaining_iterations > 0) {
            for ($h = 1; $h <= $heats_total; $h++) {
                if (in_array($h, $processed_for_order)) continue;
                
                $setting = $heat_settings[$h] ?? [];
                $source_heat = $setting['flow_source_heat'] ?? null;
                
                // If this heat flows from a heat that's already processed, add it
                if ($source_heat && in_array($source_heat, $processed_for_order)) {
                    $heat_order[] = $h;
                    $processed_for_order[] = $h;
                }
            }
            $remaining_iterations--;
        }
        
        // Add any remaining heats that couldn't be sorted
        for ($h = 1; $h <= $heats_total; $h++) {
            if (!in_array($h, $processed_for_order)) {
                $heat_order[] = $h;
            }
        }
        ?>
        
        <div class="row" id="heat-buttons-container">
            <?php 
            // Debug output
            echo "<!-- Debug: Heat order count: " . count($heat_order) . " -->";
            echo "<!-- Debug: Heat settings count: " . count($heat_settings) . " -->";
            foreach ($heat_order as $h): 
                echo "<!-- Debug: Processing heat $h -->";
            ?>
                <?php 
                $setting = $heat_settings[$h] ?? [
                    'heat_name' => '', 
                    'scoring_type' => 'Points',
                    'runs_count' => 1,
                    'runs_scoring_method' => 'best_from_all',
                    'time_start' => '',
                    'estimate_time_per_participant' => 0,
                    'categories' => [],
                    'flow_type' => 'none',
                    'flow_source_heat' => null,
                    'flow_participants_per_category' => 0,
                    'is_active' => 0,
                    'active_run' => 1,
                    'format_name' => $event_data['format_name'] ?? '',
                    'discipline' => $event_data['discipline'] ?? '',
                    'difficulty_level' => '',
                    'course_length' => 0,
                    'time_limit' => 0,
                    'weather_dependent' => 0,
                    'format_description' => '',
                    'scoring_method' => 'standard',
                    'required_figures' => [],
                    'judges_required' => 5,
                    'scale_min' => $event_data['scale_min'] ?? 0,
                    'scale_max' => $event_data['scale_max'] ?? 100,
                    'precision_decimal' => $event_data['precision_decimal'] ?? 0
                ];
                ?>
                <!-- Debug: Heat <?= $h ?>, Setting active: <?= $setting['is_active'] ? 'true' : 'false' ?> -->
                <div class="col-md-4 col-lg-3 mb-3">
                    <div class="border-0 shadow-none card h-100 position-relative <?= $setting['is_active'] ? 'border-success bg-success-subtle' : '' ?>">
                        <?php if ($setting['is_active']): ?>
                            <span class="badge text-bg-success position-absolute top-0 end-0 m-2 z-3">
                                <i class="fas fa-fire me-1"></i>ACTIVE
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($setting['flow_type'] !== 'none'): ?>
                            <span class="badge text-bg-warning position-absolute top-0 start-0 m-2 z-3">
                                <i class="fas fa-arrow-up me-1"></i>FLOW
                            </span>
                        <?php endif; ?>
                        
                        <div class="border-0 shadow-none card-body text-center">
                            <h6 class="card-title">
                                <i class="fas fa-fire me-2 text-warning"></i>
                                Heat <?= $h ?>
                            </h6>
                            <p class="card-text text-muted small">
                                <?= !empty($setting['heat_name']) ? htmlspecialchars($setting['heat_name']) : 'Unnamed Heat' ?>
                            </p>
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-primary btn-sm" onclick="openHeatModal(<?= $h ?>)">
                                    <i class="fas fa-cog me-1"></i>Configure
                                </button>
                                <?php if (!$setting['is_active']): ?>
                                    <button type="button" class="btn btn-outline-success btn-sm" onclick="activateHeat(<?= $h ?>)">
                                        <i class="fas fa-play me-1"></i>Activate
                                    </button>
                                <?php else: ?>
                                    <small class="text-success fw-bold">
                                        <i class="fas fa-play-circle me-1"></i>Run <?= $setting['active_run'] ?>
                                    </small>
                                <?php endif; ?>
                            </div>
                            <small class="text-muted d-block mt-2">
                                <?= $heat_participant_counts[$h] ?? 0 ?> participants
                            </small>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="text-center mt-3">
            <small class="text-muted">
                <i class="fas fa-info-circle me-1"></i>
                Click "Configure" to set up each heat's settings and timing
            </small>
            <br>
            <button type="button" class="btn btn-sm btn-info mt-2" onclick="testModal()">
                <i class="fas fa-bug me-1"></i>Test Modal Function
            </button>
        </div>
    </div>

    <!-- Heat Configuration Modals -->
    <?php foreach ($heat_order as $h): ?>
        <?php 
        $setting = $heat_settings[$h] ?? [
            'heat_name' => '', 
            'scoring_type' => 'Points',
            'runs_count' => 1,
            'runs_scoring_method' => 'best_from_all',
            'time_start' => '',
            'estimate_time_per_participant' => 0,
            'categories' => [],
            'flow_type' => 'none',
            'flow_source_heat' => null,
            'flow_participants_per_category' => 0,
            'is_active' => 0,
            'active_run' => 1,
            'format_name' => $event_data['format_name'] ?? '',
            'discipline' => $event_data['discipline'] ?? '',
            'difficulty_level' => '',
            'course_length' => 0,
            'time_limit' => 0,
            'weather_dependent' => 0,
            'format_description' => '',
            'scoring_method' => 'standard',
            'required_figures' => [],
            'judges_required' => 5,
            'scale_min' => $event_data['scale_min'] ?? 0,
            'scale_max' => $event_data['scale_max'] ?? 100,
            'precision_decimal' => $event_data['precision_decimal'] ?? 0
        ];
        ?>
        
        <div class="modal fade" id="heatModal<?= $h ?>" tabindex="-1" aria-labelledby="heatModalLabel<?= $h ?>" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="heatModalLabel<?= $h ?>">
                            <i class="fas fa-fire me-2 text-warning"></i>
                            Configure Heat <?= $h ?>
                            <?php if ($setting['is_active']): ?>
                                <span class="badge text-bg-success ms-2">ACTIVE</span>
                            <?php endif; ?>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    
                    <form method="post" onsubmit="return validateHeatForm(<?= $h ?>)">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="save_settings" value="1">
                        <input type="hidden" name="single_heat" value="<?= $h ?>">
                        
                        <div class="modal-body">
                            <!-- Heat Activation Status -->
                            <?php if ($setting['is_active']): ?>
                                <div class="alert alert-success border-0 mb-4">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-fire text-success fs-4 me-3"></i>
                                        <div>
                                            <h6 class="mb-1">This Heat is Currently Active</h6>
                                            <small class="text-muted">All scoring activity is directed to this heat</small>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Tabbed Interface -->
                            <ul class="nav nav-tabs mb-4" id="heatConfigTabs<?= $h ?>" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="basic-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#basic-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-info-circle me-2"></i>Basic Settings
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="timing-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#timing-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-clock me-2"></i>Timing & Runs
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="format-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#format-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-clipboard-list me-2"></i>Format
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="flow-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#flow-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-sitemap me-2"></i>Flow
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="activation-tab-<?= $h ?>" data-bs-toggle="tab" 
                                            data-bs-target="#activation-<?= $h ?>" type="button" role="tab">
                                        <i class="fas fa-power-off me-2"></i>Activation
                                    </button>
                                </li>
                            </ul>
                            
                            <!-- Tab Content -->
                            <div class="tab-content" id="heatConfigTabContent<?= $h ?>">
                                
                                <!-- Basic Settings Tab -->
                                <div class="tab-pane fade show active" id="basic-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Heat Name</label>
                                                <input type="text" class="form-control" 
                                                       name="heat_name[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['heat_name'] ?? '') ?>"
                                                       placeholder="Enter descriptive heat name">
                                                <div class="form-text">Optional: Give this heat a descriptive name</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Type</label>
                                                <select class="form-select" name="scoring_type[<?= $h ?>]">
                                                    <option value="Points" <?= $setting['scoring_type'] == 'Points' ? 'selected' : '' ?>>Points Based</option>
                                                    <option value="Time" <?= $setting['scoring_type'] == 'Time' ? 'selected' : '' ?>>Time Based</option>
                                                </select>
                                                <div class="form-text">How this heat will be scored</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label class="form-label fw-semibold">Categories</label>
                                        <?php if (empty($event_categories)): ?>
                                            <div class="alert alert-warning">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                No categories defined for this event. 
                                                <a href="event_categories.php?event_id=<?= $selected_event_id ?>" class="alert-link">Add categories first</a>
                                            </div>
                                        <?php else: ?>
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header py-2">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" 
                                                               id="all_categories_modal_<?= $h ?>"
                                                               <?= empty($setting['categories']) ? 'checked' : '' ?>
                                                               onchange="toggleAllCategoriesModal(<?= $h ?>)">
                                                        <label class="form-check-label fw-semibold" for="all_categories_modal_<?= $h ?>">
                                                            All Categories
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="border-0 shadow-none card-body" style="max-height: 200px; overflow-y: auto;">
                                                    <div class="row">
                                                        <?php foreach ($event_categories as $category): ?>
                                                            <div class="col-md-6">
                                                                <div class="form-check">
                                                                    <input class="form-check-input category-checkbox" type="checkbox" 
                                                                           name="categories[<?= $h ?>][]" 
                                                                           value="<?= $category['id'] ?>"
                                                                           id="cat_modal_<?= $h ?>_<?= $category['id'] ?>"
                                                                           data-heat="<?= $h ?>"
                                                                           <?= in_array($category['id'], $setting['categories']) ? 'checked' : '' ?>
                                                                           <?= empty($setting['categories']) ? 'disabled' : '' ?>
                                                                           onchange="updateCategorySelectionModal(<?= $h ?>)">
                                                                    <label class="form-check-label" for="cat_modal_<?= $h ?>_<?= $category['id'] ?>">
                                                                        <?= htmlspecialchars($category['category_name']) ?>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Timing & Runs Tab -->
                                <div class="tab-pane fade" id="timing-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Start Time</label>
                                                <input type="time" class="form-control" 
                                                       name="time_start[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['time_start'] ?? '') ?>"
                                                       onchange="calculateEstimatedFinishModal(<?= $h ?>)">
                                                <div class="form-text">When this heat is scheduled to begin</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Time per Participant</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control" 
                                                           name="estimate_time_per_participant[<?= $h ?>]" 
                                                           value="<?= $setting['estimate_time_per_participant'] ?>"
                                                           min="0" step="5"
                                                           onchange="calculateEstimatedFinishModal(<?= $h ?>)">
                                                    <span class="input-group-text">seconds</span>
                                                </div>
                                                <div class="form-text">Estimated time allocation per participant</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Number of Runs</label>
                                                <select class="form-select" name="runs_count[<?= $h ?>]" 
                                                        onchange="updateRunOptionsModal(<?= $h ?>)">
                                                    <?php for ($r = 1; $r <= 5; $r++): ?>
                                                        <option value="<?= $r ?>" <?= $setting['runs_count'] == $r ? 'selected' : '' ?>>
                                                            <?= $r ?> Run<?= $r > 1 ? 's' : '' ?>
                                                        </option>
                                                    <?php endfor; ?>
                                                </select>
                                                <div class="form-text">How many runs each participant gets</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Method</label>
                                                <select class="form-select" name="runs_scoring_method[<?= $h ?>]" 
                                                        id="runs_scoring_modal_<?= $h ?>"
                                                        onchange="updateScoringExplanationModal(<?= $h ?>)">
                                                    <!-- Options populated by JavaScript -->
                                                </select>
                                                <div class="form-text">
                                                    <span id="scoring_explanation_modal_<?= $h ?>">How to calculate final score from multiple runs</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Estimated Finish -->
                                    <div id="estimated_finish_modal_<?= $h ?>" class="alert alert-light border d-none">
                                        <i class="fas fa-clock text-primary me-2"></i>
                                        <strong>Estimated Finish:</strong>
                                        <span id="finish_time_modal_<?= $h ?>"></span>
                                    </div>
                                </div>
                                
                                <!-- Format Settings Tab -->
                                <div class="tab-pane fade" id="format-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <h6 class="text-muted mb-3">Competition Format</h6>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Format Name</label>
                                                <input type="text" class="form-control" 
                                                       name="format_name[<?= $h ?>]" 
                                                       value="<?= htmlspecialchars($setting['format_name'] ?? '') ?>"
                                                       placeholder="e.g., Street Style, Park Competition">
                                                <div class="form-text">Override event format name for this heat</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Discipline</label>
                                                <select class="form-select" name="discipline[<?= $h ?>]">
                                                    <option value="">-- Use Event Default --</option>
                                                    <option value="freestyle_scooter" <?= $setting['discipline'] == 'freestyle_scooter' ? 'selected' : '' ?>>Freestyle Scooter</option>
                                                    <option value="street_scooter" <?= $setting['discipline'] == 'street_scooter' ? 'selected' : '' ?>>Street Scooter</option>
                                                    <option value="park_scooter" <?= $setting['discipline'] == 'park_scooter' ? 'selected' : '' ?>>Park Scooter</option>
                                                    <option value="freestyle_skiing" <?= $setting['discipline'] == 'freestyle_skiing' ? 'selected' : '' ?>>Freestyle Skiing</option>
                                                    <option value="alpine_skiing" <?= $setting['discipline'] == 'alpine_skiing' ? 'selected' : '' ?>>Alpine Skiing</option>
                                                    <option value="snowboard_freestyle" <?= $setting['discipline'] == 'snowboard_freestyle' ? 'selected' : '' ?>>Snowboard Freestyle</option>
                                                    <option value="skateboard_street" <?= $setting['discipline'] == 'skateboard_street' ? 'selected' : '' ?>>Skateboard Street</option>
                                                    <option value="skateboard_park" <?= $setting['discipline'] == 'skateboard_park' ? 'selected' : '' ?>>Skateboard Park</option>
                                                    <option value="bmx_freestyle" <?= $setting['discipline'] == 'bmx_freestyle' ? 'selected' : '' ?>>BMX Freestyle</option>
                                                    <option value="breaking" <?= $setting['discipline'] == 'breaking' ? 'selected' : '' ?>>Breaking</option>
                                                    <option value="parkour" <?= $setting['discipline'] == 'parkour' ? 'selected' : '' ?>>Parkour</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Difficulty Level</label>
                                                <select class="form-select" name="difficulty_level[<?= $h ?>]">
                                                    <option value="">-- No Specific Level --</option>
                                                    <option value="beginner" <?= $setting['difficulty_level'] == 'beginner' ? 'selected' : '' ?>>Beginner</option>
                                                    <option value="intermediate" <?= $setting['difficulty_level'] == 'intermediate' ? 'selected' : '' ?>>Intermediate</option>
                                                    <option value="advanced" <?= $setting['difficulty_level'] == 'advanced' ? 'selected' : '' ?>>Advanced</option>
                                                    <option value="professional" <?= $setting['difficulty_level'] == 'professional' ? 'selected' : '' ?>>Professional</option>
                                                    <option value="elite" <?= $setting['difficulty_level'] == 'elite' ? 'selected' : '' ?>>Elite</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Scoring Method</label>
                                                <select class="form-select" name="scoring_method[<?= $h ?>]">
                                                    <option value="standard" <?= $setting['scoring_method'] == 'standard' ? 'selected' : '' ?>>Standard Scoring</option>
                                                    <option value="comparative" <?= $setting['scoring_method'] == 'comparative' ? 'selected' : '' ?>>Comparative Scoring</option>
                                                    <option value="elimination" <?= $setting['scoring_method'] == 'elimination' ? 'selected' : '' ?>>Elimination</option>
                                                    <option value="head_to_head" <?= $setting['scoring_method'] == 'head_to_head' ? 'selected' : '' ?>>Head to Head</option>
                                                    <option value="battle" <?= $setting['scoring_method'] == 'battle' ? 'selected' : '' ?>>Battle Format</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="col-lg-6">
                                            <h6 class="text-muted mb-3">Course & Judging</h6>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Course Length</label>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control" 
                                                                   name="course_length[<?= $h ?>]" 
                                                                   value="<?= $setting['course_length'] ?>"
                                                                   min="0" step="1">
                                                            <span class="input-group-text">meters</span>
                                                        </div>
                                                        <div class="form-text">0 = not applicable</div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Time Limit</label>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control" 
                                                                   name="time_limit[<?= $h ?>]" 
                                                                   value="<?= $setting['time_limit'] ?>"
                                                                   min="0" step="1">
                                                            <span class="input-group-text">seconds</span>
                                                        </div>
                                                        <div class="form-text">0 = no limit</div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Required Figures</label>
                                                <textarea class="form-control" rows="3"
                                                          name="required_figures[<?= $h ?>]" 
                                                          placeholder="List required figures/maneuvers..."><?= htmlspecialchars(is_array($setting['required_figures']) ? implode("\n", $setting['required_figures']) : $setting['required_figures']) ?></textarea>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Judges Required</label>
                                                <input type="number" class="form-control" 
                                                       name="judges_required[<?= $h ?>]" 
                                                       value="<?= $setting['judges_required'] ?>"
                                                       min="1" max="15">
                                                <div class="form-text">Number of judges needed</div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Score Min</label>
                                                        <input type="number" class="form-control" 
                                                               name="scale_min[<?= $h ?>]" 
                                                               value="<?= $setting['scale_min'] ?>"
                                                               step="0.01">
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Score Max</label>
                                                        <input type="number" class="form-control" 
                                                               name="scale_max[<?= $h ?>]" 
                                                               value="<?= $setting['scale_max'] ?>"
                                                               step="0.01">
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Precision</label>
                                                        <select class="form-select" name="precision_decimal[<?= $h ?>]">
                                                            <option value="0" <?= $setting['precision_decimal'] == 0 ? 'selected' : '' ?>>Whole Numbers</option>
                                                            <option value="1" <?= $setting['precision_decimal'] == 1 ? 'selected' : '' ?>>1 Decimal</option>
                                                            <option value="2" <?= $setting['precision_decimal'] == 2 ? 'selected' : '' ?>>2 Decimals</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="mb-3">
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" 
                                                           name="weather_dependent[<?= $h ?>]" value="1"
                                                           id="weather_modal_<?= $h ?>"
                                                           <?= $setting['weather_dependent'] ? 'checked' : '' ?>>
                                                    <label class="form-check-label" for="weather_modal_<?= $h ?>">
                                                        <i class="fas fa-cloud-sun me-1"></i>Weather Dependent Competition
                                                    </label>
                                                </div>
                                                <div class="form-text">Check if this heat is affected by weather conditions</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label fw-semibold">Format Description</label>
                                                <textarea class="form-control" rows="3"
                                                          name="format_description[<?= $h ?>]" 
                                                          placeholder="Additional format-specific details, rules, or requirements for this heat"><?= htmlspecialchars($setting['format_description'] ?? '') ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Flow Control Tab -->
                                <div class="tab-pane fade" id="flow-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-sitemap me-2"></i>Flow Configuration
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Flow Type</label>
                                                        <select class="form-select" name="flow_type[<?= $h ?>]" 
                                                                onchange="toggleFlowConfigModal(<?= $h ?>)">
                                                            <option value="none" <?= $setting['flow_type'] == 'none' ? 'selected' : '' ?>>
                                                                No Flow (Manual Entry)
                                                            </option>
                                                            <option value="promotion" <?= $setting['flow_type'] == 'promotion' ? 'selected' : '' ?>>
                                                                Promotion from Previous Heat
                                                            </option>
                                                            <option value="qualifying" <?= $setting['flow_type'] == 'qualifying' ? 'selected' : '' ?>>
                                                                Qualifying Heat (Best from Categories)
                                                            </option>
                                                        </select>
                                                    </div>
                                                    
                                                    <div id="flow_config_modal_<?= $h ?>" class="<?= $setting['flow_type'] !== 'none' ? '' : 'd-none' ?>">
                                                        <?php if ($h > 1): ?>
                                                            <div class="mb-3">
                                                                <label class="form-label fw-semibold">Source Heat (for Promotion)</label>
                                                                <select class="form-select" name="flow_source_heat[<?= $h ?>]">
                                                                    <option value="">-- Select Source Heat --</option>
                                                                    <?php for ($source_h = 1; $source_h < $h; $source_h++): ?>
                                                                        <option value="<?= $source_h ?>" 
                                                                                data-heat-number="<?= $source_h ?>"
                                                                                <?= $setting['flow_source_heat'] == $source_h ? 'selected' : '' ?>>
                                                                            Heat <?= $source_h ?><?= !empty($heat_settings[$source_h]['heat_name']) ? ' (' . htmlspecialchars($heat_settings[$source_h]['heat_name']) . ')' : '' ?>
                                                                        </option>
                                                                    <?php endfor; ?>
                                                                </select>
                                                            </div>
                                                        <?php endif; ?>
                                                        
                                                        <div class="mb-3">
                                                            <label class="form-label fw-semibold">Participants to Promote per Category</label>
                                                            <input type="number" class="form-control" 
                                                                   name="flow_participants_per_category[<?= $h ?>]"
                                                                   value="<?= $setting['flow_participants_per_category'] ?>"
                                                                   min="1"
                                                                   data-heat="<?= $h ?>">
                                                            <div class="form-text">
                                                                Number of top participants from each category to advance to this heat
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="alert alert-info">
                                                            <i class="fas fa-info-circle me-2"></i>
                                                            Flow configuration will automatically populate participants based on results from the source heat.
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-info-circle me-2"></i>Flow Info
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="text-center">
                                                        <div class="mb-2">
                                                            <i class="fas fa-arrow-right fa-2x text-primary"></i>
                                                        </div>
                                                        <h6 class="text-primary">Automatic</h6>
                                                        <small class="text-muted">
                                                            Participants will be automatically populated based on your flow configuration
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Activation Tab -->
                                <div class="tab-pane fade" id="activation-<?= $h ?>" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <!-- Active Heat Selection -->
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-power-off me-2"></i>Heat Activation
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="form-check form-switch mb-3">
                                                        <input class="form-check-input" type="radio" name="is_active" 
                                                               value="<?= $h ?>" id="active_modal_<?= $h ?>"
                                                               <?= $setting['is_active'] ? 'checked' : '' ?>
                                                               onchange="toggleActiveHeatModal(<?= $h ?>)">
                                                        <label class="form-check-label fw-semibold" for="active_modal_<?= $h ?>">
                                                            Set as Active Heat
                                                        </label>
                                                    </div>
                                                    
                                                    <?php if ($setting['is_active']): ?>
                                                        <div class="alert alert-success">
                                                            <i class="fas fa-check-circle me-2"></i>
                                                            This heat is currently active and receiving all scoring activity
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="alert alert-light">
                                                            <i class="fas fa-info-circle me-2"></i>
                                                            This heat is inactive. Select to activate for scoring.
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <!-- Active Run Selection -->
                                            <div id="run_selector_modal_<?= $h ?>" class="card mt-3 <?= $setting['is_active'] ? '' : 'd-none' ?>">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-play me-2"></i>Active Run Selection
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="row">
                                                        <?php for ($r = 1; $r <= max(1, $setting['runs_count']); $r++): ?>
                                                            <div class="col-auto">
                                                                <div class="form-check">
                                                                    <input class="form-check-input" type="radio" 
                                                                           name="active_run[<?= $h ?>]" value="<?= $r ?>" 
                                                                           id="run_modal_<?= $h ?>_<?= $r ?>" 
                                                                           <?= $r === $setting['active_run'] ? 'checked' : '' ?>>
                                                                    <label class="form-check-label" for="run_modal_<?= $h ?>_<?= $r ?>">
                                                                        Run <?= $r ?>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        <?php endfor; ?>
                                                    </div>
                                                    <div class="form-text mt-2">
                                                        Select which run is currently active for scoring
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="border-0 shadow-none card">
                                                <div class="border-0 shadow-none card-header">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-chart-line me-2"></i>Heat Status
                                                    </h6>
                                                </div>
                                                <div class="border-0 shadow-none card-body">
                                                    <div class="text-center">
                                                        <?php if ($setting['is_active']): ?>
                                                            <div class="text-success mb-2">
                                                                <i class="fas fa-fire fa-2x"></i>
                                                            </div>
                                                            <h6 class="text-success">ACTIVE</h6>
                                                            <small class="text-muted">Receiving all scores</small>
                                                        <?php else: ?>
                                                            <div class="text-muted mb-2">
                                                                <i class="fas fa-pause fa-2x"></i>
                                                            </div>
                                                            <h6 class="text-muted">INACTIVE</h6>
                                                            <small class="text-muted">Not receiving scores</small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-1"></i>Cancel
                            </button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save me-1"></i>Save Heat Configuration
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <?php elseif ($selected_event_id): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            This event has no heats defined (heats_total = 0). 
            <a href="events.php" class="alert-link">Edit the event</a> to set the number of heats.
        </div>
    <?php endif; ?>
        </div>

</div></div>
        

</div>

<script>
// Modal functions
function testModal() {
    console.log('Test modal function called');
    alert('Test function works! Bootstrap available: ' + (typeof bootstrap !== 'undefined'));
    
    if (typeof bootstrap !== 'undefined') {
        // Try to open the first heat modal
        const firstModal = document.querySelector('[id^="heatModal"]');
        if (firstModal) {
            console.log('Found modal:', firstModal.id);
            try {
                const modal = new bootstrap.Modal(firstModal);
                modal.show();
                console.log('Modal opened successfully');
            } catch (error) {
                console.error('Error opening modal:', error);
                alert('Error: ' + error.message);
            }
        } else {
            alert('No modal found');
        }
    }
}

function openHeatModal(heatNumber) {
    console.log('Opening modal for heat:', heatNumber);
    
    // Wait a bit for Bootstrap to be fully loaded if needed
    setTimeout(() => {
        // Check if Bootstrap is available
        if (typeof bootstrap === 'undefined') {
            console.error('Bootstrap is not loaded!');
            alert('Bootstrap is not loaded. Please refresh the page.');
            return;
        }
        
        const modalElement = document.getElementById('heatModal' + heatNumber);
        if (!modalElement) {
            console.error('Modal element not found:', 'heatModal' + heatNumber);
            alert('Modal not found for heat ' + heatNumber);
            return;
        }
        
        try {
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
            
            // Initialize the modal content
            setTimeout(() => {
                updateRunOptionsModal(heatNumber);
                calculateEstimatedFinishModal(heatNumber);
                toggleFlowConfigModal(heatNumber);
                
                // Update button text in main card when modal opens
                updateHeatButtonDisplay(heatNumber);
            }, 100);
            
            console.log('Modal opened successfully for heat:', heatNumber);
        } catch (error) {
            console.error('Error opening modal:', error);
            alert('Error opening modal: ' + error.message);
        }
    }, 50);
}

function activateHeat(heatNumber) {
    // Check the radio button in the modal and submit
    const radio = document.getElementById('active_modal_' + heatNumber);
    if (radio) {
        radio.checked = true;
        toggleActiveHeatModal(heatNumber);
        
        // Auto-submit the form to activate the heat
        const form = radio.closest('form');
        if (form) {
            form.submit();
        }
    }
}

function updateHeatButtonDisplay(heatNumber) {
    // Update the button text and heat name display in the main cards when data changes
    const heatNameInput = document.querySelector(`input[name="heat_name[${heatNumber}]"]`);
    if (heatNameInput) {
        // Update card display based on modal input
        heatNameInput.addEventListener('input', function() {
            const cardText = document.querySelector(`#heat-buttons-container .card:nth-child(${heatNumber}) .card-text`);
            if (cardText) {
                cardText.textContent = this.value.trim() || 'Unnamed Heat';
            }
        });
    }
}

// Modal-specific functions (copies of existing functions with modal suffix)
function toggleActiveHeatModal(heatNumber) {
    // Show/hide run selector in modal
    const runSelector = document.getElementById(`run_selector_modal_${heatNumber}`);
    const isActive = document.getElementById(`active_modal_${heatNumber}`).checked;
    
    if (runSelector) {
        if (isActive) {
            runSelector.classList.remove('d-none');
        } else {
            runSelector.classList.add('d-none');
        }
    }
}

function toggleAllCategoriesModal(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_modal_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox`);
    
    if (allCheckbox.checked) {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.disabled = true;
        });
    } else {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.disabled = false;
        });
    }
}

function updateCategorySelectionModal(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_modal_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox:checked`);
    
    if (categoryCheckboxes.length > 0) {
        allCheckbox.checked = false;
    }
}

function toggleFlowConfigModal(heatNumber) {
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`).value;
    const flowConfig = document.getElementById(`flow_config_modal_${heatNumber}`);
    const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
    const sourceHeatSelect = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
    
    if (flowType !== 'none') {
        flowConfig.classList.remove('d-none');
        if (participantsInput) {
            participantsInput.removeAttribute('disabled');
            participantsInput.setAttribute('min', '1');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.removeAttribute('disabled');
        }
    } else {
        flowConfig.classList.add('d-none');
        if (participantsInput) {
            participantsInput.setAttribute('disabled', 'disabled');
            participantsInput.removeAttribute('min');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.setAttribute('disabled', 'disabled');
        }
    }
}

function calculateEstimatedFinishModal(heatNumber) {
    const startTime = document.querySelector(`input[name="time_start[${heatNumber}]"]`).value;
    const timePerParticipant = parseInt(document.querySelector(`input[name="estimate_time_per_participant[${heatNumber}]"]`).value) || 0;
    
    if (startTime && timePerParticipant > 0) {
        // Get actual participant count for this heat
        const participantCount = window.heatParticipantCounts ? window.heatParticipantCounts[heatNumber] || 0 : 0;
        
        if (participantCount > 0) {
            const totalSeconds = timePerParticipant * participantCount;
            const totalMinutes = Math.ceil(totalSeconds / 60);
            
            const [hours, minutes] = startTime.split(':').map(Number);
            const startDateTime = new Date();
            startDateTime.setHours(hours, minutes, 0, 0);
            
            const finishDateTime = new Date(startDateTime.getTime() + (totalMinutes * 60000));
            const finishTime = finishDateTime.toTimeString().slice(0, 5);
            
            const finishElement = document.getElementById(`finish_time_modal_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = `${finishTime} (${totalMinutes} minutes for ${participantCount} participants)`;
                document.getElementById(`estimated_finish_modal_${heatNumber}`).classList.remove('d-none');
            }
        } else {
            const finishElement = document.getElementById(`finish_time_modal_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = 'No participants assigned to this heat yet';
                document.getElementById(`estimated_finish_modal_${heatNumber}`).classList.remove('d-none');
            }
        }
    } else {
        const estimatedElement = document.getElementById(`estimated_finish_modal_${heatNumber}`);
        if (estimatedElement) {
            estimatedElement.classList.add('d-none');
        }
    }
}

function updateRunOptionsModal(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const scoringSelect = document.getElementById(`runs_scoring_modal_${heatNumber}`);
    
    if (!scoringSelect) return;
    
    // Store current selection to try to maintain it
    const currentValue = scoringSelect.value;
    
    // Clear existing options
    scoringSelect.innerHTML = '';
    
    // Generate scoring options based on runs count
    const scoringOptions = generateScoringOptions(runsCount);
    
    // Get the saved value from PHP for this heat
    const savedValue = 'best_from_all'; // Default fallback
    
    scoringOptions.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        
        // Set selected if it matches saved value or current value
        if (option.value === savedValue || option.value === currentValue) {
            optionElement.selected = true;
        }
        
        scoringSelect.appendChild(optionElement);
    });
    
    // If no option was selected and we have options, select the first one
    if (!scoringSelect.value && scoringOptions.length > 0) {
        scoringSelect.value = scoringOptions[0].value;
    }
    
    // Update explanation
    updateScoringExplanationModal(heatNumber);
    
    // Update run selector for active heat selection
    updateRunSelectorModal(heatNumber);
}

function updateScoringExplanationModal(heatNumber) {
    const scoringSelect = document.getElementById(`runs_scoring_modal_${heatNumber}`);
    const explanationSpan = document.getElementById(`scoring_explanation_modal_${heatNumber}`);
    
    if (!scoringSelect || !explanationSpan) return;
    
    const selectedValue = scoringSelect.value;
    
    const explanations = {
        'single_run': 'Score from the single run attempt',
        'best_from_2': 'Highest score from 2 runs',
        'average_from_2': 'Average score from both runs',
        'best_from_3': 'Highest score from 3 runs',
        'average_best_2_from_3': 'Average of the 2 highest scores from 3 runs',
        'average_from_3': 'Average score from all 3 runs',
        'best_from_4': 'Highest score from 4 runs',
        'average_best_2_from_4': 'Average of the 2 highest scores from 4 runs',
        'average_best_3_from_4': 'Average of the 3 highest scores from 4 runs',
        'average_from_4': 'Average score from all 4 runs',
        'best_from_5': 'Highest score from 5 runs',
        'average_best_2_from_5': 'Average of the 2 highest scores from 5 runs',
        'average_best_3_from_5': 'Average of the 3 highest scores from 5 runs',
        'average_best_4_from_5': 'Average of the 4 highest scores from 5 runs',
        'average_from_5': 'Average score from all 5 runs'
    };
    
    explanationSpan.textContent = explanations[selectedValue] || 'How to calculate final score from multiple runs';
}

function updateRunSelectorModal(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const runSelector = document.getElementById(`run_selector_modal_${heatNumber}`);
    
    if (!runSelector) return;
    
    // Rebuild run radio buttons
    const runOptions = Array.from({length: runsCount}, (_, i) => {
        const runNum = i + 1;
        return `
            <div class="col-auto">
                <div class="form-check">
                    <input class="form-check-input" type="radio" 
                           name="active_run[${heatNumber}]" value="${runNum}" 
                           id="run_modal_${heatNumber}_${runNum}" ${runNum === 1 ? 'checked' : ''}>
                    <label class="form-check-label" for="run_modal_${heatNumber}_${runNum}">
                        Run ${runNum}
                    </label>
                </div>
            </div>
        `;
    }).join('');
    
    const runsContainer = runSelector.querySelector('.row');
    if (runsContainer) {
        runsContainer.innerHTML = runOptions;
    }
}

function validateHeatForm(heatNumber) {
    let isValid = true;
    const errors = [];
    
    // Check flow configuration
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`);
    if (flowType) {
        const flowTypeValue = flowType.value;
        
        if (flowTypeValue !== 'none') {
            const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
            const participantsValue = participantsInput ? parseInt(participantsInput.value) || 0 : 0;
            
            if (participantsValue < 1) {
                errors.push(`Please specify number of participants to promote (minimum 1)`);
                isValid = false;
            }
            
            if (flowTypeValue === 'promotion') {
                const sourceHeat = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
                const sourceHeatValue = sourceHeat ? sourceHeat.value : '';
                if (!sourceHeatValue) {
                    errors.push(`Please select a source heat for promotion flow`);
                    isValid = false;
                }
            }
        }
    }
    
    if (!isValid) {
        alert('Please fix the following errors:\n\n' + errors.join('\n'));
        return false;
    }
    
    return true;
}

function generateScoringOptions(runsCount) {
    const options = [];
    
    if (runsCount === 1) {
        options.push({
            value: 'single_run',
            text: 'Single Run Score'
        });
    } else if (runsCount === 2) {
        options.push(
            {
                value: 'best_from_2',
                text: 'Best from 2 Runs'
            },
            {
                value: 'average_from_2',
                text: 'Average from 2 Runs'
            }
        );
    } else if (runsCount === 3) {
        options.push(
            {
                value: 'best_from_3',
                text: 'Best from 3 Runs'
            },
            {
                value: 'average_best_2_from_3',
                text: 'Average of Best 2 from 3 Runs'
            },
            {
                value: 'average_from_3',
                text: 'Average from 3 Runs'
            }
        );
    } else if (runsCount === 4) {
        options.push(
            {
                value: 'best_from_4',
                text: 'Best from 4 Runs'
            },
            {
                value: 'average_best_2_from_4',
                text: 'Average of Best 2 from 4 Runs'
            },
            {
                value: 'average_best_3_from_4',
                text: 'Average of Best 3 from 4 Runs'
            },
            {
                value: 'average_from_4',
                text: 'Average from 4 Runs'
            }
        );
    } else if (runsCount === 5) {
        options.push(
            {
                value: 'best_from_5',
                text: 'Best from 5 Runs'
            },
            {
                value: 'average_best_2_from_5',
                text: 'Average of Best 2 from 5 Runs'
            },
            {
                value: 'average_best_3_from_5',
                text: 'Average of Best 3 from 5 Runs'
            },
            {
                value: 'average_best_4_from_5',
                text: 'Average of Best 4 from 5 Runs'
            },
            {
                value: 'average_from_5',
                text: 'Average from 5 Runs'
            }
        );
    }
    
    return options;
}

function updateScoringExplanation(heatNumber) {
    const scoringSelect = document.getElementById(`runs_scoring_${heatNumber}`);
    const explanationSpan = document.getElementById(`scoring_explanation_${heatNumber}`);
    
    if (!scoringSelect || !explanationSpan) return;
    
    const selectedValue = scoringSelect.value;
    
    const explanations = {
        'single_run': 'Score from the single run attempt',
        'best_from_2': 'Highest score from 2 runs',
        'average_from_2': 'Average score from both runs',
        'best_from_3': 'Highest score from 3 runs',
        'average_best_2_from_3': 'Average of the 2 highest scores from 3 runs',
        'average_from_3': 'Average score from all 3 runs',
        'best_from_4': 'Highest score from 4 runs',
        'average_best_2_from_4': 'Average of the 2 highest scores from 4 runs',
        'average_best_3_from_4': 'Average of the 3 highest scores from 4 runs',
        'average_from_4': 'Average score from all 4 runs',
        'best_from_5': 'Highest score from 5 runs',
        'average_best_2_from_5': 'Average of the 2 highest scores from 5 runs',
        'average_best_3_from_5': 'Average of the 3 highest scores from 5 runs',
        'average_best_4_from_5': 'Average of the 4 highest scores from 5 runs',
        'average_from_5': 'Average score from all 5 runs'
    };
    
    explanationSpan.textContent = explanations[selectedValue] || 'How to calculate final score from multiple runs';
}

function updateRunSelector(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const runSelector = document.getElementById(`run_selector_${heatNumber}`);
    
    if (!runSelector) return;
    
    // Rebuild run radio buttons
    const runOptions = Array.from({length: runsCount}, (_, i) => {
        const runNum = i + 1;
        return `
            <div class="col-auto">
                <div class="form-check">
                    <input class="form-check-input" type="radio" 
                           name="active_run[${heatNumber}]" value="${runNum}" 
                           id="run_${heatNumber}_${runNum}" ${runNum === 1 ? 'checked' : ''}>
                    <label class="form-check-label" for="run_${heatNumber}_${runNum}">
                        Run ${runNum}
                    </label>
                </div>
            </div>
        `;
    }).join('');
    
    const runsContainer = runSelector.querySelector('.row');
    if (runsContainer) {
        runsContainer.innerHTML = runOptions;
    }
}

function updateRunOptions(heatNumber) {
    const runsCount = parseInt(document.querySelector(`select[name="runs_count[${heatNumber}]"]`).value);
    const scoringSelect = document.getElementById(`runs_scoring_${heatNumber}`);
    
    if (!scoringSelect) return;
    
    // Store current selection to try to maintain it
    const currentValue = scoringSelect.value;
    
    // Clear existing options
    scoringSelect.innerHTML = '';
    
    // Generate scoring options based on runs count
    const scoringOptions = generateScoringOptions(runsCount);
    
    // Get the saved value from PHP for this heat
    const savedValue = '<?= $setting['runs_scoring_method'] ?? 'best_from_all' ?>';
    
    scoringOptions.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        
        // Set selected if it matches saved value or current value
        if (option.value === savedValue || option.value === currentValue) {
            optionElement.selected = true;
        }
        
        scoringSelect.appendChild(optionElement);
    });
    
    // If no option was selected and we have options, select the first one
    if (!scoringSelect.value && scoringOptions.length > 0) {
        scoringSelect.value = scoringOptions[0].value;
    }
    
    // Update explanation
    updateScoringExplanation(heatNumber);
    
    // Update run selector for active heat selection
    updateRunSelector(heatNumber);
}

function attachScoringMethodListeners() {
    <?php foreach ($heat_order as $h): ?>
        const scoringSelect_<?= $h ?> = document.getElementById(`runs_scoring_<?= $h ?>`);
        if (scoringSelect_<?= $h ?>) {
            scoringSelect_<?= $h ?>.addEventListener('change', function() {
                updateScoringExplanation(<?= $h ?>);
            });
        }
    <?php endforeach; ?>
}

function toggleActiveHeat(heatNumber) {
    // Hide all run selectors
    document.querySelectorAll('.run-selector').forEach(selector => {
        selector.classList.add('d-none');
    });
    
    // Remove active styles from all heat cards
    document.querySelectorAll('.heat-card').forEach(card => {
        card.classList.remove('border-success', 'bg-success-subtle');
        card.classList.add('opacity-75');
    });
    
    // Show run selector for active heat
    const runSelector = document.getElementById(`run_selector_${heatNumber}`);
    if (runSelector) {
        runSelector.classList.remove('d-none');
    }
    
    // Add active class to selected heat card
    const activeCard = document.querySelector(`input[value="${heatNumber}"]`).closest('.heat-card');
    if (activeCard) {
        activeCard.classList.add('border-success', 'bg-success-subtle');
        activeCard.classList.remove('opacity-75');
    }
}

function toggleAllCategories(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox`);
    
    if (allCheckbox.checked) {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.disabled = true;
        });
    } else {
        categoryCheckboxes.forEach(checkbox => {
            checkbox.disabled = false;
        });
    }
}

function updateCategorySelection(heatNumber) {
    const allCheckbox = document.getElementById(`all_categories_${heatNumber}`);
    const categoryCheckboxes = document.querySelectorAll(`input[data-heat="${heatNumber}"].category-checkbox:checked`);
    
    if (categoryCheckboxes.length > 0) {
        allCheckbox.checked = false;
    }
}

function toggleFlowConfig(heatNumber) {
    const flowType = document.querySelector(`select[name="flow_type[${heatNumber}]"]`).value;
    const flowConfig = document.getElementById(`flow_config_${heatNumber}`);
    const participantsInput = document.querySelector(`input[name="flow_participants_per_category[${heatNumber}]"]`);
    const sourceHeatSelect = document.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
    
    if (flowType !== 'none') {
    flowConfig.classList.remove('d-none');
        if (participantsInput) {
            participantsInput.removeAttribute('disabled');
            participantsInput.setAttribute('min', '1');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.removeAttribute('disabled');
        }
    } else {
    flowConfig.classList.add('d-none');
        if (participantsInput) {
            participantsInput.setAttribute('disabled', 'disabled');
            participantsInput.removeAttribute('min');
        }
        if (sourceHeatSelect) {
            sourceHeatSelect.setAttribute('disabled', 'disabled');
        }
    }
}

function calculateEstimatedFinish(heatNumber) {
    const startTime = document.querySelector(`input[name="time_start[${heatNumber}]"]`).value;
    const timePerParticipant = parseInt(document.querySelector(`input[name="estimate_time_per_participant[${heatNumber}]"]`).value) || 0;
    
    if (startTime && timePerParticipant > 0) {
        // Get actual participant count for this heat
        const participantCount = window.heatParticipantCounts ? window.heatParticipantCounts[heatNumber] || 0 : 0;
        
        if (participantCount > 0) {
            const totalSeconds = timePerParticipant * participantCount;
            const totalMinutes = Math.ceil(totalSeconds / 60);
            
            const [hours, minutes] = startTime.split(':').map(Number);
            const startDateTime = new Date();
            startDateTime.setHours(hours, minutes, 0, 0);
            
            const finishDateTime = new Date(startDateTime.getTime() + (totalMinutes * 60000));
            const finishTime = finishDateTime.toTimeString().slice(0, 5);
            
            const finishElement = document.getElementById(`finish_time_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = `${finishTime} (${totalMinutes} minutes for ${participantCount} participants)`;
                document.getElementById(`estimated_finish_${heatNumber}`).classList.remove('d-none');
            }
        } else {
            const finishElement = document.getElementById(`finish_time_${heatNumber}`);
            if (finishElement) {
                finishElement.textContent = 'No participants assigned to this heat yet';
                document.getElementById(`estimated_finish_${heatNumber}`).classList.remove('d-none');
            }
        }
    } else {
        const estimatedElement = document.getElementById(`estimated_finish_${heatNumber}`);
        if (estimatedElement) {
            estimatedElement.classList.add('d-none');
        }
    }
}

function updateHeatNameDisplay(heatNumber) {
    const nameInput = document.querySelector(`input[name="heat_name[${heatNumber}]"]`);
    const nameDisplay = document.getElementById(`heat_name_display_${heatNumber}`);
    
    if (nameInput && nameDisplay) {
        const name = nameInput.value.trim();
        nameDisplay.textContent = name ? `(${name})` : '';
    }
}

function updateHeatNameReferences(changedHeatNumber) {
    const nameInput = document.querySelector(`input[name="heat_name[${changedHeatNumber}]"]`);
    const newName = nameInput ? nameInput.value.trim() : '';
    
    // Update all source heat dropdowns that reference this heat
    document.querySelectorAll(`option[data-heat-number="${changedHeatNumber}"]`).forEach(option => {
        const heatNumber = changedHeatNumber;
        const baseText = `Heat ${heatNumber}`;
        option.textContent = newName ? `${baseText} (${newName})` : baseText;
    });
    
    // Update the heat name display
    updateHeatNameDisplay(changedHeatNumber);
    
    // Update flow visualization if visible
    updateFlowDisplay();
}

function sortHeatsByFlow() {
    const container = document.getElementById('heats-container');
    if (!container) return;
    
    const heatCards = Array.from(container.querySelectorAll('.heat-card'));
    
    // Get current flow relationships
    const flowRelations = {};
    const heatNames = {};
    
    heatCards.forEach(card => {
        const heatNumber = parseInt(card.dataset.heat);
        const sourceSelect = card.querySelector(`select[name="flow_source_heat[${heatNumber}]"]`);
        const nameInput = card.querySelector(`input[name="heat_name[${heatNumber}]"]`);
        
        flowRelations[heatNumber] = sourceSelect ? parseInt(sourceSelect.value) || null : null;
        heatNames[heatNumber] = nameInput ? nameInput.value.trim() : '';
    });
    
    // Sort heats by flow order
    const sortedOrder = [];
    const processed = new Set();
    
    // First, add starting heats (no source)
    Object.keys(flowRelations).forEach(heat => {
        const heatNum = parseInt(heat);
        if (!flowRelations[heatNum]) {
            // Check if this is truly a starting heat (no other heat flows to it)
            const hasIncoming = Object.values(flowRelations).includes(heatNum);
            if (!hasIncoming) {
                sortedOrder.push(heatNum);
                processed.add(heatNum);
            }
        }
    });
    
    // Then add heats in flow order
    let iterations = 0;
    const maxIterations = Object.keys(flowRelations).length;
    
    while (processed.size < Object.keys(flowRelations).length && iterations < maxIterations) {
        Object.keys(flowRelations).forEach(heat => {
            const heatNum = parseInt(heat);
            const sourceHeat = flowRelations[heatNum];
            
            if (!processed.has(heatNum) && sourceHeat && processed.has(sourceHeat)) {
                sortedOrder.push(heatNum);
                processed.add(heatNum);
            }
        });
        iterations++;
    }
    
    // Add any remaining heats
    Object.keys(flowRelations).forEach(heat => {
        const heatNum = parseInt(heat);
        if (!processed.has(heatNum)) {
            sortedOrder.push(heatNum);
        }
    });
    
    // Reorder the DOM elements
    sortedOrder.forEach(heatNumber => {
        const card = container.querySelector(`[data-heat="${heatNumber}"]`);
        if (card) {
            container.appendChild(card);
        }
    });
    
    // Show a notification
    showNotification('Heat cards reordered by flow connections', 'success');
}

function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 mt-3 me-3 shadow w-auto`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'info-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}

function updateFlowDisplay() {
    // This would update the flow visualization section if it's visible
    console.log('Flow display updated');
}

function validateForm() {
    let isValid = true;
    const errors = [];
    
    // Check each heat's flow configuration
    <?php foreach ($heat_order as $h): ?>
        const flowType_<?= $h ?> = document.querySelector(`select[name="flow_type[<?= $h ?>]"]`);
        if (flowType_<?= $h ?>) {
            const flowTypeValue = flowType_<?= $h ?>.value;
            
            if (flowTypeValue !== 'none') {
                const participantsInput_<?= $h ?> = document.querySelector(`input[name="flow_participants_per_category[<?= $h ?>]"]`);
                const participantsValue_<?= $h ?> = participantsInput_<?= $h ?> ? parseInt(participantsInput_<?= $h ?>.value) || 0 : 0;
                
                if (participantsValue_<?= $h ?> < 1) {
                    errors.push(`Heat <?= $h ?>: Please specify number of participants to promote (minimum 1)`);
                    isValid = false;
                }
                
                <?php if ($h > 1): ?>
                    if (flowTypeValue === 'promotion') {
                        const sourceHeat_<?= $h ?> = document.querySelector(`select[name="flow_source_heat[<?= $h ?>]"]`);
                        const sourceHeatValue = sourceHeat_<?= $h ?> ? sourceHeat_<?= $h ?>.value : '';
                        if (!sourceHeatValue) {
                            errors.push(`Heat <?= $h ?>: Please select a source heat for promotion flow`);
                            isValid = false;
                        }
                    }
                <?php endif; ?>
            }
        }
    <?php endforeach; ?>
    
    if (!isValid) {
        alert('Please fix the following errors:\n\n' + errors.join('\n'));
        return false;
    }
    
    return true;
}

// Enhanced initialization
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded');
    console.log('Bootstrap available:', typeof bootstrap !== 'undefined');
    
    // Test function - add simple click listener
    document.querySelectorAll('[onclick*="openHeatModal"]').forEach(button => {
        console.log('Found button with openHeatModal:', button);
    });
    
    // Make participant counts available to JavaScript
    const heatParticipantCounts = <?= json_encode($heat_participant_counts ?? []) ?>;
    window.heatParticipantCounts = heatParticipantCounts;
    
    // Initialize run options and scoring methods for all heats
    <?php foreach ($heat_order as $h): ?>
        // Initialize each heat with proper values
        (function(heatNum) {
            const savedScoringMethod = '<?= $heat_settings[$h]['runs_scoring_method'] ?? 'best_from_all' ?>';
            
            // Update run options first
            updateRunOptions(heatNum);
            
            // Set the saved scoring method
            const scoringSelect = document.getElementById(`runs_scoring_${heatNum}`);
            if (scoringSelect && savedScoringMethod) {
                scoringSelect.value = savedScoringMethod;
                updateScoringExplanation(heatNum);
            }
            
            calculateEstimatedFinish(heatNum);
            toggleFlowConfig(heatNum);
            
            // Initialize category selection
            <?php if (empty($heat_settings[$h]['categories'] ?? [])): ?>
                toggleAllCategories(heatNum);
            <?php endif; ?>
            
            // Attach heat name change listeners
            const nameInput = document.querySelector(`input[name="heat_name[${heatNum}]"]`);
            if (nameInput) {
                nameInput.addEventListener('input', function() {
                    updateHeatNameDisplay(heatNum);
                });
                nameInput.addEventListener('change', function() {
                    updateHeatNameReferences(heatNum);
                });
            }
        })(<?= $h ?>);
    <?php endforeach; ?>
    
    // Attach scoring method listeners
    attachScoringMethodListeners();
    
    // Show run selector for active heat
    const activeHeatRadio = document.querySelector('input[name="is_active"]:checked');
    if (activeHeatRadio) {
        toggleActiveHeat(activeHeatRadio.value);
    }
    
    // Add form validation
    const form = document.querySelector('form');
    if (form) {
        form.addEventListener('submit', function(e) {
            
            if (!validateForm()) {
                e.preventDefault();
            } else {
                // Update URL with event_id parameter before submission
                c
            }
        });
    }
    
    // Add keyboard shortcut for sorting (Ctrl+Shift+S)
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.shiftKey && e.key === 'S') {
            e.preventDefault();
            sortHeatsByFlow();
        }
    });
});
</script>

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