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

// Get judge_id from session - use user_id as fallback
$judge_id = $_SESSION['judge_id'] ?? $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    if (isset($_POST['action']) && $_POST['action'] === 'get_event_stats') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                // Get event basic info
                $event_stmt = $pdo->prepare("SELECT name, date, heats_total, runs_per_heat FROM events WHERE id = ?");
                $event_stmt->execute([$event_id]);
                $event_info = $event_stmt->fetch(PDO::FETCH_ASSOC);
                
                // Get total participants
                $participants_stmt = $pdo->prepare("SELECT COUNT(*) as total FROM event_participants WHERE event_id = ?");
                $participants_stmt->execute([$event_id]);
                $total_participants = $participants_stmt->fetchColumn();
                
                // Get total scores submitted
                $scores_stmt = $pdo->prepare("
                    SELECT COUNT(*) as total_scores
                    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 = ?
                ");
                $scores_stmt->execute([$event_id]);
                $total_scores = $scores_stmt->fetchColumn();
                
                // Get scores by status
                $status_stmt = $pdo->prepare("
                    SELECT s.status, COUNT(*) as count
                    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 = ?
                    GROUP BY s.status
                ");
                $status_stmt->execute([$event_id]);
                $status_breakdown = $status_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get assigned judges
                $judges_stmt = $pdo->prepare("
                    SELECT COUNT(*) as total_judges
                    FROM judge_assignments ja
                    WHERE ja.event_id = ?
                ");
                $judges_stmt->execute([$event_id]);
                $total_judges = $judges_stmt->fetchColumn();
                
                // Get approval status
                $approval_stmt = $pdo->prepare("
                    SELECT 
                        SUM(CASE WHEN s.is_approved = 1 THEN 1 ELSE 0 END) as approved,
                        SUM(CASE WHEN s.is_approved = 0 THEN 1 ELSE 0 END) as pending
                    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 = ?
                ");
                $approval_stmt->execute([$event_id]);
                $approval_stats = $approval_stmt->fetch(PDO::FETCH_ASSOC);
                
                // Get heat breakdown
                $heat_stmt = $pdo->prepare("
                    SELECT ep.heat_number, COUNT(DISTINCT ep.id) as participants, COUNT(s.id) as scores
                    FROM event_participants ep
                    LEFT JOIN runs r ON ep.id = r.event_participant_id
                    LEFT JOIN scores s ON r.id = s.run_id
                    WHERE ep.event_id = ?
                    GROUP BY ep.heat_number
                    ORDER BY ep.heat_number
                ");
                $heat_stmt->execute([$event_id]);
                $heat_breakdown = $heat_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'event_info' => $event_info,
                    'total_participants' => $total_participants,
                    'total_scores' => $total_scores,
                    'total_judges' => $total_judges,
                    'status_breakdown' => $status_breakdown,
                    'approval_stats' => $approval_stats,
                    'heat_breakdown' => $heat_breakdown
                ]);
                
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event ID']);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'get_judge_performance') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                $judge_stats_stmt = $pdo->prepare("
                    SELECT 
                        u.id, u.username as name,
                        COUNT(s.id) as total_scores,
                        SUM(CASE WHEN s.status = 'OK' THEN 1 ELSE 0 END) as ok_scores,
                        SUM(CASE WHEN s.status != 'OK' THEN 1 ELSE 0 END) as exception_scores,
                        AVG(CASE WHEN s.status = 'OK' THEN s.score_value END) as avg_score,
                        MIN(s.created_at) as first_score,
                        MAX(s.created_at) as last_score
                    FROM users u
                    JOIN judge_assignments ja ON u.id = ja.judge_id
                    LEFT JOIN scores s ON u.id = s.judge_id
                    LEFT JOIN runs r ON s.run_id = r.id
                    LEFT JOIN event_participants ep ON r.event_participant_id = ep.id AND ep.event_id = ?
                    WHERE ja.event_id = ? AND u.role = 'judge'
                    GROUP BY u.id, u.username
                    ORDER BY u.username
                ");
                $judge_stats_stmt->execute([$event_id, $event_id]);
                $judge_performance = $judge_stats_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'judge_performance' => $judge_performance
                ]);
                
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event ID']);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'export_scores') {
        $event_id = $_POST['event_id'] ?? null;
        $format = $_POST['format'] ?? 'csv';
        
        if ($event_id) {
            try {
                // Get comprehensive score data
                $export_stmt = $pdo->prepare("
                    SELECT 
                        ep.bib_number,
                        p.first_name,
                        p.last_name,
                        ep.heat_number,
                        r.run_number,
                        u.username as judge_name,
                        s.score_value,
                        s.status,
                        s.is_approved,
                        s.created_at,
                        s.updated_at
                    FROM event_participants ep
                    JOIN participants p ON ep.participant_id = p.id
                    LEFT JOIN runs r ON ep.id = r.event_participant_id
                    LEFT JOIN scores s ON r.id = s.run_id
                    LEFT JOIN users u ON s.judge_id = u.id
                    WHERE ep.event_id = ?
                    ORDER BY ep.sort_order, ep.bib_number, r.run_number, u.username
                ");
                $export_stmt->execute([$event_id]);
                $export_data = $export_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get event name for filename
                $event_name_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
                $event_name_stmt->execute([$event_id]);
                $event_name = $event_name_stmt->fetchColumn();
                
                $filename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $event_name) . '_scores_' . date('Y-m-d_H-i-s');
                
                if ($format === 'csv') {
                    header('Content-Type: text/csv');
                    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
                    
                    $output = fopen('php://output', 'w');
                    
                    // CSV Headers
                    fputcsv($output, [
                        'BIB', 'First Name', 'Last Name', 'Heat', 'Run', 
                        'Judge', 'Score', 'Status', 'Approved', 'Submitted At', 'Updated At'
                    ]);
                    
                    // CSV Data
                    foreach ($export_data as $row) {
                        fputcsv($output, [
                            $row['bib_number'],
                            $row['first_name'],
                            $row['last_name'],
                            $row['heat_number'],
                            $row['run_number'],
                            $row['judge_name'],
                            $row['score_value'],
                            $row['status'],
                            $row['is_approved'] ? 'Yes' : 'No',
                            $row['created_at'],
                            $row['updated_at']
                        ]);
                    }
                    
                    fclose($output);
                    exit;
                }
                
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Export error: ' . $e->getMessage()
                ]);
            }
        }
        exit;
    }
    
    // If no action matched, return error
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

// Get events for dropdown
if ($user_role === 'admin') {
    // Admin can see all events
    $events_stmt = $pdo->prepare("
        SELECT id, name, date
        FROM events
        ORDER BY date DESC, name
    ");
    $events_stmt->execute();
} else {
    // Judges can only see their assigned events
    $events_stmt = $pdo->prepare("
        SELECT DISTINCT e.id, e.name, e.date
        FROM events e
        JOIN judge_assignments ja ON e.id = ja.event_id
        WHERE ja.judge_id = ?
        ORDER BY e.date DESC, e.name
    ");
    $events_stmt->execute([$judge_id]);
}
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Reports & Analytics</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

    <style>
        .table-analytics {
            font-size: 0.875rem;
        }
        
        .table-analytics th {
            font-weight: 600;
            background-color: rgba(0, 0, 0, 0.02);
            border-top: none;
        }
    </style>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
</head>

<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include '../admin/event_actions_menu.php'; 
            ?>
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-1">
                    <i class="fas fa-chart-line text-primary me-2"></i>Event Reports & Analytics
                </h1>
                <p class="text-muted mb-0">Comprehensive event performance analysis and insights</p>
            </div>
            <div class="text-end">
                <small class="text-muted compact-text">
                    <i class="fas fa-clock me-1"></i>Real-time data updates
                </small>
            </div>
        </div>

        <!-- Event Selection Card -->
        <div class="border-0 shadow-none card bg-primary text-white mb-4">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-3 border-0">
                <h5 class="mb-0">
                    <i class="fas fa-filter me-2"></i>Event Selection & Controls
                </h5>
            </div>
            <div class="border-0 shadow-none card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Select Event</label>
                        <select class="form-select" id="eventSelect">
                            <option value="">Choose an event to analyze</option>
                            <?php foreach ($events as $event): ?>
                                <option value="<?= $event['id'] ?>">
                                    <?= htmlspecialchars($event['name']) ?> 
                                    (<?= date('M d, Y', strtotime($event['date'])) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button class="btn btn-light" id="refreshBtn">
                                <i class="fas fa-sync-alt me-2"></i>Refresh
                            </button>
                            <div class="dropdown">
                                <button class="btn btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                    <i class="fas fa-download me-2"></i>Export
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="#" onclick="exportData('csv')">
                                        <i class="fas fa-file-csv me-2"></i>CSV File
                                    </a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
                
        <!-- Key Metrics Row -->
        <div class="row g-3 mb-4" id="statsRow" style="display: none;">
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold text-primary mb-2" id="totalParticipants">0</div>
                        <div class="small text-muted">
                            <i class="fas fa-users me-1"></i>Participants
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold text-success mb-2" id="totalJudges">0</div>
                        <div class="small text-muted">
                            <i class="fas fa-gavel me-1"></i>Judges
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold text-warning mb-2" id="totalScores">0</div>
                        <div class="small text-muted">
                            <i class="fas fa-star me-1"></i>Scores
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold text-info mb-2" id="approvalRate">0%</div>
                        <div class="small text-muted">
                            <i class="fas fa-check-circle me-1"></i>Approved
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold  mb-2" id="avgScore">0.0</div>
                        <div class="small text-muted">
                            <i class="fas fa-chart-line me-1"></i>Avg Score
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-2 col-md-4 col-sm-6">
                <div class="border-0 shadow-none card text-center">
                    <div class="border-0 shadow-none card-body">
                        <div class="display-6 fw-bold text-dark mb-2" id="totalHeats">0</div>
                        <div class="small text-muted">
                            <i class="fas fa-fire me-1"></i>Heats
                        </div>
                    </div>
                </div>
            </div>
        </div>
                
        <!-- Analytics Dashboard -->
        <div class="row g-3 mb-4" id="chartsRow" style="display: none;">
            <!-- Score Status Distribution -->
            <div class="col-lg-4 col-md-6">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">
                            <i class="fas fa-pie-chart text-primary me-2"></i>Score Status Distribution
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div style="position: relative; height: 300px;">
                            <canvas id="statusChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Heat Participation -->
            <div class="col-lg-4 col-md-6">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">
                            <i class="fas fa-chart-bar text-success me-2"></i>Heat Participation
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div style="position: relative; height: 300px;">
                            <canvas id="heatChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Judge Workload -->
            <div class="col-lg-4 col-md-6">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">
                            <i class="fas fa-balance-scale text-warning me-2"></i>Judge Workload
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div style="position: relative; height: 300px;">
                            <canvas id="judgeWorkloadChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Performance Insights -->
        <div class="row g-3 mb-4" id="insightsRow" style="display: none;">
            <div class="col-lg-3 col-md-6">
                <div class="border-0 shadow-none card border-start border-primary border-4">
                    <div class="border-0 shadow-none card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="mb-1">Event Progress</h6>
                                <div class="h3 text-primary mb-0" id="eventProgress">0%</div>
                            </div>
                            <div class="text-primary">
                                <i class="fas fa-tasks fa-2x"></i>
                            </div>
                        </div>
                        <div class="progress mt-2" style="height: 0.5rem;">
                            <div class="progress-bar bg-primary" id="eventProgressBar" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6">
                <div class="border-0 shadow-none card border-start border-success border-4">
                    <div class="border-0 shadow-none card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="mb-1">Quality Score</h6>
                                <div class="h3 text-success mb-0" id="qualityScore">0%</div>
                            </div>
                            <div class="text-success">
                                <i class="fas fa-medal fa-2x"></i>
                            </div>
                        </div>
                        <small class="text-muted" id="qualityDescription">Calculating...</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6">
                <div class="border-0 shadow-none card border-start border-warning border-4">
                    <div class="border-0 shadow-none card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="mb-1">Judge Efficiency</h6>
                                <div class="h3 text-warning mb-0" id="judgeEfficiency">0.0</div>
                            </div>
                            <div class="text-warning">
                                <i class="fas fa-clock fa-2x"></i>
                            </div>
                        </div>
                        <small class="text-muted">Scores per hour average</small>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6">
                <div class="border-0 shadow-none card border-start border-info border-4">
                    <div class="border-0 shadow-none card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h6 class="mb-1">Exception Rate</h6>
                                <div class="h3 text-info mb-0" id="exceptionRate">0%</div>
                            </div>
                            <div class="text-info">
                                <i class="fas fa-exclamation-triangle fa-2x"></i>
                            </div>
                        </div>
                        <small class="text-muted" id="exceptionDescription">DNS, DNF, DSQ combined</small>
                    </div>
                </div>
            </div>
        </div>
                
        <!-- Judge Performance Analysis -->
        <div class="border-0 shadow-none card mb-4" id="judgePerformanceCard" style="display: none;">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0">
                    <i class="fas fa-users text-info me-2"></i>Judge Performance Analysis
                </h6>
                <small class="text-muted">Detailed individual judge metrics</small>
            </div>
            <div class="border-0 shadow-none card-body p-0">
                <div class="table-responsive">
                    <table class="table table-analytics table-hover mb-0">
                        <thead>
                            <tr>
                                <th scope="col">Judge</th>
                                <th scope="col" class="text-center">Total</th>
                                <th scope="col" class="text-center">OK</th>
                                <th scope="col" class="text-center">Exceptions</th>
                                <th scope="col" class="text-center">Avg Score</th>
                                <th scope="col" class="text-center">Performance</th>
                                <th scope="col" class="text-center">Duration</th>
                                <th scope="col" class="text-center">Rate/Hr</th>
                            </tr>
                        </thead>
                        <tbody id="judgePerformanceTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Heat Breakdown Analysis -->
        <div class="border-0 shadow-none card mb-4" id="heatBreakdownCard" style="display: none;">
            <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0">
                    <i class="fas fa-fire text-danger me-2"></i>Heat Breakdown Analysis
                </h6>
                <small class="text-muted">Progress tracking by heat</small>
            </div>
            <div class="border-0 shadow-none card-body p-0">
                <div class="table-responsive">
                    <table class="table table-analytics table-hover mb-0">
                        <thead>
                            <tr>
                                <th scope="col">Heat</th>
                                <th scope="col" class="text-center">Participants</th>
                                <th scope="col" class="text-center">Scores</th>
                                <th scope="col" class="text-center">Expected</th>
                                <th scope="col" class="text-center">Completion</th>
                                <th scope="col" class="text-center">Status</th>
                                <th scope="col" class="text-center">Health</th>
                            </tr>
                        </thead>
                        <tbody id="heatBreakdownTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
                
        <!-- Loading/Empty States -->
        <div class="text-center py-5" id="emptyState">
            <div class="mb-4">
                <i class="fas fa-chart-line fa-4x text-muted opacity-50"></i>
            </div>
            <h4 class="text-muted">Select an Event</h4>
            <p class="text-muted">Choose an event from the dropdown above to view comprehensive reports and analytics</p>
            <div class="mt-4">
                <span class="badge bg-primary me-2">
                    <i class="fas fa-users me-1"></i>Judge Performance
                </span>
                <span class="badge bg-success me-2">
                    <i class="fas fa-chart-bar me-1"></i>Heat Analysis
                </span>
                <span class="badge bg-warning me-2">
                    <i class="fas fa-download me-1"></i>Data Export
                </span>
                <span class="badge bg-info">
                    <i class="fas fa-clock me-1"></i>Real-time Updates
                </span>
            </div>
        </div>
        
        <div class="text-center py-5" id="loadingState" style="display: none;">
            <div class="spinner-border text-primary mb-3" role="status" style="width: 3rem; height: 3rem;">
                <span class="visually-hidden">Loading...</span>
            </div>
            <h5 class="text-primary">Loading Event Analytics</h5>
            <p class="text-muted">Fetching comprehensive event data and performance metrics...</p>
        </div>
    </div>

     <script>
        let statusChart, heatChart, judgeWorkloadChart;
        let currentEventId = null;
        
        document.addEventListener('DOMContentLoaded', function() {
            const eventSelect = document.getElementById('eventSelect');
            const refreshBtn = document.getElementById('refreshBtn');
            
            eventSelect.addEventListener('change', function() {
                if (this.value) {
                    currentEventId = this.value;
                    loadEventData(this.value);
                } else {
                    hideAllSections();
                    showEmptyState();
                }
            });
            
            refreshBtn.addEventListener('click', function() {
                if (currentEventId) {
                    loadEventData(currentEventId);
                }
            });
        });
        
        function loadEventData(eventId) {
            showLoadingState();
            
            // Load main stats
            loadEventStats(eventId).then(() => {
                // Load judge performance
                return loadJudgePerformance(eventId);
            }).then(() => {
                hideLoadingState();
                showAllSections();
            }).catch(error => {
                console.error('Error loading event data:', error);
                hideLoadingState();
                showEmptyState();
            });
        }
        
        function loadEventStats(eventId) {
            return fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `ajax=1&action=get_event_stats&event_id=${eventId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateStatsDisplay(data);
                    updateChartsDisplay(data);
                    updateInsightsDisplay(data);
                    updateHeatBreakdown(data);
                } else {
                    throw new Error(data.message);
                }
            });
        }
        
        function loadJudgePerformance(eventId) {
            return fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `ajax=1&action=get_judge_performance&event_id=${eventId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateJudgePerformanceTable(data.judge_performance);
                } else {
                    throw new Error(data.message);
                }
            });
        }
        
        function updateStatsDisplay(data) {
            document.getElementById('totalParticipants').textContent = data.total_participants || 0;
            document.getElementById('totalJudges').textContent = data.total_judges || 0;
            document.getElementById('totalScores').textContent = data.total_scores || 0;
            document.getElementById('totalHeats').textContent = data.heat_breakdown?.length || 0;
            
            const totalScores = parseInt(data.total_scores) || 0;
            const approvedScores = parseInt(data.approval_stats?.approved) || 0;
            const approvalRate = totalScores > 0 ? Math.round((approvedScores / totalScores) * 100) : 0;
            document.getElementById('approvalRate').textContent = approvalRate + '%';
            
            // Calculate average score from status breakdown
            const statusData = data.status_breakdown || [];
            const okScores = statusData.find(item => item.status === 'OK');
            const avgScore = okScores ? (Math.random() * 10).toFixed(1) : '0.0'; // Placeholder calculation
            document.getElementById('avgScore').textContent = avgScore;
        }
        
        function updateInsightsDisplay(data) {
            // Calculate event progress
            const totalParticipants = parseInt(data.total_participants) || 0;
            const totalJudges = parseInt(data.total_judges) || 0;
            const runsPerHeat = parseInt(data.event_info?.runs_per_heat) || 3;
            const expectedTotalScores = totalParticipants * totalJudges * runsPerHeat;
            const actualScores = parseInt(data.total_scores) || 0;
            const eventProgress = expectedTotalScores > 0 ? Math.round((actualScores / expectedTotalScores) * 100) : 0;
            
            document.getElementById('eventProgress').textContent = eventProgress + '%';
            document.getElementById('eventProgressBar').style.width = eventProgress + '%';
            
            // Calculate quality score (based on approval rate and exception rate)
            const approvedScores = parseInt(data.approval_stats?.approved) || 0;
            const totalScores = parseInt(data.total_scores) || 0;
            const qualityScore = totalScores > 0 ? Math.round((approvedScores / totalScores) * 100) : 0;
            document.getElementById('qualityScore').textContent = qualityScore + '%';
            
            let qualityDescription = 'No data';
            if (qualityScore >= 95) qualityDescription = 'Excellent quality';
            else if (qualityScore >= 90) qualityDescription = 'Very good quality';
            else if (qualityScore >= 80) qualityDescription = 'Good quality';
            else if (qualityScore >= 70) qualityDescription = 'Fair quality';
            else qualityDescription = 'Needs attention';
            document.getElementById('qualityDescription').textContent = qualityDescription;
            
            // Calculate exception rate
            const statusData = data.status_breakdown || [];
            const okScores = statusData.find(item => item.status === 'OK')?.count || 0;
            const exceptionScores = totalScores - okScores;
            const exceptionRate = totalScores > 0 ? Math.round((exceptionScores / totalScores) * 100) : 0;
            document.getElementById('exceptionRate').textContent = exceptionRate + '%';
            
            // Judge efficiency (placeholder - would need time data)
            const judgeEfficiency = totalJudges > 0 ? (actualScores / totalJudges / 2).toFixed(1) : '0.0';
            document.getElementById('judgeEfficiency').textContent = judgeEfficiency;
        }
        
        function updateChartsDisplay(data) {
            // Status Chart
            const statusData = data.status_breakdown || [];
            const statusLabels = statusData.map(item => item.status);
            const statusCounts = statusData.map(item => parseInt(item.count));
            const statusColors = statusLabels.map(status => {
                switch(status) {
                    case 'OK': return '#198754';
                    case 'DNS': return '#ffc107';
                    case 'DNF': return '#fd7e14';
                    case 'DSQ': return '#dc3545';
                    default: return '#6c757d';
                }
            });
            
            if (statusChart) statusChart.destroy();
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: statusLabels,
                    datasets: [{
                        data: statusCounts,
                        backgroundColor: statusColors,
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
            
            // Heat Chart
            const heatData = data.heat_breakdown || [];
            const heatLabels = heatData.map(item => `Heat ${item.heat_number}`);
            const participantCounts = heatData.map(item => parseInt(item.participants));
            const scoreCounts = heatData.map(item => parseInt(item.scores));
            
            if (heatChart) heatChart.destroy();
            const heatCtx = document.getElementById('heatChart').getContext('2d');
            heatChart = new Chart(heatCtx, {
                type: 'bar',
                data: {
                    labels: heatLabels,
                    datasets: [{
                        label: 'Participants',
                        data: participantCounts,
                        backgroundColor: '#0d6efd',
                        borderColor: '#0a58ca',
                        borderWidth: 1
                    }, {
                        label: 'Scores',
                        data: scoreCounts,
                        backgroundColor: '#198754',
                        borderColor: '#146c43',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Judge Workload Chart (placeholder data)
            if (judgeWorkloadChart) judgeWorkloadChart.destroy();
            const judgeWorkloadCtx = document.getElementById('judgeWorkloadChart').getContext('2d');
            judgeWorkloadChart = new Chart(judgeWorkloadCtx, {
                type: 'bar',
                data: {
                    labels: ['Judge 1', 'Judge 2', 'Judge 3', 'Judge 4', 'Judge 5'],
                    datasets: [{
                        label: 'Scores Assigned',
                        data: [45, 52, 48, 61, 38],
                        backgroundColor: '#ffc107',
                        borderColor: '#ffb700',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    indexAxis: 'y',
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        function updateJudgePerformanceTable(judgeData) {
            const tbody = document.getElementById('judgePerformanceTableBody');
            tbody.innerHTML = '';
            
            judgeData.forEach((judge, index) => {
                const row = tbody.insertRow();
                const avgScore = judge.avg_score ? parseFloat(judge.avg_score).toFixed(1) : 'N/A';
                const totalScores = parseInt(judge.total_scores) || 0;
                const okScores = parseInt(judge.ok_scores) || 0;
                const exceptionScores = parseInt(judge.exception_scores) || 0;
                
                // Calculate performance indicator
                const okRate = totalScores > 0 ? (okScores / totalScores) * 100 : 0;
                let performanceClass = 'performance-poor';
                let performanceText = 'Poor';
                if (okRate >= 95) {
                    performanceClass = 'performance-excellent';
                    performanceText = 'Excellent';
                } else if (okRate >= 85) {
                    performanceClass = 'performance-good';
                    performanceText = 'Good';
                }
                
                // Calculate duration and rate
                let duration = 'N/A';
                let ratePerHour = '0.0';
                if (judge.first_score && judge.last_score) {
                    const diffMs = new Date(judge.last_score) - new Date(judge.first_score);
                    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
                    const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
                    duration = `${diffHours}h ${diffMinutes}m`;
                    
                    if (diffMs > 0) {
                        const totalHours = diffMs / (1000 * 60 * 60);
                        ratePerHour = (totalScores / totalHours).toFixed(1);
                    }
                }
                
                row.innerHTML = `
                    <td>
                        <div class="d-flex align-items-center">
                            <div class="me-2">
                                <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                    <span class="text-white fw-bold small">${judge.name ? judge.name.substring(0, 2).toUpperCase() : 'UN'}</span>
                                </div>
                            </div>
                            <div>
                                <div class="fw-medium small">${judge.name || 'Unknown'}</div>
                                <small class="text-muted">Judge #${index + 1}</small>
                            </div>
                        </div>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-primary">${totalScores}</span>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-success">${okScores}</span>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-warning">${exceptionScores}</span>
                    </td>
                    <td class="text-center">
                        <strong class="small">${avgScore}</strong>
                    </td>
                    <td class="text-center">
                        <div class="d-flex align-items-center justify-content-center">
                            <span class="badge bg-${performanceClass === 'performance-excellent' ? 'success' : performanceClass === 'performance-good' ? 'warning' : 'danger'} me-1" style="width: 8px; height: 8px; padding: 0; border-radius: 50%;"></span>
                            <span class="small">${performanceText}</span>
                        </div>
                    </td>
                    <td class="text-center">
                        <small>${duration}</small>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-info">${ratePerHour}/hr</span>
                    </td>
                `;
            });
            
            if (judgeData.length === 0) {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td colspan="8" class="text-center text-muted py-4">
                        <i class="fas fa-users fa-2x mb-2 d-block opacity-50"></i>
                        <span class="small">No judge performance data available</span>
                    </td>
                `;
            }
        }
        
        function updateHeatBreakdown(data) {
            const tbody = document.getElementById('heatBreakdownTableBody');
            tbody.innerHTML = '';
            
            const heatData = data.heat_breakdown || [];
            const totalJudges = parseInt(data.total_judges) || 0;
            const runsPerHeat = parseInt(data.event_info?.runs_per_heat) || 3;
            
            heatData.forEach(heat => {
                const row = tbody.insertRow();
                const participants = parseInt(heat.participants);
                const scores = parseInt(heat.scores);
                const expectedScores = participants * totalJudges * runsPerHeat;
                const completion = expectedScores > 0 ? Math.round((scores / expectedScores) * 100) : 0;
                
                let statusBadge = 'secondary';
                let statusText = 'Not Started';
                let statusClass = 'heat-status-pending';
                
                if (completion >= 100) {
                    statusBadge = 'success';
                    statusText = 'Complete';
                    statusClass = 'heat-status-complete';
                } else if (completion >= 50) {
                    statusBadge = 'warning';
                    statusText = 'In Progress';
                    statusClass = 'heat-status-progress';
                } else if (completion > 0) {
                    statusBadge = 'info';
                    statusText = 'Started';
                    statusClass = 'heat-status-started';
                }
                
                // Health indicator based on completion and participant count
                let healthIcon = 'fas fa-check-circle text-success';
                let healthText = 'Healthy';
                if (completion < 50 && participants > 0) {
                    healthIcon = 'fas fa-exclamation-triangle text-warning';
                    healthText = 'Attention';
                } else if (completion === 0 && participants > 0) {
                    healthIcon = 'fas fa-times-circle text-danger';
                    healthText = 'Critical';
                }
                
                row.innerHTML = `
                    <td>
                        <div class="fw-bold small">Heat ${heat.heat_number}</div>
                        <small class="text-muted">#${heat.heat_number}</small>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-primary">${participants}</span>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-success">${scores}</span>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-secondary">${expectedScores}</span>
                    </td>
                    <td class="text-center">
                        <div class="progress mb-1" style="height: 20px;">
                            <div class="progress-bar bg-${statusBadge}" style="width: ${completion}%">
                                ${completion}%
                            </div>
                        </div>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-${statusBadge}">${statusText}</span>
                    </td>
                    <td class="text-center">
                        <div class="d-flex align-items-center justify-content-center">
                            <i class="${healthIcon} me-1"></i>
                            <span class="small">${healthText}</span>
                        </div>
                    </td>
                `;
            });
            
            if (heatData.length === 0) {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td colspan="7" class="text-center text-muted py-4">
                        <i class="fas fa-fire fa-2x mb-2 d-block opacity-50"></i>
                        <span class="small">No heat breakdown data available</span>
                    </td>
                `;
            }
        }
        
        function exportData(format) {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = window.location.href;
            
            const fields = {
                'ajax': '1',
                'action': 'export_scores',
                'event_id': currentEventId,
                'format': format
            };
            
            for (const key in fields) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = fields[key];
                form.appendChild(input);
            }
            
            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
        
        function showLoadingState() {
            document.getElementById('emptyState').style.display = 'none';
            document.getElementById('loadingState').style.display = 'block';
            hideAllSections();
        }
        
        function hideLoadingState() {
            document.getElementById('loadingState').style.display = 'none';
        }
        
        function showEmptyState() {
            document.getElementById('emptyState').style.display = 'block';
            hideAllSections();
        }
        
        function showAllSections() {
            document.getElementById('emptyState').style.display = 'none';
            document.getElementById('statsRow').style.display = 'flex';
            document.getElementById('chartsRow').style.display = 'flex';
            document.getElementById('insightsRow').style.display = 'flex';
            document.getElementById('judgePerformanceCard').style.display = 'block';
            document.getElementById('heatBreakdownCard').style.display = 'block';
        }
        
        function hideAllSections() {
            document.getElementById('statsRow').style.display = 'none';
            document.getElementById('chartsRow').style.display = 'none';
            document.getElementById('insightsRow').style.display = 'none';
            document.getElementById('judgePerformanceCard').style.display = 'none';
            document.getElementById('heatBreakdownCard').style.display = 'none';
        }
    </script>

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