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

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

$event_id = $_GET['event_id'] ?? null;

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

try {
    // Fetch event details with sport and format information
    $event_stmt = $pdo->prepare("
        SELECT e.*, 
               sf.name as format_name, sf.mode as format_mode,
               fsd.icon_path as sport_icon_path, fsd.short_name as sport_short_name
        FROM events e
        LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
        LEFT JOIN figure_sports fs ON LOWER(e.sport_discipline) = LOWER(fs.sport_name)
        LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
        WHERE e.id = ?
    ");
    $event_stmt->execute([$event_id]);
    $event = $event_stmt->fetch(PDO::FETCH_ASSOC);

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

    // Initialize default values
    $participant_stats = [
        'total_participants' => 0,
        'male_participants' => 0,
        'female_participants' => 0,
        'total_categories' => 0,
        'total_heats' => 0
    ];

    $judge_stats = [
        'total_judges' => 0,
        'head_judges' => 0,
        'control_points_with_judges' => 0,
        'judge_names' => ''
    ];

    $scoring_stats = [
        'total_scores' => 0,
        'approved_scores' => 0,
        'pending_scores' => 0,
        'total_runs' => 0,
        'participants_with_scores' => 0,
        'average_score' => 0
    ];

    $categories = [];
    $control_points = [];
    $judge_assignments = [];
    $recent_scores = [];

    // Check if event_participants table exists
    try {
        $participants_stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as total_participants,
                COUNT(CASE WHEN gender = 'M' THEN 1 END) as male_participants,
                COUNT(CASE WHEN gender = 'F' THEN 1 END) as female_participants,
                COUNT(DISTINCT category) as total_categories,
                COUNT(DISTINCT heat_number) as total_heats
            FROM event_participants 
            WHERE event_id = ?
        ");
        $participants_stmt->execute([$event_id]);
        $result = $participants_stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $participant_stats = $result;
        }
    } catch (Exception $e) {
        // Table might not exist, use defaults
    }

    // Fetch categories breakdown
    try {
        $categories_stmt = $pdo->prepare("
            SELECT category, COUNT(*) as count, GROUP_CONCAT(DISTINCT heat_number ORDER BY heat_number) as heats
            FROM event_participants 
            WHERE event_id = ? 
            GROUP BY category 
            ORDER BY category
        ");
        $categories_stmt->execute([$event_id]);
        $categories = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Table might not exist
    }

    // Fetch event categories
    $event_categories = [];
    $category_stats = [
        'total_categories' => 0,
        'with_requirements' => 0,
        'with_country_restrictions' => 0
    ];
    
    try {
        $event_categories_stmt = $pdo->prepare("
            SELECT 
                category_name,
                start_year,
                end_year,
                gender,
                requires_fis_number,
                requires_licence_number,
                country_rule,
                country_codes,
                is_main_category,
                use_for_ranking
            FROM event_categories 
            WHERE event_id = ? 
            ORDER BY category_name
        ");
        $event_categories_stmt->execute([$event_id]);
        $event_categories = $event_categories_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Calculate category statistics
        $category_stats['total_categories'] = count($event_categories);
        foreach ($event_categories as $cat) {
            if ($cat['requires_fis_number'] || $cat['requires_licence_number']) {
                $category_stats['with_requirements']++;
            }
            if ($cat['country_rule'] !== 'all') {
                $category_stats['with_country_restrictions']++;
            }
        }
    } catch (Exception $e) {
        // Table might not exist
    }


    // Check if judge_assignments table exists
    try {
        $judges_stmt = $pdo->prepare("
            SELECT 
                COUNT(DISTINCT ja.judge_id) as total_judges,
                COUNT(CASE WHEN u.judge_id = 1 THEN 1 END) as head_judges,
                COUNT(DISTINCT ja.control_point_id) as control_points_with_judges,
                GROUP_CONCAT(DISTINCT u.username ORDER BY u.username SEPARATOR ', ') as judge_names
            FROM judge_assignments ja
            JOIN users u ON ja.judge_id = u.id
            WHERE ja.event_id = ?
        ");
        $judges_stmt->execute([$event_id]);
        $result = $judges_stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $judge_stats = $result;
        }
    } catch (Exception $e) {
        // Table might not exist
    }

    // Fetch control points
    try {
        $control_points_stmt = $pdo->prepare("
            SELECT ecp.*, COUNT(ja.judge_id) as assigned_judges
            FROM event_control_points ecp
            LEFT JOIN judge_assignments ja ON ecp.id = ja.control_point_id AND ja.event_id = ecp.event_id
            WHERE ecp.event_id = ?
            GROUP BY ecp.id
            ORDER BY ecp.sort_order, ecp.control_point_name
        ");
        $control_points_stmt->execute([$event_id]);
        $control_points = $control_points_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Table might not exist
    }

    // Fetch judge assignments by control point (including general)
    try {
        $judge_assignments_stmt = $pdo->prepare("
            SELECT 
                ja.control_point_id,
                CASE 
                    WHEN ja.control_point_id IS NULL THEN 'General Judging'
                    ELSE ecp.control_point_name
                END as control_point_name,
                u.id,
                u.username,
                u.judge_id as is_head,
                COALESCE(ecp.sort_order, 0) as sort_order,
                ecp.weight as control_point_weight
            FROM judge_assignments ja
            JOIN users u ON ja.judge_id = u.id
            LEFT JOIN event_control_points ecp ON ja.control_point_id = ecp.id
            WHERE ja.event_id = ?
            ORDER BY sort_order, control_point_name, u.username
        ");
        $judge_assignments_stmt->execute([$event_id]);
        $judge_assignments = $judge_assignments_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Table might not exist
    }

    // Fetch scoring statistics
    try {
        $scoring_stmt = $pdo->prepare("
            SELECT 
                COUNT(DISTINCT s.id) as total_scores,
                COUNT(CASE WHEN s.is_approved = 1 THEN 1 END) as approved_scores,
                COUNT(CASE WHEN s.is_approved = 0 THEN 1 END) as pending_scores,
                COUNT(DISTINCT s.run_id) as total_runs,
                COUNT(DISTINCT r.event_participant_id) as participants_with_scores,
                AVG(CASE WHEN s.status = 'OK' AND s.score_value IS NOT NULL THEN s.score_value END) as average_score
            FROM scores s
            JOIN runs r ON s.run_id = r.id
            JOIN event_participants ep ON r.event_participant_id = ep.id
            WHERE ep.event_id = ?
        ");
        $scoring_stmt->execute([$event_id]);
        $result = $scoring_stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $scoring_stats = $result;
        }
    } catch (Exception $e) {
        // Tables might not exist
    }

    // Fetch recent scoring activity
    try {
        $recent_scores_stmt = $pdo->prepare("
            SELECT 
                s.score_value,
                s.status,
                s.is_approved,
                s.created_at,
                ep.first_name,
                ep.last_name,
                ep.bib_number,
                u.username as judge_name,
                r.run_number,
                ep.heat_number
            FROM scores s
            JOIN runs r ON s.run_id = r.id
            JOIN event_participants ep ON r.event_participant_id = ep.id
            JOIN users u ON s.judge_id = u.id
            WHERE ep.event_id = ?
            ORDER BY s.created_at DESC
            LIMIT 10
        ");
        $recent_scores_stmt->execute([$event_id]);
        $recent_scores = $recent_scores_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Tables might not exist
    }

    // Fetch available reports configurations
    $report_configurations = [];
    try {
        $config_stmt = $pdo->prepare("
            SELECT id, name, view_type, heat_number, category, status, display_order, created_at
            FROM result_configurations 
            WHERE event_id = ? AND status = 'active'
            ORDER BY view_type, heat_number, display_order ASC, name ASC
        ");
        $config_stmt->execute([$event_id]);
        $report_configurations = $config_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Table might not exist
    }

} catch (Exception $e) {
    die("Database error: " . $e->getMessage());
}

// Calculate event progress with safe defaults
$runs_per_heat = $event['runs_per_heat'] ?? 1;
$total_possible_scores = $participant_stats['total_participants'] * $judge_stats['total_judges'] * $runs_per_heat;
$completion_percentage = $total_possible_scores > 0 ? round(($scoring_stats['total_scores'] / $total_possible_scores) * 100, 1) : 0;

// Determine status colors and icons
$status_config = [
    'draft' => ['color' => 'secondary', 'icon' => 'edit'],
    'open' => ['color' => 'success', 'icon' => 'door-open'],
    'closed' => ['color' => 'warning', 'icon' => 'lock'],
    'completed' => ['color' => 'info', 'icon' => 'check-circle']
];

$current_status = $status_config[$event['status']] ?? $status_config['draft'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Dashboard - <?= htmlspecialchars($event['name']) ?></title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <!-- Lucide Icons and translation utility are now included globally via stylesheets.php and footer.php -->
    
<!-- style skin holder -->

<style>
.card-hover:hover {
    transform: translateY(-2px);
    transition: transform 0.2s ease-in-out;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}
.overflow-auto {
    overflow: auto !important;
    display: grid;
    grid-template-columns: auto auto; 
    gap: .5em;
}
.category-setting {
    display: flex
;
    gap: 4px;
}
</style>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>

<script>
// Early-safe globals so inline onclicks never throw
window.currentFilter = window.currentFilter || 'all';
window.refreshReports = window.refreshReports || function() {
    try {
        if (typeof loadReports === 'function') {
            loadReports(window.currentFilter || 'all');
        }
    } catch (e) { /* no-op */ }
};
window.filterReports = window.filterReports || function(type) {
    window.currentFilter = type || 'all';
    try {
        if (typeof loadReports === 'function') {
            loadReports(window.currentFilter);
        }
    } catch (e) { /* no-op */ }
};
</script>

<div class="container-fluid container-StyleScore p-4">
    
    
    <!-- Event Header -->
    <div class="border-0 shadow-none card bg-primary text-white border-0 shadow-sm">
        <div class="border-0 shadow-none card-body">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-2">
                        <i class="fas fa-trophy fa-2x me-3"></i>
                        <div>
                            <h2 class="mb-1"><?= htmlspecialchars($event['name'] ?? '') ?></h2>
                            <div class="small opacity-75">
                                <i class="fas fa-calendar me-1"></i><?= date('F d, Y', strtotime($event['date'])) ?>
                                <span class="ms-3">
                                    <i class="fas fa-map-marker-alt me-1"></i><?= htmlspecialchars($event['location'] ?? '') ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2 flex-wrap">
                        <span class="badge text-bg-<?= $current_status['color'] ?>">
                            <i class="fas <?= $current_status['icon'] ?> me-1"></i><?= ucfirst($event['status']) ?>
                        </span>
                        
                        <!-- Sport Badge with Icon -->
                        <span class="badge text-bg-light text-dark d-flex align-items-center">
                            <?php if (!empty($event['sport_icon_path']) && file_exists('../' . $event['sport_icon_path'])): ?>
                                <img src="../<?= htmlspecialchars($event['sport_icon_path']) ?>" 
                                     alt="<?= htmlspecialchars($event['sport_discipline']) ?>" 
                                     style="width: 16px; height: 16px; object-fit: contain;" 
                                     class="me-1">
                            <?php endif; ?>
                            <?= htmlspecialchars($event['sport_short_name'] ?: $event['sport_discipline'] ?: 'Sport') ?>
                        </span>
                        
                        <!-- Format Badge with Icon -->
                        <?php if (!empty($event['scoring_format'])): ?>
                            <?php 
                            $format_key = strtolower($event['scoring_format']);
                            $format_img_path = "../assets/img/SVG/{$format_key}.svg";
                            $format_img_path_upper = "../assets/img/SVG/{$format_key}.SVG";
                            $has_format_icon = file_exists($format_img_path) || file_exists($format_img_path_upper);
                            if (file_exists($format_img_path_upper)) $format_img_path = $format_img_path_upper;
                            ?>
                            <span class="badge text-bg-info text-white d-flex align-items-center">
                                <?php if ($has_format_icon): ?>
                                    <span class="format-icon me-2">
                                        <img src="<?= $format_img_path ?>" alt="<?= htmlspecialchars($event['scoring_format']) ?>" style="width: 16px; height: 16px; object-fit: contain; filter: brightness(0) invert(1);">
                                    </span>
                                <?php endif; ?>
                                <?= htmlspecialchars($event['format_name'] ?: $event['scoring_format']) ?>
                                <?php if (!empty($event['format_mode'])): ?>
                                    <small class="ms-1 opacity-75">(<?= htmlspecialchars(str_replace('_', ' ', $event['format_mode'])) ?>)</small>
                                <?php endif; ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="text-end">
                        <div class="small opacity-75">Completion</div>
                        <div class="progress" role="progressbar" aria-valuenow="<?= (float)$completion_percentage ?>" aria-valuemin="0" aria-valuemax="100" style="height: 8px;">
                            <div class="progress-bar bg-light progress-bar-animated" style="width: <?= (float)$completion_percentage ?>%"></div>
                        </div>
                        <div class="fw-bold mt-1 text-light"><?= $completion_percentage ?>%</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<!-- Quick Actions -->
    <div class="row">
        <div class="col-12">
            <?php $show_header = false; include 'event_actions_menu.php'; ?>
        </div>
    </div>

    <div class="row">
        <!-- Left Column -->
        <div class="col-md-6">

        <!-- Heat Flow Information Panel -->
        <div class="row mb-4">
        <div class="col-12">
            <div class="border-0 shadow-none card border-0 shadow-sm card-hover">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-fire me-2"></i>Heat Flow Overview
                    </h5>
                        <div class="d-flex gap-2">
                            <button id="refreshHeatData" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-sync-alt me-1"></i>Refresh
                            </button>
                            
                            <a href="heat_flow_preview.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-external-link-alt me-1"></i>Full Preview
                            </a>
                            <a href="admin_heat_config.php?event_id=<?= $event_id ?>" class="btn btn-outline-info btn-sm">
                                <i class="fas fa-cogs me-1"></i>Configure
                            </a>
                            <a href="heat_management_modal.php?event_id=<?= $event_id ?>&standalone=1" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-wrench me-1"></i>Manage
                            </a>
                    </div>
                </div>
                <div class="border-0 shadow-none card-body">
                    
                    <!-- Loading State -->
                    <div id="heatLoadingState" class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading heat data...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading heat configuration...</p>
                        </div>

                        <!-- Error State -->
                        <div id="heatErrorState" class="alert alert-warning d-none">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <span id="heatErrorMessage">Failed to load heat data</span>
                        <button class="btn btn-outline-warning btn-sm ms-2" onclick="loadHeatData()">
                            <i class="fas fa-redo me-1"></i>Retry
                        </button>
                        </div>

                        <!-- Empty State -->
                        <div id="heatEmptyState" class="alert alert-secondary text-center d-none">
                        <i class="fas fa-fire fa-lg mb-2 text-muted d-block"></i>
                        <div class="fw-semibold">No Heat Configuration</div>
                        <div class="small text-muted mb-2">Configure heats to manage competition flow.</div>
                        <a href="admin_heat_config.php?event_id=<?= $event_id ?>" class="btn btn-primary btn-sm">
                            <i class="fas fa-cogs me-1"></i>Configure Heats
                        </a>
                        </div>

                        <!-- Heat Data Display -->
                        <div id="heatDataContainer" class="d-none">
                        <div class="row mb-3" id="heatStatsRow"></div>
                        <div id="heatChainsContainer"></div>
                        <div id="activeHeatContainer" class="mt-3"></div>
                        </div>
                </div>
            </div>
        </div>
    </div>
            <!-- Participants Breakdown -->
            <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-users me-2"></i>Participants by Category
                    </h5>
                </div>
                <div class="border-0 shadow-none card-body p-0">
                    <?php if (empty($categories)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-users-slash fa-3x mb-3 text-muted"></i>
                            <h6>No Participants Yet</h6>
                            <p class="text-muted">Start by adding participants to this event.</p>
                            <a href="heats_configure.php?event_id=<?= $event_id ?>" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i>Add Participants
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-sm mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Category</th>
                                        <th>Count</th>
                                        <th>Heats</th>
                                    </tr>
                                    </thead>
                                <tbody>
                                    <?php foreach ($categories as $category): ?>
                                        <tr>
                                            <td><strong><?= htmlspecialchars($category['category'] ?? '') ?></strong></td>
                                                                                        <td>
    <span class="badge bg-primary"><?= $category['count'] ?></span>
</td>
<!-- Removed stray JS from table -->
<td>
    <small class="text-muted"><?= htmlspecialchars($category['heats'] ?? '') ?></small>
</td>
       
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Recent Scoring Activity -->
            <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-clock me-2"></i>Recent Scoring Activity
                    </h5>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php foreach ($recent_scores as $score): ?>
                            <div class="border-bottom pb-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong>
                                            <?= htmlspecialchars(($score['first_name'] ?? '') . ' ' . ($score['last_name'] ?? '')) ?>
                                            <span class="badge bg-secondary">#<?= htmlspecialchars($score['bib_number'] ?? '') ?></span>
                                        </strong>
                                        <div class="small text-muted">
                                            Heat <?= htmlspecialchars($score['heat_number'] ?? '') ?>, Run <?= htmlspecialchars($score['run_number'] ?? '') ?> • 
                                            Judge: <?= htmlspecialchars($score['judge_name'] ?? '') ?>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <div class="h6 mb-1">
                                            <?php if ($score['status'] === 'OK' && $score['score_value']): ?>
                                                <span class="text-success"><?= htmlspecialchars($score['score_value'] ?? '') ?></span>
                                            <?php else: ?>
                                                <span class="text-warning"><?= htmlspecialchars($score['status'] ?? '') ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <span class="badge bg-<?= $score['is_approved'] ? 'success' : 'warning' ?>">
                                            <?= $score['is_approved'] ? 'Approved' : 'Pending' ?>
                                        </span>
                                        <div class="small text-muted">
                                            <?= date('M d, H:i', strtotime($score['created_at'])) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                   
                </div>
            </div>
                                                <!-- Event Format Settings -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                        <h5 class="mb-0 fw-bold text-primary">
                            <i class="fas fa-cogs me-2"></i>Event Format Settings
                        </h5>
                        <?php if (!empty($event['scoring_format'])): ?>
                            <a href="scoring_format_view.php?id=<?= urlencode($event['scoring_format']) ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-external-link-alt me-1"></i>Full Details
                            </a>
                        <?php endif; ?>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        
                        <?php 
                        // Load detailed format configuration
                        $formatSettings = null;
                        $judgeConfig = null;
                        $modeConfigs = [];
                        $rounds = [];
                        $criteriaByType = [];
                        
                        if (!empty($event['scoring_format'])) {
                            try {
                                // Load format details with judge configuration
                                $format_stmt = $pdo->prepare("
                                    SELECT sf.*, 
                                           sfj.min_judges, sfj.max_judges, sfj.scale_min, sfj.scale_max, 
                                           sfj.scale_type, sfj.scale_custom, sfj.precision_decimal, sfj.drop_rule
                                    FROM scoring_formats sf
                                    LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
                                    WHERE sf.format_id = ?
                                ");
                                $format_stmt->execute([$event['scoring_format']]);
                                $formatSettings = $format_stmt->fetch(PDO::FETCH_ASSOC);
                                
                                if ($formatSettings) {
                                    // Load mode configuration
                                    $mode_stmt = $pdo->prepare("
                                        SELECT config_type, config_key, config_value
                                        FROM scoring_format_mode_config
                                        WHERE format_id = ?
                                        ORDER BY config_type, config_key
                                    ");
                                    $mode_stmt->execute([$event['scoring_format']]);
                                    foreach ($mode_stmt->fetchAll(PDO::FETCH_ASSOC) as $config) {
                                        $modeConfigs[$config['config_type']][$config['config_key']] = $config['config_value'];
                                    }
                                    
                                    // Load rounds
                                    $rounds_stmt = $pdo->prepare("
                                        SELECT round_name, runs, aggregation
                                        FROM scoring_format_rounds
                                        WHERE format_id = ?
                                        ORDER BY round_name
                                    ");
                                    $rounds_stmt->execute([$event['scoring_format']]);
                                    $rounds = $rounds_stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    // Load criteria
                                    $criteria_stmt = $pdo->prepare("
                                        SELECT criteria_type, criteria_name, sort_order
                                        FROM scoring_format_criteria
                                        WHERE format_id = ?
                                        ORDER BY criteria_type, sort_order
                                    ");
                                    $criteria_stmt->execute([$event['scoring_format']]);
                                    foreach ($criteria_stmt->fetchAll(PDO::FETCH_ASSOC) as $criterion) {
                                        $criteriaByType[$criterion['criteria_type']][] = $criterion['criteria_name'];
                                    }
                                }
                            } catch (Exception $e) {
                                // Handle database errors gracefully
                                error_log("Format settings error: " . $e->getMessage());
                            }
                        }
                        
                        // Function to get drop rule name
                        function getDropRuleName($dropRule) {
                            $dropRuleNames = [
                                'none' => 'None',
                                'highest' => 'Drop Highest',
                                'lowest' => 'Drop Lowest', 
                                'highest_and_lowest' => 'Drop High/Low',
                                'median' => 'Median Score'
                            ];
                            return $dropRuleNames[$dropRule] ?? ucfirst(str_replace('_', ' ', $dropRule));
                        }
                        ?>
                        
                        <?php if ($formatSettings): ?>
                            <!-- Judge Configuration Section -->
                            <div class="mb-4">
                                <h6 class="text-primary border-bottom pb-2">
                                    <i class="fas fa-gavel me-2"></i>Judge Configuration
                                </h6>
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <div class="text-center p-2 bg-light rounded">
                                            <div class="h6 text-primary mb-1">
                                                <i class="fas fa-users"></i>
                                            </div>
                                            <strong>Number of Judges</strong>
                                            <div class="mt-1">
                                                <span class="badge bg-secondary">
                                                    <?= $formatSettings['min_judges'] ?>
                                                    <?php if ($formatSettings['max_judges'] && $formatSettings['max_judges'] != $formatSettings['min_judges']): ?>
                                                        -<?= $formatSettings['max_judges'] ?>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="text-center p-2 bg-light rounded">
                                            <div class="h6 text-primary mb-1">
                                                <i class="fas fa-ruler"></i>
                                            </div>
                                            <strong>Scoring Scale</strong>
                                            <div class="mt-1">
                                                <?php if ($formatSettings['scale_type'] === 'numeric'): ?>
                                                    <span class="badge bg-info">
                                                        <?= $formatSettings['scale_min'] ?> - <?= $formatSettings['scale_max'] ?>
                                                        <?php if ($formatSettings['precision_decimal'] > 0): ?>
                                                            (<?= $formatSettings['precision_decimal'] ?> decimal)
                                                        <?php endif; ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">
                                                        <?= htmlspecialchars($formatSettings['scale_custom']) ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="text-center p-2 bg-light rounded">
                                            <div class="h6 text-primary mb-1">
                                                <i class="fas fa-filter"></i>
                                            </div>
                                            <strong>Drop Rule</strong>
                                            <div class="mt-1">
                                                <span class="badge bg-secondary">
                                                    <?= htmlspecialchars(getDropRuleName($formatSettings['drop_rule'])) ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Mode Configuration Section -->
                            <?php if (!empty($modeConfigs)): ?>
                                <div class="mb-4">
                                    <h6 class="text-info border-bottom pb-2">
                                        <i class="fas fa-cogs me-2"></i>Mode Configuration
                                    </h6>
                                    <?php foreach ($modeConfigs as $configType => $configs): ?>
                                        <div class="mb-2">
                                            <strong class="text-primary"><?= str_replace('_', ' ', ucwords($configType)) ?>:</strong>
                                            <div class="d-flex flex-wrap gap-1 mt-1">
                                                <?php foreach ($configs as $key => $value): ?>
                                                    <span class="badge bg-light border text-dark">
                                                        <strong><?= str_replace('_', ' ', $key) ?>:</strong> <?= $value ?>
                                                    </span>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Rounds Configuration Section -->
                            <?php if (!empty($rounds)): ?>
                                <div class="mb-4">
                                    <h6 class="text-warning border-bottom pb-2">
                                        <i class="fas fa-layer-group me-2"></i>Rounds Configuration
                                    </h6>
                                    <div class="row g-2">
                                        <?php foreach ($rounds as $index => $round): ?>
                                            <div class="col-md-6">
                                                <div class="bg-light p-2 rounded border">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <strong class="text-primary"><?= htmlspecialchars($round['round_name']) ?></strong>
                                                        <span class="badge bg-primary">Round <?= $index + 1 ?></span>
                                                    </div>
                                                    <div class="d-flex gap-1">
                                                        <span class="badge bg-success">
                                                            <?= $round['runs'] ?> run<?= $round['runs'] != 1 ? 's' : '' ?>
                                                        </span>
                                                        <span class="badge bg-secondary">
                                                            <?= htmlspecialchars($round['aggregation']) ?>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Scoring Criteria Section -->
                            <?php if (!empty($criteriaByType)): ?>
                                <div class="mb-3">
                                    <h6 class="text-success border-bottom pb-2">
                                        <i class="fas fa-list-check me-2"></i>Scoring Criteria
                                    </h6>
                                    <?php foreach ($criteriaByType as $type => $criteriaList): ?>
                                        <div class="mb-2">
                                            <strong class="text-primary"><?= str_replace('_', ' ', ucwords($type)) ?>:</strong>
                                            <div class="d-flex flex-wrap gap-1 mt-1">
                                                <?php foreach ($criteriaList as $criterion): ?>
                                                    <span class="badge bg-success text-white"><?= htmlspecialchars($criterion) ?></span>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Format Summary -->
                            <div class="bg-primary bg-opacity-10 p-3 rounded">
                                <div class="row text-center">
                                    <div class="col-3">
                                        <div class="small text-muted">Format</div>
                                        <strong><?= htmlspecialchars($formatSettings['name']) ?></strong>
                                    </div>
                                    <div class="col-3">
                                        <div class="small text-muted">Sport</div>
                                        <strong><?= htmlspecialchars($formatSettings['sport']) ?></strong>
                                    </div>
                                    <div class="col-3">
                                        <div class="small text-muted">Mode</div>
                                        <strong><?= str_replace('_', ' ', $formatSettings['mode']) ?></strong>
                                    </div>
                                    <div class="col-3">
                                        <div class="small text-muted">Status</div>
                                        <span class="badge bg-<?= $formatSettings['is_active'] ? 'success' : 'secondary' ?>">
                                            <?= $formatSettings['is_active'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-4">
                                <i class="fas fa-exclamation-triangle fa-2x mb-3 text-muted"></i>
                                <h6>No Format Configuration</h6>
                                <p class="text-muted">This event doesn't have a scoring format configured yet.</p>
                                <a href="scoring_formats.php" class="btn btn-primary">
                                    <i class="fas fa-plus me-1"></i>Configure Format
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

        </div>

     <!-- Right Column -->
        <div class="col-md-6">


        <!-- Statistics Overview -->
            <div class="row mb-4">
                <div class="col-md-3 p-1">
                    <div class="border-0 shadow-none card border-0 shadow-sm h-100 card-hover">
                        <div class="border-0 shadow-none card-body text-center">
                            <div class="h4 fw-bold text-primary"><?= $participant_stats['total_participants'] ?></div>
                            <div class="text-muted fw-semibold small">Participants</div>
                            <small class="text-success">
                                <i class="fas fa-male me-1"></i><?= $participant_stats['male_participants'] ?> , 
                                <i class="fas fa-female me-1"></i><?= $participant_stats['female_participants'] ?> 
                            </small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 p-1">
                    <div class="border-0 shadow-none card border-0 shadow-sm h-100 card-hover">
                        <div class="border-0 shadow-none card-body text-center">
                            <div class="h4 fw-bold text-info"><?= $judge_stats['total_judges'] ?></div>
                            <div class="text-muted fw-semibold small">Judges</div>
                            <small class="text-warning">
                                <i class="fas fa-star me-1"></i><?= $judge_stats['head_judges'] ?> Head Judges
                            </small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 p-1">
                    <div class="border-0 shadow-none card border-0 shadow-sm h-100 card-hover">
                        <div class="border-0 shadow-none card-body text-center">
                            <div class="h4 fw-bold text-success"><?= $scoring_stats['approved_scores'] ?></div>
                            <div class="text-muted fw-semibold small">Scores</div>
                            <small class="text-danger">
                                <i class="fas fa-clock me-1"></i><?= $scoring_stats['pending_scores'] ?> Pending
                            </small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 p-1">
                    <div class="border-0 shadow-none card border-0 shadow-sm h-100 card-hover">
                        <div class="border-0 shadow-none card-body text-center">
                            <div class="h4 fw-bold text-warning"><?= $participant_stats['total_heats'] ?></div>
                            <div class="text-muted fw-semibold small">Active Heats</div>
                            <small class="text-info">
                                <i class="fas fa-running me-1"></i><?= $runs_per_heat ?> Runs per Heat
                            </small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Available Reports & Start Lists -->
            <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-file-alt me-2"></i>Reports & Start Lists
                    </h5>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-secondary btn-sm" onclick="refreshReports()" title="Refresh Reports">
                            <i class="fas fa-sync-alt me-1"></i>Refresh
                        </button>
                        <div class="dropdown">
                            <button class="btn btn-outline-info btn-sm dropdown-toggle" type="button" id="filterDropdown" data-bs-toggle="dropdown">
                                <i class="fas fa-filter me-1"></i>Filter
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="filterReports('all')">All Reports</a></li>
                                <li><a class="dropdown-item" href="#" onclick="filterReports('start_list')">Start Lists Only</a></li>
                                <li><a class="dropdown-item" href="#" onclick="filterReports('summary_table')">Summary Tables Only</a></li>
                            </ul>
                        </div>
                        
                    </div>
                </div>
                <div class="border-0 shadow-none card-body p-0">
                    <div id="reports-container">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading reports...</span>
                            </div>
                            <div class="mt-2 text-muted">Loading available reports...</div>
                        </div>
                    </div>
                </div>
                <div class="border-0 shadow-none card-footer text-right">
                   <a href="event_start_list.php?event_id=<?= $event_id ?>&view_type=start_list" class="btn btn-outline-success btn-sm">
                            <i class="fas fa-plus me-1"></i>Start List
                        </a>
                        <a href="event_start_list.php?event_id=<?= $event_id ?>&view_type=summary_table" class="btn btn-outline-info btn-sm">
                            <i class="fas fa-plus me-1"></i>Summary Table
                        </a>
                        <a href="results_styling.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-palette me-1"></i>Styling
                        </a>
            </div></div>

            <!-- Event Categories -->
            <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h5 class="mb-0 fw-bold text-primary">
                        <i class="fas fa-tags me-2"></i>Sport Categories
                    </h5>
                    <a href="event_categories.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-cog me-1"></i>Manage
                    </a>
                </div>
                <div class="border-0 shadow-none card-body">
                    
                    <?php if (empty($event_categories)): ?>
                        <div class="empty-state">
                            <i class="fas fa-tags fa-3x mb-3 text-muted"></i>
                            <h6>No Categories Defined</h6>
                            <p>Create sport categories to organize participants automatically.</p>
                            <a href="event_categories.php?event_id=<?= $event_id ?>" class="btn btn-success">
                                <i class="fas fa-plus me-1"></i>Create Categories
                            </a>
                        </div>
                    <?php else: ?>
                        <!-- Category Statistics -->
                        <div class="row text-center mb-3">
                            <div class="col-4">
                                <div class="h5 text-primary mb-1"><?= $category_stats['total_categories'] ?></div>
                                <small class="text-muted">Total Categories</small>
                            </div>
                            <div class="col-4">
                                <div class="h5 text-warning mb-1"><?= $category_stats['with_requirements'] ?></div>
                                <small class="text-muted">With Requirements</small>
                            </div>
                            <div class="col-4">
                                <div class="h5 text-info mb-1"><?= $category_stats['with_country_restrictions'] ?></div>
                                <small class="text-muted">Country Rules</small>
                            </div>
                        </div>
                        
                        <!-- Categories List -->
                        <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                            <table class="table table-hover table-sm mb-0">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <td>Category Name</td>
                                        <td>Gender & Age</td>
                                        <td>Requirements</td>
                                        <td>Main/Ranking</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($event_categories as $category): ?>
                                        <tr>
                                            <td>
                                                <div class="fw-bold">
                                                    <i class="fas fa-tag text-success me-1"></i>
                                                    <?= htmlspecialchars($category['category_name'] ?? '') ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex flex-wrap gap-1">
                                                    <!-- Gender Badge -->
                                                    <?php
                                                    $gender_config = [
                                                        'M' => ['color' => 'info', 'icon' => 'fa-mars', 'text' => 'Male'],
                                                        'F' => ['color' => 'danger', 'icon' => 'fa-venus', 'text' => 'Female'],
                                                        'open' => ['color' => 'success', 'icon' => 'fa-venus-mars', 'text' => 'Open']
                                                    ];
                                                    $gender_info = $gender_config[$category['gender']] ?? $gender_config['open'];
                                                    ?>
                                                    <span class="badge bg-<?= $gender_info['color'] ?> text-white small">
                                                        <i class="fas <?= $gender_info['icon'] ?> me-1"></i>
                                                        <?= $gender_info['text'] ?>
                                                    </span>
                                                    
                                                    <!-- Age Range -->
                                                    <?php if ($category['start_year'] || $category['end_year']): ?>
                                                        <span class="badge bg-warning small">
                                                            <i class="fas fa-birthday-cake me-1"></i>
                                                            <?= $category['start_year'] ?: 'Any' ?>-<?= $category['end_year'] ?: 'Any' ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if ($category['requires_fis_number'] || $category['requires_licence_number']): ?>
                                                    <div class="d-flex flex-wrap gap-1">
                                                        <?php if ($category['requires_fis_number']): ?>
                                                            <span class="badge bg-primary text-white small">
                                                                <i class="fas fa-id-card me-1"></i>FIS
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($category['requires_licence_number']): ?>
                                                            <span class="badge bg-warning small">
                                                                <i class="fas fa-certificate me-1"></i>Licence
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small">None</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="d-flex flex-wrap gap-1">
                                                    <?php if ($category['is_main_category']): ?>
                                                        <span class="badge bg-primary text-white small">
                                                            <i class="fas fa-star me-1"></i>Main
                                                        </span>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($category['use_for_ranking']): ?>
                                                        <span class="badge bg-success text-white small">
                                                            <i class="fas fa-trophy me-1"></i>Ranking
                                                        </span>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!$category['is_main_category'] && !$category['use_for_ranking']): ?>
                                                        <span class="text-muted small">Standard</span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                            
                            <!-- Auto-assignment info -->
                            <div class="mt-3 p-2 bg-info bg-opacity-10 border border-info rounded">
                                <small class="text-info">
                                    <i class="fas fa-robot me-1"></i>
                                    Use the <strong>Sport Categories</strong> panel to run auto-assignment of participants.
                                </small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Judge Assignments -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                        <h5 class="mb-0 fw-bold text-primary">
                            <i class="fas fa-gavel me-2"></i>Judge Assignments by Control Point
                        </h5>
                        <a href="judge_assign.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-cog me-1"></i>Manage
                        </a>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="overflow-auto" id="judge-assignments">
                            <?php if (empty($judge_assignments)): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-user-slash fa-3x mb-3 text-muted"></i>
                                    <h6>No Judges Assigned</h6>
                                    <p class="text-muted">Assign judges to control points to enable scoring.</p>
                                    <a href="judge_assign.php?event_id=<?= $event_id ?>" class="btn btn-success">
                                        <i class="fas fa-gavel me-1"></i>Assign Judges
                                    </a>
                                </div>
                            <?php else: ?>
                                <?php
                                // Group assignments by control point
                                $assignments_by_cp = [];
                                foreach ($judge_assignments as $assignment) {
                                    $cp_key = $assignment['control_point_id'] ?? 'general';
                                    if (!isset($assignments_by_cp[$cp_key])) {
                                        $assignments_by_cp[$cp_key] = [
                                            'name' => $assignment['control_point_name'],
                                            'weight' => $assignment['control_point_weight'],
                                            'judges' => []
                                        ];
                                    }
                                    $assignments_by_cp[$cp_key]['judges'][] = $assignment;
                                }
                                ?>
                                <?php foreach ($assignments_by_cp as $cp_key => $cp_data): ?>
                                    <div class="mb-3 p-3 border rounded"  data-cp-id="<?= htmlspecialchars($cp_key) ?>" data-cp-name="<?= htmlspecialchars($cp_data['name'] ?? '') ?>">
                                        <h6 class="fw-bold mb-2">
                                            <?php if ($cp_key === 'general'): ?>
                                                <i class="fas fa-star text-warning me-1"></i>
                                            <?php else: ?>
                                                <i class="fas fa-map-marker-alt text-info me-1"></i>
                                            <?php endif; ?>
                                            <?= htmlspecialchars($cp_data['name'] ?? '') ?>
                                            <span class="badge bg-secondary ms-2"><?= count($cp_data['judges']) ?></span>
                                            <?php if ($cp_key !== 'general' && !empty($cp_data['weight'])): ?>
                                                <span class="badge bg-warning text-dark ms-1" title="Control Point Weight">
                                                    <i class="fas fa-weight-hanging me-1"></i><?= number_format($cp_data['weight'], 1) ?>
                                                </span>
                                            <?php endif; ?>
                                        </h6>
                                        <div>
                                            <?php foreach ($cp_data['judges'] as $judge): ?>
                                                <span class="btn btn-sm btn-outline-primary judge-badge <?= $judge['is_head'] == 1 ? 'head-judge' : '' ?>" 
                                                      onclick="viewJudgeInfo(<?= $judge['id'] ?>, '<?= htmlspecialchars($judge['username']) ?>')"
                                                      style="cursor: pointer;"
                                                      title="Click to view judge information">
                                                    <?php if ($judge['is_head'] == 1): ?>
                                                        <i class="fas fa-star me-1 text-warning"></i>
                                                    <?php endif; ?>
                                                    <?= htmlspecialchars($judge['username'] ?? '') ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                

                <!-- Event Details -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                        <h5 class="mb-0 fw-bold text-primary">
                            <i class="fas fa-info-circle me-2"></i>Event Details
                        </h5>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="mb-2">
                                    <small class="text-muted">Registration Deadline</small>
                                    <div><?= ($event['registration_deadline'] ?? null) ? date('M d, Y', strtotime($event['registration_deadline'])) : 'Not set' ?></div>
                                </div>
                                <div class="mb-2">
                                    <small class="text-muted">Entry Fee</small>
                                    <div><?= ($event['entry_fee'] ?? null) ? '$' . number_format($event['entry_fee'], 2) : 'Free' ?></div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="mb-2">
                                    <small class="text-muted">Age Limit</small>
                                    <div><?= htmlspecialchars($event['age_limit'] ?? 'None') ?></div>
                                </div>
                                <div class="mb-2">
                                    <small class="text-muted">Max Participants</small>
                                    <div><?= htmlspecialchars($event['max_participants'] ?? 'Unlimited') ?></div>
                                </div>
                            </div>
                        </div>
                        <?php if (!empty($event['description'])): ?>
                            <div class="mt-3">
                                <small class="text-muted">Description</small>
                                <div class="mt-1"><?= nl2br(htmlspecialchars($event['description'] ?? '')) ?></div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<script>
// Global variables for reports management
// Use window.currentFilter instead of let to avoid duplicate declaration conflicts
let reportsData = null;



// Make showHTMLPreview globally accessible - defined early
window.showHTMLPreview = function(url, title) {
    // Check for modal elements
    setTimeout(function() {
        let modal = document.getElementById('summaryModal');
        let modalTitle = document.getElementById('summaryModalTitle');
        let modalBody = document.getElementById('summaryModalBody');
        
        if (!modal || !modalTitle || !modalBody) {
            // Create the modal dynamically if it's missing
            const modalHTML = `
                <div class="modal fade" id="summaryModal" tabindex="-1" aria-labelledby="summaryModalTitle" aria-hidden="true">
                    <div class="modal-dialog modal-xl modal-dialog-scrollable">
                        <div class="modal-content">
                            <div class="modal-header bg-primary text-white">
                                <h3 class="modal-title fs-5 mb-0" id="summaryModalTitle">
                                    <i class="fas fa-table me-2"></i>Report
                                </h3>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body" id="summaryModalBody"></div>
                        </div>
                    </div>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            // Re-get the elements
            modal = document.getElementById('summaryModal');
            modalTitle = document.getElementById('summaryModalTitle');
            modalBody = document.getElementById('summaryModalBody');
            
            if (!modal || !modalTitle || !modalBody) {
                window.open(url, '_blank');
                return;
            }
        }
        
        // Show modal content
        showModalContent(modal, modalTitle, modalBody, url, title);
    }, 100);
    
    // Helper function to show modal content
    function showModalContent(modal, modalTitle, modalBody, url, title) {
        modalTitle.innerHTML = `<i class="fas fa-file-alt me-2"></i>${title}`;
        modalBody.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading report...</p>
            </div>
        `;
        
        // Translate any new Font Awesome icons to Lucide
        if (window.translateFAToLucide) {
            window.translateFAToLucide();
        }
        
        // Show the modal
        const bootstrapModal = new bootstrap.Modal(modal);
        bootstrapModal.show();
        
        // Fetch the HTML content
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.text();
            })
            .then(html => {
                modalBody.innerHTML = `
                    <div class="d-flex justify-content-end mb-3">
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary" onclick="window.open('${url}', '_blank')">
                                <i class="fas fa-external-link-alt me-1"></i>Open in New Tab
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="printIframeReport()">
                                <i class="fas fa-print me-1"></i>Print
                            </button>
                        </div>
                    </div>
                    <iframe id="reportIframe" 
                            style="width: 100%; height: 60vh; border: 1px solid #dee2e6; border-radius: 0.375rem;" 
                            srcdoc="">
                    </iframe>
                `;
                
                // Load the HTML content into the iframe
                const iframe = document.getElementById('reportIframe');
                iframe.srcdoc = html;
            })
            .catch(error => {
                modalBody.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Failed to load report: ${error.message}
                        <div class="mt-2">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="window.open('${url}', '_blank')">
                                <i class="fas fa-external-link-alt me-1"></i>Try opening in new tab
                            </button>
                        </div>
                    </div>
                `;
            });
    }
};

// Make printReport globally accessible - defined early
window.printReport = function() {
    const reportContent = document.getElementById('reportContent');
    if (!reportContent) {
        console.error('Report content not found');
        return;
    }
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Report</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    margin: 20px;
                    color: #333;
                }
                table { 
                    width: 100%; 
                    border-collapse: collapse; 
                    margin: 10px 0;
                }
                th, td { 
                    border: 1px solid #ddd; 
                    padding: 8px; 
                    text-align: left; 
                    font-size: 12px;
                }
                th { 
                    background-color: #f2f2f2; 
                    font-weight: bold;
                }
                .badge {
                    padding: 2px 6px;
                    border-radius: 3px;
                    font-size: 10px;
                    color: white;
                }
                .bg-primary { background-color: #0d6efd; }
                .bg-secondary { background-color: #6c757d; }
                .bg-success { background-color: #198754; }
                .bg-warning { background-color: #ffc107; color: black; }
                .bg-danger { background-color: #dc3545; }
                .bg-info { background-color: #0dcaf0; color: black; }
                @media print {
                    body { margin: 0; }
                    .no-print { display: none; }
                }
            </style>
        </head>
        <body>
            ${reportContent.innerHTML}
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
    }, 250);
};

// Make printIframeReport globally accessible - for iframe content
window.printIframeReport = function() {
    const iframe = document.getElementById('reportIframe');
    if (!iframe) {
        return;
    }
    
    try {
        // Try to access iframe content and print it
        const iframeWindow = iframe.contentWindow;
        if (iframeWindow) {
            iframeWindow.focus();
            iframeWindow.print();
        } else {
            // Fallback: open the same URL in a new window for printing
            const currentUrl = iframe.src || iframe.getAttribute('src');
            if (currentUrl && currentUrl !== 'about:blank') {
                window.open(currentUrl, '_blank');
            }
        }
    } catch (error) {
        // Final fallback: try to get the srcdoc content
        try {
            const srcdoc = iframe.srcdoc;
            if (srcdoc) {
                const printWindow = window.open('', '_blank');
                printWindow.document.write(srcdoc);
                printWindow.document.close();
                printWindow.focus();
                setTimeout(() => {
                    printWindow.print();
                }, 250);
            }
        } catch (fallbackError) {
            // Silent fail
        }
    }
};

// Global function for judge info modal - defined early to ensure availability
window.viewJudgeInfo = function(judgeId, username) {
    // Give a small delay to ensure DOM is ready
    setTimeout(() => {
        let modalElement = document.getElementById('viewJudgeModal');
        
        // If not found, try querySelector
        if (!modalElement) {
            modalElement = document.querySelector('#viewJudgeModal');
        }
        
        // If still not found, try finding by class and checking IDs
        if (!modalElement) {
            const allModals = document.querySelectorAll('.modal');
            for (let modal of allModals) {
                if (modal.id === 'viewJudgeModal') {
                    modalElement = modal;
                    break;
                }
            }
        }
        
        if (!modalElement) {
            // Last resort: create the modal dynamically
            modalElement = createJudgeModal();
        }
        
        try {
            // Method 1: Try getOrCreateInstance (Bootstrap 5.1+)
            if (bootstrap && bootstrap.Modal && bootstrap.Modal.getOrCreateInstance) {
                const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
                modal.show();
            }
            // Method 2: Try getInstance/new (Bootstrap 5.0+)
            else if (bootstrap && bootstrap.Modal) {
                let modal = bootstrap.Modal.getInstance(modalElement);
                if (!modal) {
                    modal = new bootstrap.Modal(modalElement);
                }
                modal.show();
            }
            // Method 3: Fallback to data attributes
            else {
                modalElement.classList.add('show');
                modalElement.style.display = 'block';
                document.body.classList.add('modal-open');
                
                // Create backdrop
                const backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop fade show';
                backdrop.id = 'judge-modal-backdrop';
                document.body.appendChild(backdrop);
            }
        } catch (error) {
            // Last resort: simple display
            modalElement.style.display = 'block';
            modalElement.classList.add('show');
        }
        
        // Show loading state
        const contentElement = document.getElementById('judgeInfoContent');
        if (contentElement) {
            contentElement.innerHTML = `
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading judge information...</p>
                </div>
            `;
        } else {
            console.error('judgeInfoContent element not found');
        }
        
        // Fetch judge details via AJAX
        fetch(`get_judge_details.php?judge_id=${judgeId}&username=${encodeURIComponent(username)}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.displayJudgeInfo(data.judge);
                } else {
                    const contentElement = document.getElementById('judgeInfoContent');
                    if (contentElement) {
                        contentElement.innerHTML = `
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Error loading judge information: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    }
                }
            })
            .catch(error => {
                // Fallback: try to get basic info from the page context
                window.displayBasicJudgeInfo(judgeId, username);
            });
    }, 100); // Small delay to ensure DOM is ready
};

// Global variable for judge info modal functions
window.currentJudgeInfo = {};

window.displayJudgeInfo = function(judge) {
    // Store current judge info for copy/print functions
    window.currentJudgeInfo = judge;
    
    // Format the date
    const formattedDate = judge.created_at ? new Date(judge.created_at).toLocaleString() : 'N/A';
    
    // Build the content
    const content = `
        <strong>User ID:</strong> <span class="badge bg-primary">${judge.id || 'N/A'}</span><br>
        <strong>Login Username:</strong> <code>${judge.username || 'N/A'}</code><br>
        <strong>Password:</strong> <code>${judge.password || 'Not available'}</code><br>
        <strong>Head Judge:</strong> ${judge.judge_id == 1 ? '<span class="badge bg-warning">Yes</span>' : '<span class="badge bg-secondary">No</span>'}<br>
        <strong>Created:</strong> ${formattedDate}<br>
        <strong>Total Events:</strong> <span class="badge bg-success">${judge.event_count || 0}</span>
    `;
    
    document.getElementById('judgeInfoContent').innerHTML = content;
    
    // Translate any new Font Awesome icons to Lucide
    if (window.translateFAToLucide) {
        window.translateFAToLucide();
    }
};

window.displayBasicJudgeInfo = function(judgeId, username) {
    // Fallback display when AJAX fails
    window.currentJudgeInfo = {
        id: judgeId,
        username: username,
        password: 'Not available',
        judge_id: 0,
        created_at: new Date().toISOString()
    };
    
    const content = `
        <strong>Login Username:</strong> <code>${username}</code><br>
        <strong>Judge ID:</strong> <span class="badge bg-primary">${judgeId || 'N/A'}</span><br>
        <strong>Password:</strong> <span class="text-muted">Not available in this context</span><br>
        <div class="mt-2">
            <small class="text-info">
                <i class="fas fa-info-circle me-1"></i>
                Full judge details can be viewed in the <a href="judge_add.php">Judge Management</a> section.
            </small>
        </div>
    `;
    
    document.getElementById('judgeInfoContent').innerHTML = content;
};

window.copyCredentials = function() {
    const text = `Judge Login Credentials
Username: ${window.currentJudgeInfo.username}
Password: ${window.currentJudgeInfo.password}
Head Judge: ${window.currentJudgeInfo.judge_id == 1 ? 'Yes' : 'No'}
User ID: ${window.currentJudgeInfo.id}`;
    
    navigator.clipboard.writeText(text).then(() => {
        // Show success message
        const toast = document.createElement('div');
        toast.className = 'toast align-items-center text-white bg-success border-0 position-fixed top-0 end-0 m-3';
        toast.setAttribute('role', 'alert');
        toast.style.zIndex = '9999';
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <i class="fas fa-check-circle me-2"></i>Credentials copied to clipboard!
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;
        document.body.appendChild(toast);
        const bootstrapToast = new bootstrap.Toast(toast);
        bootstrapToast.show();
        setTimeout(() => toast.remove(), 5000);
    }).catch(err => {
        console.error('Failed to copy text: ', err);
        alert('Failed to copy credentials to clipboard');
    });
};

window.printCredentials = function() {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <html>
        <head>
            <title>Judge Credentials</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; }
                .header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 10px; margin-bottom: 20px; }
                .credentials { background: #f8f9fa; padding: 15px; border: 1px solid #dee2e6; border-radius: 5px; }
                .field { margin-bottom: 10px; }
                .label { font-weight: bold; }
            </style>
        </head>
        <body>
            <div class="header">
                <h2>Judge Login Credentials</h2>
            </div>
            <div class="credentials">
                <div class="field"><span class="label">Username:</span> ${window.currentJudgeInfo.username}</div>
                <div class="field"><span class="label">Password:</span> ${window.currentJudgeInfo.password}</div>
                <div class="field"><span class="label">Head Judge:</span> ${window.currentJudgeInfo.judge_id == 1 ? 'Yes' : 'No'}</div>
                <div class="field"><span class="label">User ID:</span> ${window.currentJudgeInfo.id}</div>
            </div>
        </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.print();
};

// Fallback function to create judge modal dynamically if not found in DOM
window.createJudgeModal = function() {
    console.log('Creating judge modal dynamically...');
    
    const modalHtml = `
        <div class="modal fade" id="viewJudgeModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-info text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-info-circle me-2"></i>Judge Information
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-user-check me-2"></i>Judge Details</h6>
                            <hr>
                            <div id="judgeInfoContent">
                                <!-- Content will be populated by JavaScript -->
                            </div>
                            <hr>
                            <small class="text-muted">
                                <i class="fas fa-shield-check me-1"></i>
                                This information should be kept secure and shared only with the judge.
                            </small>
                        </div>
                        
                        <div class="d-flex gap-2 mt-3">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="copyCredentials()">
                                <i class="fas fa-clipboard me-1"></i>Copy Credentials
                            </button>
                            <button type="button" class="btn btn-outline-success btn-sm" onclick="printCredentials()">
                                <i class="fas fa-print me-1"></i>Print Info
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Add modal to the page
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Return the created modal element
    return document.getElementById('viewJudgeModal');
};

// Global function to close judge modal
window.closeJudgeModal = function() {
    const modalElement = document.getElementById('viewJudgeModal');
    if (!modalElement) return;
    
    try {
        if (bootstrap && bootstrap.Modal) {
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            } else {
                // Fallback manual close
                modalElement.classList.remove('show');
                modalElement.style.display = 'none';
                document.body.classList.remove('modal-open');
                
                // Remove backdrop
                const backdrop = document.getElementById('judge-modal-backdrop');
                if (backdrop) {
                    backdrop.remove();
                }
            }
        } else {
            // Manual close
            modalElement.classList.remove('show');
            modalElement.style.display = 'none';
            document.body.classList.remove('modal-open');
            
            // Remove backdrop
            const backdrop = document.getElementById('judge-modal-backdrop');
            if (backdrop) {
                backdrop.remove();
            }
        }
    } catch (error) {
        console.error('Error closing modal:', error);
        // Force close
        modalElement.style.display = 'none';
        modalElement.classList.remove('show');
    }
};

document.addEventListener('DOMContentLoaded', function() {
    // Add close event handlers for judge modal
    const judgeModal = document.getElementById('viewJudgeModal');
    if (judgeModal) {
        // Handle backdrop clicks
        judgeModal.addEventListener('click', function(e) {
            if (e.target === judgeModal) {
                window.closeJudgeModal();
            }
        });
        
        // Handle close button clicks
        const closeButtons = judgeModal.querySelectorAll('[data-bs-dismiss="modal"]');
        closeButtons.forEach(button => {
            button.addEventListener('click', function() {
                window.closeJudgeModal();
            });
        });
    }
    
    loadHeatData();
    
    // Auto-refresh every 60 seconds
    setInterval(loadHeatData, 60000);
    
    // Manual refresh button
    document.getElementById('refreshHeatData').addEventListener('click', loadHeatData);
});

async function loadHeatData() {
    const eventId = <?= json_encode($event_id) ?>;
    
    try {
        showHeatLoadingState();
        
        const response = await fetch(`heat_flow_api.php?event_id=${eventId}`);
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || 'Failed to load heat data');
        }
        
        renderHeatData(data);
        
    } catch (error) {
        console.error('Error loading heat data:', error);
        showHeatErrorState(error.message);
    }
}

function showHeatLoadingState() {
  document.getElementById('heatLoadingState').classList.remove('d-none');
  document.getElementById('heatErrorState').classList.add('d-none');
  document.getElementById('heatEmptyState').classList.add('d-none');
  document.getElementById('heatDataContainer').classList.add('d-none');
}

function showHeatErrorState(message) {
  document.getElementById('heatLoadingState').classList.add('d-none');
  document.getElementById('heatErrorState').classList.remove('d-none');
  document.getElementById('heatEmptyState').classList.add('d-none');
  document.getElementById('heatDataContainer').classList.add('d-none');
  document.getElementById('heatErrorMessage').textContent = message;
}

function showHeatEmptyState() {
  document.getElementById('heatLoadingState').classList.add('d-none');
  document.getElementById('heatErrorState').classList.add('d-none');
  document.getElementById('heatEmptyState').classList.remove('d-none');
  document.getElementById('heatDataContainer').classList.add('d-none');
}

function renderHeatData(data) {
  document.getElementById('heatLoadingState').classList.add('d-none');
  document.getElementById('heatErrorState').classList.add('d-none');
  document.getElementById('heatEmptyState').classList.add('d-none');
  document.getElementById('heatDataContainer').classList.remove('d-none');
  if (!data.flow_chains || data.flow_chains.length === 0) return showHeatEmptyState();
  renderHeatStatistics(data.statistics);
  renderHeatChains(data.flow_chains);
  renderActiveHeatInfo(data.flow_chains);
  
  // Translate any new Font Awesome icons to Lucide
  if (window.translateFAToLucide) {
    window.translateFAToLucide();
  }
}

function renderHeatStatistics(stats) {
    const statsContainer = document.getElementById('heatStatsRow');
    
    const statItems = [
        { 
            value: stats.total_heats, 
            label: 'Total Heats', 
            color: 'primary',
            icon: 'flame'
        },
        { 
            value: stats.flow_chains, 
            label: 'Flow Chains', 
            color: 'info',
            icon: 'git-branch'
        },
        { 
            value: stats.auto_flow_heats, 
            label: 'Auto Flow', 
            color: 'success',
            icon: 'route'
        },
        { 
            value: stats.total_participants, 
            label: 'Participants', 
            color: 'warning',
            icon: 'users'
        },
        { 
            value: stats.active_heats, 
            label: 'Active Heats', 
            color: 'danger',
            icon: 'zap'
        }
    ];
    
    statsContainer.innerHTML = statItems.map(item => `
        <div class="col p-1">
            <div class="border-0 shadow-none card border-0 shadow-sm h-100 card-hover">
                <div class="border-0 shadow-none card-body text-center p-3">
                    <div class="h4 fw-bold text-${item.color} mb-1">
                        <i data-lucide="${item.icon}" class="me-1"></i>
                        ${item.value}
                    </div>
                    <div class="small text-muted">${item.label}</div>
                </div>
            </div>
        </div>
    `).join('');
}

function renderHeatChains(chains) {
  const container = document.getElementById('heatChainsContainer');
  if (!chains.length) {
    container.innerHTML = '<div class="text-muted">No heat chains configured.</div>';
    return;
  }
  let html = '<h6 class="mb-2"><i class="fas fa-sitemap me-2"></i>Heat Flow Chains</h6>';
  chains.forEach((chain, idx) => {
    const totalParticipants = chain.reduce((s,h)=>s+h.participant_count,0);
    const hasConflicts = chain.some(h=>h.has_time_conflict);
    html += `
      <div class="border rounded p-3 mb-2 ${hasConflicts ? 'border-danger' : ''}">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <div class="fw-semibold">Chain ${idx+1}</div>
          <div class="small text-muted">${totalParticipants} participants</div>
        </div>
        <div class="d-flex flex-wrap align-items-center gap-2">
          ${chain.map((h,i)=>createMiniHeatNode(h,i,chain)).join('')}
        </div>
      </div>
    `;
  });
  container.innerHTML = html;
}

function createMiniHeatNode(heat, index, chain) {
  const isActive = !!heat.is_active;
  const hasFlow = heat.flow_type && heat.flow_type !== 'none';
  const next = chain[index+1];
  const connected = next && next.flow_source_heat == heat.heat_number;
  const nodeClasses = [
    'border','rounded','p-2','text-center','bg-light'
  ];
  if (isActive) nodeClasses.push('border-success','bg-success-subtle');
  if (hasFlow && !isActive) nodeClasses.push('border-warning','bg-warning-subtle');

  let timeInfo = '';
  if (heat.time_start) {
    timeInfo = heat.estimated_end_time && heat.estimated_end_time !== heat.time_start
      ? `${heat.time_start}-${heat.estimated_end_time}` : heat.time_start;
  } else if (heat.estimated_start_time) {
    timeInfo = `~${heat.estimated_start_time}`;
  }

  let html = `
    <div class="${nodeClasses.join(' ')}">
      <div class="fw-semibold">Heat ${heat.heat_number} ${isActive ? '<i class="fas fa-bolt text-success ms-1"></i>' : ''}</div>
      ${heat.heat_name ? `<div class="small">${heat.heat_name}</div>` : ''}
      <div class="small text-muted">${heat.participant_count} participants${timeInfo ? `<br>${timeInfo}` : ''}</div>
    </div>
  `;
  if (index < chain.length - 1) {
    html += connected
      ? '<i class="fas fa-arrow-right text-success"></i>'
      : '<i class="fas fa-ellipsis-h text-muted"></i>';
  }
  return html;
}

function renderActiveHeatInfo(chains) {
  const container = document.getElementById('activeHeatContainer');
  const actives = [];
  chains.forEach(c => c.forEach(h => { if (h.is_active) actives.push(h); }));
  if (!actives.length) {
    container.innerHTML = `
      <div class="alert alert-info mb-0">
        <i class="fas fa-info-circle me-2"></i>No heats are currently active.
      </div>`;
    return;
  }
  let html = '<h6 class="mb-2"><i class="fas fa-bolt me-2"></i>Currently Active Heats</h6>';
  actives.forEach(h => {
    const cats = (h.categories||[]);
    const label = cats.length <= 3 ? cats.join(', ') : `${cats.slice(0,3).join(', ')} +${cats.length-3}`;
    html += `
      <div class="border border-success rounded p-3 mb-2">
        <div class="row align-items-center">
          <div class="col-md-8">
            <div class="fw-semibold mb-1"><i class="fas fa-fire me-1"></i>Heat ${h.heat_number}${h.heat_name ? ` - ${h.heat_name}` : ''}</div>
            <div class="small text-success mb-2"><i class="fas fa-play me-1"></i>Run ${h.active_run} of ${h.runs_count}</div>
            <div class="d-flex flex-wrap gap-1">
              <span class="badge text-bg-primary"><i class="fas fa-users me-1"></i>${h.participant_count}</span>
              <span class="badge text-bg-info"><i class="fas fa-tags me-1"></i>${label}</span>
              <span class="badge text-bg-secondary"><i class="fas fa-trophy me-1"></i>${h.scoring_type}</span>
            </div>
          </div>
          <div class="col-md-4 text-end">
            <a href="../judge/score.php?event_id=<?= $event_id ?>&heat=${h.heat_number}" class="btn btn-success btn-sm">
              <i class="fas fa-clipboard-list me-1"></i>Score Heat
            </a>
            <a href="../judge/head_judge.php?event_id=<?= $event_id ?>" class="btn btn-outline-primary btn-sm">
              <i class="fas fa-cogs me-1"></i>Manage
            </a>
          </div>
        </div>
      </div>
    `;
  });
  container.innerHTML = html;
}

// ---------- General Reports + Modal helpers ----------
const DASH_API = '../api/public_dashboard_api.php';
let configurationsCache = null;

function refreshGeneralReports(evtId) {
    fetch(`${DASH_API}?action=get_configurations&event_id=${encodeURIComponent(evtId)}`, { method: 'GET' })
        .then(r => r.json())
        .then(data => {
            const card = document.getElementById('general-reports-card');
            if (!card) return;
            card.classList.remove('d-none');
            if (data.success) {
                configurationsCache = data.configurations || [];
                updateGeneralReports(evtId, configurationsCache);
            } else {
                const gr = document.getElementById('general-reports');
                if (gr) gr.innerHTML = `<div class="text-danger small">${data.message||'Failed to load'}</div>`;
            }
        })
        .catch(() => {
            const gr = document.getElementById('general-reports');
            if (gr) gr.innerHTML = `<div class="text-danger small">Network error</div>`;
        });
}

function updateGeneralReports(evtId, configurations = []) {
    const container = document.getElementById('general-reports');
    const card = document.getElementById('general-reports-card');
    if (!container || !card) return;

    card.classList.remove('d-none');
    const general = (configurations || []).filter(c => !c.heat_number);
    if (general.length === 0) {
        container.innerHTML = `<div class="text-muted small">No general reports available</div>`;
        return;
    }

    const summaryTables = general.filter(c => c.view_type === 'summary_table');
    const startLists = general.filter(c => c.view_type === 'start_list');

    let html = '<div class="row g-2">';
    if (summaryTables.length) {
        html += `
            <div class="col-12">
                <small class="text-muted">Summary Tables:</small>
                <div class="d-flex flex-wrap gap-1 mt-1">
                    ${summaryTables.map(cfg => `
                        <button class="btn btn-sm btn-info"
                            onclick="loadSummaryTableCard(${evtId}, null, ${cfg.id}, '${String(cfg.name).replace(/'/g, "\\'")}')">
                            <i class="fas fa-table me-1"></i>${cfg.name}
                        </button>`).join('')}
                </div>
            </div>`;
    }
    if (startLists.length) {
        html += `
            <div class="col-12">
                <small class="text-muted">Start Lists:</small>
                <div class="d-flex flex-wrap gap-1 mt-1">
                    ${startLists.map(cfg => `
                        <button class="btn btn-sm btn-success"
                            onclick="loadStartListCard(${evtId}, null)">
                            <i class="fas fa-users me-1"></i>${cfg.name}
                        </button>`).join('')}
                </div>
            </div>`;
    }
    html += '</div>';
    container.innerHTML = html;
}

// Modal loaders (proxy via public_event_dashboard.php)
function loadSummaryTableCard(evtId, heatNumber, configId, configName) {
    const modal = document.getElementById('summaryModal');
    const modalTitle = document.getElementById('summaryModalTitle');
    const modalBody = document.getElementById('summaryModalBody');
    const heatLabel = heatNumber ? ` - Heat ${heatNumber}` : '';
    modalTitle.innerHTML = `<i class=\"fas fa-table me-2\"></i>${configName || 'Summary Table'}${heatLabel}`;
    modalBody.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <div class="mt-2 small text-muted">Loading summary table…</div>
        </div>`;
    const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
    bsModal.show();

    fetch('../public_event_dashboard.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `ajax=1&action=load_summary_table&config_id=${encodeURIComponent(configId)}`
    })
    .then(r => r.json())
    .then(res => {
        if (!res || res.success !== true) throw new Error(res?.message || 'Failed to load summary table');
        const data = res.data || {};
        const tableHead = data.table_head || '';
        const tableBody = data.table_body || '';
        const participantCount = data.participant_count;
        const filterSummary = data.filter_summary;
        const stats = (participantCount != null || filterSummary) ? `
            <div class=\"d-flex flex-wrap gap-2 align-items-center mb-2\">
                ${participantCount != null ? `<span class=\\"badge bg-primary\\">${participantCount} Participants</span>` : ''}
                ${filterSummary ? `<span class=\\"badge bg-info text-dark\\">${filterSummary}</span>` : ''}
            </div>` : '';
        modalBody.innerHTML = `
            ${stats}
            <div class="table-responsive">
                <style>${data.table_badge_colors || ''}</style>
                <table class="table table-sm table-striped table-hover mb-0">${tableHead}${tableBody}</table>
            </div>`;
    })
    .catch(err => {
        modalBody.innerHTML = `
            <div class="alert alert-danger mb-0">
                <i class="fas fa-exclamation-triangle me-2"></i>${err.message}
            </div>`;
    });
}

function loadStartListCard(evtId, heatNumber) {
    const modal = document.getElementById('summaryModal');
    const modalTitle = document.getElementById('summaryModalTitle');
    const modalBody = document.getElementById('summaryModalBody');
    const heatLabel = heatNumber ? ` - Heat ${heatNumber}` : ' - All Heats';
    modalTitle.innerHTML = `<i class=\"fas fa-users me-2\"></i>Start List${heatLabel}`;
    modalBody.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <div class="mt-2 small text-muted">Loading start list…</div>
        </div>`;
    const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
    bsModal.show();

    fetch('../public_event_dashboard.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `ajax=1&action=load_start_list&event_id=${encodeURIComponent(evtId)}${heatNumber ? `&heat_number=${encodeURIComponent(heatNumber)}` : ''}`
    })
    .then(r => r.json())
    .then(res => {
        if (!res || res.success !== true) throw new Error(res?.message || 'Failed to load start list');
        const htmlContent = res.html_content || res.html || (res.data && (res.data.html_content || res.data.html)) || '';
        modalBody.innerHTML = `
            <div class="overflow-auto" style="max-height:70vh;">
                ${htmlContent || '<div class="alert alert-info mb-0">No participants found</div>'}
            </div>`;
    })
    .catch(err => {
        modalBody.innerHTML = `
            <div class="alert alert-danger mb-0">
                <i class="fas fa-exclamation-triangle me-2"></i>${err.message}
            </div>`;
    });
}

</script>
<?php
// Include the heat management helper
include 'heat_management_helper.php';

// Include the modal
includeHeatManagementModal($event_id);

// Render the floating trigger button
renderHeatManagementFloatingButton($event_id);
?>

<!-- Remove all the previous Heat Management Modal HTML and JavaScript -->
<!-- The modal functionality is now handled by the external files -->

<script>
// Listen for heat settings updates from the modal
window.addEventListener('heatSettingsUpdated', function(event) {
    // Refresh the heat data when settings are updated
    loadHeatData();
     setInterval(loadHeatData, 60000);
    console.log('Heat settings updated:', event.detail);
});
</script>

<div class="modal fade" id="summaryModal" tabindex="-1" aria-labelledby="summaryModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h3 class="modal-title fs-5 mb-0" id="summaryModalTitle">
          <i class="fas fa-table me-2"></i>Report
        </h3>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="summaryModalBody"></div>
    </div>
  </div>
</div>

<!-- View Judge Info Modal -->
<div class="modal fade" id="viewJudgeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>Judge Information
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <h6><i class="fas fa-user-check me-2"></i>Judge Details</h6>
                    <hr>
                    <div id="judgeInfoContent">
                        <!-- Content will be populated by JavaScript -->
                    </div>
                    <hr>
                    <small class="text-muted">
                        <i class="fas fa-shield-check me-1"></i>
                        This information should be kept secure and shared only with the judge.
                    </small>
                </div>
                
                <div class="d-flex gap-2 mt-3">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="copyCredentials()">
                        <i class="fas fa-clipboard me-1"></i>Copy Credentials
                    </button>
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="printCredentials()">
                        <i class="fas fa-print me-1"></i>Print Info
                    </button>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
// Ensure viewJudgeInfo is available globally
window.viewJudgeInfo = function(judgeId, username) {
    // Show the modal first
    const modal = new bootstrap.Modal(document.getElementById('viewJudgeModal'));
    modal.show();
    
    // Show loading state
    document.getElementById('judgeInfoContent').innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading judge information...</p>
        </div>
    `;
    
    // Fetch judge details via AJAX
    fetch(`get_judge_details.php?judge_id=${judgeId}&username=${encodeURIComponent(username)}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayJudgeInfo(data.judge);
            } else {
                document.getElementById('judgeInfoContent').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading judge information: ${data.message || 'Unknown error'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            // Fallback: try to get basic info from the page context
            displayBasicJudgeInfo(judgeId, username);
        });
};

</script>

<script>
// Load reports from API - Global function
async function loadReports(filterType = 'all') {
    const eventId = <?= json_encode($event_id) ?>;
    const container = document.getElementById('reports-container');
    
    try {
        // Show loading state
        container.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading reports...</span>
                </div>
                <div class="mt-2 text-muted">Loading available reports...</div>
            </div>
        `;

        // Use the real API now that table structure is fixed
        const response = await fetch(`../api/reports_api.php?event_id=${eventId}&type=${filterType}`);
        const data = await response.json();
        
        if (data.success) {
            reportsData = data;
            window.currentFilter = filterType;
            renderReports(data);
        } else {
            throw new Error(data.error || 'Failed to load reports');
        }
    } catch (error) {
        console.error('Error loading reports:', error);
        container.innerHTML = `
            <div class="alert alert-danger m-3" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                Error loading reports: ${error.message}
            </div>
        `;
    }
}

// Render reports in the container
function renderReports(data) {
    const container = document.getElementById('reports-container');
    const eventId = <?= json_encode($event_id) ?>;
    
    if (!data.reports || data.reports.length === 0) {
        container.innerHTML = `
            <div class="table-responsive">
                <table class="table table-hover table-sm mb-0">
                    <thead class="table-light">
                        <tr>
                            <td>Name</td>
                            <td>Heat</td>
                            <td>Buttons</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td colspan="3" class="text-center py-4">
                                <i class="fas fa-file-alt fa-2x mb-2 text-muted"></i>
                                <div class="text-muted">No report configurations available</div>
                                <div class="mt-2">
                                    <a href="event_start_list.php?event_id=${eventId}&view_type=start_list" class="btn btn-success btn-sm me-2">
                                        <i class="fas fa-plus me-1"></i>Create Start List
                                    </a>
                                    <a href="event_start_list.php?event_id=${eventId}&view_type=summary_table" class="btn btn-info btn-sm">
                                        <i class="fas fa-plus me-1"></i>Create Summary Table
                                    </a>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        `;
        return;
    }

    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
                <thead class="table-light">
                    <tr>
                        <td>Name</td>
                        <td>Heat</td>
                        <td>Buttons</td>
                    </tr>
                </thead>
                <tbody>
    `;

    // Get grouped reports from API response
    const groupedReports = data.grouped_reports || {};
    
    // Display Start Lists first
    if (groupedReports.start_list && groupedReports.start_list.length > 0) {
        groupedReports.start_list.forEach(config => {
            const categoryText = config.category ? ` • ${escapeHtml(config.category)}` : '';
            const heatParam = config.heat_number ? `&heat_number=${config.heat_number}` : '';
            const configParam = `&config_name=${encodeURIComponent(config.name)}`;
            
            tableHTML += `
                <tr>
                    <td>
                        <div class="fw-bold">${escapeHtml(config.name)}</div>
                        <small class="text-success">
                            <i class="fas fa-list-ul me-1"></i>Start List${categoryText}
                        </small>
                    </td>
                    <td>
                        ${config.heat_number ? 
                            `<span class="badge bg-secondary">Heat ${config.heat_number}</span>` : 
                            `<span class="badge bg-primary">General</span>`
                        }
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" onclick="window.open('../api/start_list_api.php?event_id=${eventId}${heatParam}&format=pdf${configParam}', '_blank')" class="btn btn-outline-danger" title="Export PDF">
                                <i class="fas fa-file-pdf"></i>
                            </button>
                            <button type="button" onclick="showHTMLPreview('../api/start_list_api.php?event_id=${eventId}${heatParam}&format=html${configParam}', '${escapeHtml(config.name)} - Start List')" class="btn btn-outline-dark" title="View HTML">
                                <i class="fas fa-code"></i>
                            </button>
                            <button type="button" onclick="window.location.href='../api/start_list_api.php?event_id=${eventId}${heatParam}&format=csv${configParam}'" class="btn btn-outline-primary" title="Download CSV">
                                <i class="fas fa-file-csv"></i>
                            </button>
                            <button type="button" onclick="window.open('../api/start_list_api.php?event_id=${eventId}${heatParam}&format=json${configParam}', '_blank')" class="btn btn-outline-success" title="View JSON">
                                <i class="fas fa-code"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });
    }
    
    // Display Summary Tables
    if (groupedReports.summary_table && groupedReports.summary_table.length > 0) {
        groupedReports.summary_table.forEach(config => {
            const categoryText = config.category ? ` • ${escapeHtml(config.category)}` : '';
            const configParam = `&config_name=${encodeURIComponent(config.name)}`;
            
            tableHTML += `
                <tr>
                    <td>
                        <div class="fw-bold">${escapeHtml(config.name)}</div>
                        <small class="text-info">
                            <i class="fas fa-table me-1"></i>Summary Table${categoryText}
                        </small>
                    </td>
                    <td>
                        ${config.heat_number ? 
                            `<span class="badge bg-secondary">Heat ${config.heat_number}</span>` : 
                            `<span class="badge bg-warning">Results</span>`
                        }
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=${config.id}&format=pdf${configParam}', '_blank')" class="btn btn-outline-danger" title="Export PDF">
                                <i class="fas fa-file-pdf"></i>
                            </button>
                            <button type="button" onclick="showHTMLPreview('../api/summary_table_api.php?config_id=${config.id}&format=html${configParam}', '${escapeHtml(config.name)} - Summary Table')" class="btn btn-outline-dark" title="View HTML">
                                <i class="fas fa-code"></i>
                            </button>
                            <button type="button" onclick="window.location.href='../api/summary_table_api.php?config_id=${config.id}&format=csv${configParam}'" class="btn btn-outline-primary" title="Download CSV">
                                <i class="fas fa-file-csv"></i>
                            </button>
                            <button type="button" onclick="window.open('../api/summary_table_api.php?config_id=${config.id}&format=json${configParam}', '_blank')" class="btn btn-outline-success" title="View JSON">
                                <i class="fas fa-code"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });
    }

    tableHTML += `
                </tbody>
            </table>
        </div>
    `;

    container.innerHTML = tableHTML;
    
    // Translate any new Font Awesome icons to Lucide
    if (window.translateFAToLucide) {
        window.translateFAToLucide();
    }
}


// Utility function to escape HTML
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

// Show HTML preview (you may already have this function)
function showHTMLPreview(url, title) {
    // Create modal if it doesn't exist
    let previewModal = document.getElementById('htmlPreviewModal');
    if (!previewModal) {
        const modalHTML = `
            <div class="modal fade" id="htmlPreviewModal" tabindex="-1" aria-labelledby="htmlPreviewModalTitle" aria-hidden="true">
                <div class="modal-dialog modal-xl modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="htmlPreviewModalTitle">
                                <i class="fas fa-eye me-2"></i>Preview
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body p-0">
                            <iframe id="htmlPreviewIframe" style="width: 100%; height: 80vh; border: none;"></iframe>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        previewModal = document.getElementById('htmlPreviewModal');
    }
    
    // Update modal title and iframe source
    const modalTitle = document.getElementById('htmlPreviewModalTitle');
    const iframe = document.getElementById('htmlPreviewIframe');
    
    if (modalTitle) {
        modalTitle.innerHTML = `<i class="fas fa-eye me-2"></i>${title || 'Preview'}`;
    }
    
    if (iframe) {
        iframe.src = url;
    }
    
    // Show the modal
    const modal = new bootstrap.Modal(previewModal);
    modal.show();
}

// Load reports on page ready
document.addEventListener('DOMContentLoaded', function() {
    // Translate Font Awesome icons to Lucide
    window.translateFAToLucide();
    
    loadReports();
});

// Refresh reports (expose globally for inline onclick)
window.refreshReports = function() {
    loadReports(window.currentFilter);
};


// Filter reports by type - expose globally for inline menu
window.filterReports = function(type) {
    window.currentFilter = type || 'all';
    try {
        if (typeof loadReports === 'function') {
            loadReports(window.currentFilter);
        }
    } finally {
        const filterLabels = {
            all: 'All Reports',
            start_list: 'Start Lists Only',
            summary_table: 'Summary Tables Only'
        };
        const dropdown = document.getElementById('filterDropdown');
        if (dropdown && filterLabels[window.currentFilter]) {
            dropdown.innerHTML = `<i class="fas fa-filter me-1"></i>${filterLabels[window.currentFilter]}`;
        }
    }
};
</script>

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