<?php
// Increase limits for complex page
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 300);

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

// Allow access for judges, head judges, and admins
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header("Location: ../login.php");
    exit;
}

// Check if user has appropriate role
$allowed_roles = ['judge', 'head_judge', 'admin'];
$user_type = $_SESSION['user_type'] ?? '';
$user_role = $_SESSION['role'] ?? '';

// Check if approval columns exist early for AJAX handling
$hasApprovalCols = false;
try {
    $pdo->query("SELECT is_approved, approved_by, approved_at FROM scores WHERE 1=0");
    $hasApprovalCols = true;
} catch (Exception $e) {
    $hasApprovalCols = false;
}

// Handle AJAX approval requests

if (!in_array($user_type, $allowed_roles) && !in_array($user_role, $allowed_roles)) {
    header("Location: ../login.php?error=unauthorized");
    exit;
}

// Get filter parameters
$selected_event = $_GET['event_id'] ?? null;
$filter_heat = $_GET['heat'] ?? null;
$filter_run = $_GET['run'] ?? null;
$filter_judge = $_GET['judge'] ?? null;
$filter_control_point = $_GET['control_point'] ?? null;
$filter_bib = $_GET['bib'] ?? null;
$filter_name = $_GET['name'] ?? null;

// Handle AJAX approval requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && 
    ($_POST['action'] === 'approve_score' || $_POST['action'] === 'unapprove_score' || $_POST['action'] === 'delete_score')) {
    header('Content-Type: application/json');
    
    $score_id = $_POST['score_id'] ?? null;
    $user_id = $_SESSION['user_id'] ?? null;
    $action = $_POST['action'];
    
    if (!$score_id || !$user_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required data']);
        exit;
    }
    
    try {
        if ($action === 'delete_score') {
            // Delete the score record
            $delete_stmt = $pdo->prepare("DELETE FROM scores WHERE id = ?");
            $delete_stmt->execute([$score_id]);
            
            if ($delete_stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true, 
                    'message' => 'Score deleted successfully'
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Score not found or already deleted']);
            }
        } elseif ($hasApprovalCols) {
            if ($action === 'approve_score') {
                $approve_stmt = $pdo->prepare("UPDATE scores SET is_approved = 1, approved_by = ?, approved_at = NOW() WHERE id = ?");
                $approve_stmt->execute([$user_id, $score_id]);
                $message = 'Score approved successfully';
                $approved_at = date('M j, H:i');
            } else {
                $approve_stmt = $pdo->prepare("UPDATE scores SET is_approved = 0, approved_by = NULL, approved_at = NULL WHERE id = ?");
                $approve_stmt->execute([$score_id]);
                $message = 'Score unapproved successfully';
                $approved_at = null;
            }
            
            echo json_encode([
                'success' => true, 
                'message' => $message,
                'approved_at' => $approved_at
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Approval columns not available']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle AJAX table refresh
if (isset($_GET['ajax_refresh']) && $_GET['ajax_refresh'] == '1') {
    // Return only the table HTML for AJAX refresh
    // This will be processed after the scores are fetched below
    $ajax_refresh_mode = true;
} else {
    $ajax_refresh_mode = false;
}

// Handle override form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['score_id'])) {
    $score_id = $_POST['score_id'];
    $new_score = $_POST['score_value'] !== '' ? floatval($_POST['score_value']) : null;
    $status = $_POST['status'];
    $new_figures_json = $_POST['figures_json'] ?? null;

    // Check if figures_json column exists
    $hasFiguresCol = false;
    try {
        $pdo->query("SELECT figures_json FROM scores WHERE 1=0");
        $hasFiguresCol = true;
    } catch (Exception $e) {
        $hasFiguresCol = false;
    }

    if ($hasFiguresCol) {
        $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, figures_json = ?, updated_at = NOW() WHERE id = ?");
        $update_stmt->execute([$new_score, $status, $new_figures_json ?: null, $score_id]);
    } else {
        $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ? WHERE id = ?");
        $update_stmt->execute([$new_score, $status, $score_id]);
    }
    
    $success_message = "Score updated successfully.";
}

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

// Build query with filters
$where_conditions = [];
$params = [];

if ($selected_event) {
    $where_conditions[] = "ep.event_id = ?";
    $params[] = $selected_event;
}

if ($filter_heat) {
    $where_conditions[] = "ep.heat_number = ?";
    $params[] = $filter_heat;
}

if ($filter_run) {
    $where_conditions[] = "r.run_number = ?";
    $params[] = $filter_run;
}

if ($filter_judge) {
    $where_conditions[] = "u.id = ?";
    $params[] = $filter_judge;
}

if ($filter_control_point) {
    $where_conditions[] = "ecp.id = ?";
    $params[] = $filter_control_point;
}

if ($filter_bib) {
    $where_conditions[] = "ep.bib_number = ?";
    $params[] = $filter_bib;
}

if ($filter_name) {
    $where_conditions[] = "(p.last_name LIKE ? OR p.first_name LIKE ? OR CONCAT(p.first_name, ' ', p.last_name) LIKE ? OR CONCAT(p.last_name, ' ', p.first_name) LIKE ?)";
    $name_param = '%' . $filter_name . '%';
    $params[] = $name_param;
    $params[] = $name_param;
    $params[] = $name_param;
    $params[] = $name_param;
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Check if figures_json column exists first
$hasFiguresCol = false;
try {
    $pdo->query("SELECT figures_json FROM scores WHERE 1=0");
    $hasFiguresCol = true;
} catch (Exception $e) {
    $hasFiguresCol = false;
}

// Check if control_point_id column exists
$hasControlPointCol = false;
try {
    $pdo->query("SELECT control_point_id FROM scores WHERE 1=0");
    $hasControlPointCol = true;
} catch (Exception $e) {
    $hasControlPointCol = false;
}

// Build query with conditional joins for control points
$figuresSelect = $hasFiguresCol ? ", s.figures_json" : "";
$controlPointJoin = $hasControlPointCol ? "LEFT JOIN event_control_points ecp ON s.control_point_id = ecp.id" : "";
$controlPointSelect = $hasControlPointCol ? ", ecp.id as control_point_id, ecp.description as control_point_name, ecp.weight as control_point_weight" : ", NULL as control_point_name, NULL as control_point_weight";
$approvalSelect = $hasApprovalCols ? ", s.is_approved, s.approved_by, s.approved_at" : ", NULL as is_approved, NULL as approved_by, NULL as approved_at";

// Fetch scores with filters
$scores_stmt = $pdo->prepare("
    SELECT s.id AS score_id, e.name AS event_name,
           p.first_name, p.last_name, ep.bib_number as bib,
           r.run_number, s.score_value, s.status, u.username AS judge_name,
           ep.heat_number, u.id as judge_id, e.id as event_id,
           s.created_at, s.updated_at
           $approvalSelect
           $figuresSelect
           $controlPointSelect
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    JOIN event_participants ep ON r.event_participant_id = ep.id
    JOIN participants p ON ep.participant_id = p.id
    JOIN events e ON ep.event_id = e.id
    JOIN users u ON s.judge_id = u.id
    $controlPointJoin
    $where_clause
    ORDER BY s.created_at DESC
    LIMIT 500
");
$scores_stmt->execute($params);
$scores = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get filter options based on selected event
$heats = [];
$runs = [];
$judges = [];
$control_points = [];

if ($selected_event) {
    // Get heats for selected event with names from event_heat_settings
    $heats_stmt = $pdo->prepare("
        SELECT DISTINCT ep.heat_number, ehs.heat_name
        FROM event_participants ep
        LEFT JOIN event_heat_settings ehs ON ep.event_id = ehs.event_id AND ep.heat_number = ehs.heat_number
        WHERE ep.event_id = ? 
        ORDER BY ep.heat_number
    ");
    $heats_stmt->execute([$selected_event]);
    $heats = $heats_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get runs for selected event
    $runs_stmt = $pdo->prepare("
        SELECT DISTINCT r.run_number 
        FROM runs r 
        JOIN event_participants ep ON r.event_participant_id = ep.id 
        WHERE ep.event_id = ? 
        ORDER BY r.run_number
    ");
    $runs_stmt->execute([$selected_event]);
    $runs = $runs_stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get judges for selected event
    $judges_stmt = $pdo->prepare("
        SELECT DISTINCT u.id, u.username as name 
        FROM users u 
        JOIN scores s ON u.id = s.judge_id 
        JOIN runs r ON s.run_id = r.id 
        JOIN event_participants ep ON r.event_participant_id = ep.id 
        WHERE ep.event_id = ? AND u.role = 'judge'
        ORDER BY u.username
    ");
    $judges_stmt->execute([$selected_event]);
    $judges = $judges_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get control points for selected event (if control points exist)
    if ($hasControlPointCol) {
        $cp_stmt = $pdo->prepare("
            SELECT DISTINCT ecp.id, ecp.description as name, ecp.weight
            FROM event_control_points ecp
            JOIN scores s ON s.control_point_id = ecp.id
            JOIN runs r ON s.run_id = r.id
            JOIN event_participants ep ON r.event_participant_id = ep.id
            WHERE ep.event_id = ? AND ecp.status = 1
            ORDER BY ecp.description
        ");
        $cp_stmt->execute([$selected_event]);
        $control_points = $cp_stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// If AJAX refresh mode, we'll skip to just the table section
if (!$ajax_refresh_mode) {
?>

<!DOCTYPE html>
<html>
<head>
    <title>Score Override Panel - <?= ucfirst($user_type ?: $user_role) ?> Access</title>
    <?php include_once '../includes/stylesheets.php'; ?>


<!-- style skin holder -->
    <style>
        .score-override-card {
            border-left: 4px solid #007bff;
        }
        .figure-chip {
            margin: 2px;
            font-size: 0.875rem;
        }
        .figure-chip.active {
            background-color: #007bff !important;
            color: white !important;
            border-color: #007bff !important;
        }
        .control-point-badge {
            background: linear-gradient(45deg, #6f42c1, #e83e8c);
            color: white;
            border: none;
        }
        
        .figures-display {
    /* background-color: #f8f9fa; */
    border-radius: 0.375rem;
    padding: 0.5rem;
    display: flex
;
}
        .figures-display {
            background-color: #f8f9fa;
            border-radius: 0.375rem;
            padding: 0.375rem;
            display: flex;
        }
        .table-responsive {
            border-radius: 0.375rem;
            overflow: hidden;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
        }
        .btn-group-sm .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        .approval-clickable {
            transition: all 0.2s ease;
        }
        .approval-clickable:hover {
            transform: scale(1.05);
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        /* Row selection styles */
        tr.selected {
            background-color: #e3f2fd !important;
        }
        tr.selected td {
            border-color: #2196F3 !important;
        }
        .row-checkbox {
            cursor: pointer;
            width: 18px;
            height: 18px;
        }
        #selectAll {
            cursor: pointer;
            width: 18px;
            height: 18px;
        }
        .bulk-actions-bar {
            position: sticky;
            top: 0;
            z-index: 100;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .selection-count {
            font-size: 1.1rem;
            font-weight: 600;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
<div class="container-fluid container-StyleScore p-4">
        <!-- event action menu. -->
<div class="row mb-2">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <div class="row mb-3">
                <div class="col-12 d-flex justify-content-between align-items-center">
                        <div>
                                <h4><i class="fas fa-gavel me-2"></i>Head Judge Override Panel</h4>
                                <p class="text-muted mb-0 small">Comprehensive score management with figure tracking and control point information</p>
                                
                        </div>
                        <div>
                            <?php if ($user_type !== 'head_judge' && $user_role !== 'head_judge'): ?>
                                        <div class="alert alert-warning mt-2" role="alert">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                <strong>Notice:</strong> You are accessing the override panel as a <?= htmlspecialchars($user_type ?: $user_role) ?>. 
                                                Score modifications should typically be performed by head judges.
                                        </div>
                                <?php endif; ?>
                        </div>
                        <div>
                                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#helpModal">
                                        <i class="fas fa-circle-question me-1"></i>Help
                                </button>
                        </div>
                </div>
        </div>

        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-circle-question me-2 text-info"></i>Head Judge Override — Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/head_judge_override_help.html" style="border:0;width:100%;height:100%;" title="Head Judge Override Help"></iframe>
                    </div>
                </div>
            </div>
        </div>
    
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success alert alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <!-- Filters Form -->
    <div class="border-0 shadow-none card mb-3 score-override-card">
        <div class="border-0 shadow-none card-header py-2">
            <h6 class="mb-0"><i class="fas fa-filter me-2"></i>Filters & Search</h6>
        </div>
        <div class="border-0 shadow-none card-body p-3">
            <form method="get" class="row g-2 load-event-selection">
                <div class="col-md-2">
                    <label for="event_id" class="form-label small">Event</label>
                    <select name="event_id" id="event_id" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">-- All Events --</option>
                        <?php foreach ($events as $event): ?>
                            <option value="<?= $event['id'] ?>" <?= $selected_event == $event['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($event['name']) ?> (<?= date('M d, Y', strtotime($event['date'])) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label for="heat" class="form-label small">Heat</label>
                    <select name="heat" id="heat" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">-- All Heats --</option>
                        <?php foreach ($heats as $heat): ?>
                            <option value="<?= $heat['heat_number'] ?>" <?= $filter_heat == $heat['heat_number'] ? 'selected' : '' ?>>
                                Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-1">
                    <label for="run" class="form-label small">Run</label>
                    <select name="run" id="run" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">-- All Runs --</option>
                        <?php foreach ($runs as $run): ?>
                            <option value="<?= $run ?>" <?= $filter_run == $run ? 'selected' : '' ?>>
                                Run <?= $run ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-1">
                    <label for="judge" class="form-label small">Judge</label>
                    <select name="judge" id="judge" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">-- All Judges --</option>
                        <?php foreach ($judges as $judge): ?>
                            <option value="<?= $judge['id'] ?>" <?= $filter_judge == $judge['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($judge['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <?php if ($hasControlPointCol && !empty($control_points)): ?>
                <div class="col-md-2">
                    <label for="control_point" class="form-label small">Control Point</label>
                    <select name="control_point" id="control_point" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">-- All Control Points --</option>
                        <?php foreach ($control_points as $cp): ?>
                            <option value="<?= $cp['id'] ?>" <?= $filter_control_point == $cp['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cp['name']) ?> (×<?= $cp['weight'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                
                <div class="col-md-2">
                    <label for="bib" class="form-label small"><i class="fas fa-hashtag me-1"></i>BIB Number</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                        <input type="text" name="bib" id="bib" class="form-control" 
                               value="<?= htmlspecialchars($filter_bib ?? '') ?>" 
                               placeholder="Enter BIB..."
                               onkeypress="if(event.key === 'Enter') this.form.submit()">
                    </div>
                </div>
                
                <div class="col-md-2">
                    <label for="name" class="form-label small"><i class="fas fa-user me-1"></i>Participant Name</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="name" id="name" class="form-control" 
                               value="<?= htmlspecialchars($filter_name ?? '') ?>" 
                               placeholder="Search by name..."
                               onkeypress="if(event.key === 'Enter') this.form.submit()">
                        <?php if ($filter_name): ?>
                        <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('name').value=''; this.form.submit()">
                            <i class="fas fa-times"></i>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="col-md-auto d-flex align-items-end gap-1">
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fas fa-search me-1"></i>Search
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearFilters()">
                        <i class="fas fa-eraser me-1"></i>Clear
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Results Summary -->
    <div class="row mb-2">
        <div class="col">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="text-muted mb-1">
                        <i class="fas fa-chart-bar me-1"></i>
                        <span id="scoresCount">Showing <?= count($scores) ?> score<?= count($scores) != 1 ? 's' : '' ?></span>
                        <?php if ($selected_event): ?>
                            for <?= htmlspecialchars($events[array_search($selected_event, array_column($events, 'id'))]['name'] ?? 'Selected Event') ?>
                        <?php endif; ?>
                    </h6>
                    <div class="text-muted small">
                        <?php if ($filter_heat): ?>
                            <span class="badge bg-info me-1">Heat <?= $filter_heat ?></span>
                        <?php endif; ?>
                        <?php if ($filter_run): ?>
                            <span class="badge bg-info me-1">Run <?= $filter_run ?></span>
                        <?php endif; ?>
                        <?php if ($filter_judge): ?>
                            <span class="badge bg-success me-1">Judge: <?= htmlspecialchars($judges[array_search($filter_judge, array_column($judges, 'id'))]['name'] ?? 'Selected Judge') ?></span>
                        <?php endif; ?>
                        <?php if ($filter_control_point): ?>
                            <span class="badge control-point-badge me-1">
                                CP: <?= htmlspecialchars($control_points[array_search($filter_control_point, array_column($control_points, 'id'))]['name'] ?? 'Selected Control Point') ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <!-- Auto-refresh Controls -->
                    <div class="d-flex align-items-center gap-2">
                        <label class="small text-muted mb-0">Auto-refresh:</label>
                        <select id="refreshInterval" class="form-select form-select-sm" style="width: auto;" onchange="handleRefreshIntervalChange()">
                            <option value="0">Off</option>
                            <option value="5">5s</option>
                            <option value="10" selected>10s</option>
                            <option value="30">30s</option>
                            <option value="60">60s</option>
                        </select>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshScoresTable()" title="Refresh now">
                            <i class="fas fa-sync" id="refreshIcon"></i>
                        </button>
                        <small class="text-muted" id="lastRefreshTime">Never</small>
                    </div>
                    <div class="vr"></div>
                    <?php if ($hasFiguresCol): ?>
                        <span class="badge bg-secondary"><i class="fas fa-list-check me-1"></i>Figures Supported</span>
                    <?php endif; ?>
                    <?php if ($hasControlPointCol): ?>
                        <span class="badge control-point-badge"><i class="fas fa-crosshairs me-1"></i>Control Points</span>
                    <?php endif; ?>
                    <span class="badge bg-<?= $user_type === 'head_judge' || $user_role === 'head_judge' ? 'success' : ($user_type === 'admin' || $user_role === 'admin' ? 'warning' : 'info') ?>">
                        <i class="fas fa-user me-1"></i><?= ucfirst($user_type ?: $user_role) ?> Access
                    </span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bulk Actions Bar (hidden by default) -->
    <div class="bulk-actions-bar mb-3 p-3 d-none" id="bulkActionsBar">
        <div class="d-flex justify-content-between align-items-center text-white">
            <div class="selection-count">
                <i class="fas fa-check-square me-2"></i>
                <span id="selectedCount">0</span> score(s) selected
            </div>
            <div class="btn-group">
                <button type="button" class="btn btn-light btn-sm" onclick="clearSelection()">
                    <i class="fas fa-times me-1"></i>Clear Selection
                </button>
                <button type="button" class="btn btn-danger btn-sm" onclick="bulkDeleteScores()">
                    <i class="fas fa-trash me-1"></i>Delete Selected
                </button>
            </div>
        </div>
    </div>
    
    <!-- Scores Table -->
    <div class="table-responsive">
        <table class="table table-bordered table-hover table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th style="width: 40px;">
                        <input type="checkbox" id="selectAll" class="form-check-input" title="Select All">
                    </th>
                    <th><i class="fas fa-trophy me-1"></i>Event</th>
                    <th><i class="fas fa-user me-1"></i>Participant</th>
                    <th><i class="fas fa-fire me-1"></i>Heat</th>
                    <th><i class="fas fa-running me-1"></i>Run</th>
                    <th><i class="fas fa-user-tie me-1"></i>Judge</th>
                    <?php if ($hasControlPointCol): ?>
                        <th><i class="fas fa-crosshairs me-1"></i>Control Point</th>
                    <?php endif; ?>
                    <th><i class="fas fa-star me-1"></i>Score</th>
                    <th><i class="fas fa-flag me-1"></i>Status</th>
                    <th><i class="fas fa-calendar me-1"></i>Created</th>
                    <?php if ($hasApprovalCols): ?>
                        <th><i class="fas fa-check-circle me-1"></i>Approval</th>
                    <?php endif; ?>
                    <?php if ($hasFiguresCol): ?>
                        <th><i class="fas fa-list-check me-1"></i>Figures</th>
                    <?php endif; ?>
                    <th><i class="fas fa-edit me-1"></i>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($scores)): ?>
                    <tr>
                        <td colspan="<?= 9 + ($hasControlPointCol ? 1 : 0) + ($hasApprovalCols ? 1 : 0) + ($hasFiguresCol ? 1 : 0) ?>" class="text-center text-muted py-4">
                            <i class="fas fa-search fa-2x mb-2 opacity-50"></i><br>
                            <?= $selected_event ? 'No scores found for the selected filters.' : 'Please select an event to view scores.' ?>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($scores as $score): ?>
                    <tr data-score-id="<?= $score['score_id'] ?>">
                        <td class="text-center">
                            <input type="checkbox" class="form-check-input row-checkbox" 
                                   data-score-id="<?= $score['score_id'] ?>"
                                   data-score-data='<?= htmlspecialchars(json_encode($score), ENT_QUOTES) ?>'>
                        </td>
                        <td>
                            <strong class="text-primary"><?= htmlspecialchars($score['event_name']) ?></strong>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-primary me-2"><?= htmlspecialchars($score['bib']) ?></span>
                                <div>
                                    <strong><?= htmlspecialchars($score['first_name']) ?> <?= htmlspecialchars($score['last_name']) ?></strong>
                                </div>
                            </div>
                        </td>
                        <td><span class="badge bg-info">Heat <?= htmlspecialchars($score['heat_number']) ?></span></td>
                        <td><span class="badge bg-success">Run <?= $score['run_number'] ?></span></td>
                        <td><?= htmlspecialchars($score['judge_name']) ?></td>
                        <?php if ($hasControlPointCol): ?>
                            <td>
                                <?php if ($score['control_point_name']): ?>
                                    <span class="badge control-point-badge">
                                        <?= htmlspecialchars($score['control_point_name']) ?>
                                        <?php if ($score['control_point_weight'] != 1.00): ?>
                                            <small>(×<?= $score['control_point_weight'] ?>)</small>
                                        <?php endif; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        <?php endif; ?>
                        <td>
                            <span class="fs-5 fw-bold text-primary"><?= $score['score_value'] ?></span>
                        </td>
                        <td>
                            <span class="badge bg-<?= $score['status'] == 'OK' ? 'success' : 'warning' ?>">
                                <?= $score['status'] ?>
                            </span>
                        </td>
                        <td>
                            <div class="small">
                                <div class="text-muted">
                                    <i class="fas fa-plus-circle me-1"></i>
                                    <?= date('M j, Y', strtotime($score['created_at'])) ?>
                                </div>
                                <div class="text-muted" style="font-size: 0.7rem;">
                                    <?= date('H:i', strtotime($score['created_at'])) ?>
                                </div>
                                <?php if ($score['updated_at'] && $score['updated_at'] !== $score['created_at']): ?>
                                    <div class="text-warning" style="font-size: 0.7rem;">
                                        <i class="fas fa-edit me-1"></i>Updated: <?= date('M j, H:i', strtotime($score['updated_at'])) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </td>
                        <?php if ($hasApprovalCols): ?>
                        <td>
                            <?php if ($hasApprovalCols && isset($score['is_approved'])): ?>
                                <?php
                                if ($score['is_approved'] === '1' || $score['is_approved'] === 1 || $score['is_approved'] === true) {
                                    $approvalBadgeClass = 'bg-success';
                                    $approvalIcon = 'fas fa-check-circle';
                                    $approvalText = 'Approved';
                                    $clickAction = 'unapproveScore';
                                    $clickTitle = 'Click to unapprove';
                                } elseif ($score['is_approved'] === '0' || $score['is_approved'] === 0 || $score['is_approved'] === false) {
                                    $approvalBadgeClass = 'bg-danger';
                                    $approvalIcon = 'fas fa-times-circle';
                                    $approvalText = 'Not Approved';
                                    $clickAction = 'approveScore';
                                    $clickTitle = 'Click to approve';
                                } else {
                                    $approvalBadgeClass = 'bg-warning';
                                    $approvalIcon = 'fas fa-clock';
                                    $approvalText = 'Pending';
                                    $clickAction = 'approveScore';
                                    $clickTitle = 'Click to approve';
                                }
                                ?>
                                <span class="badge <?= $approvalBadgeClass ?> approval-clickable" 
                                      onclick="<?= $clickAction ?>(<?= $score['score_id'] ?>, this)" 
                                      style="cursor: pointer;" 
                                      title="<?= $clickTitle ?>">
                                    <i class="<?= $approvalIcon ?> me-1"></i><?= $approvalText ?>
                                </span>
                                <?php if ($score['approved_at']): ?>
                                    <div class="text-muted small mt-1">
                                        <?= date('M j, H:i', strtotime($score['approved_at'])) ?>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                        <?php if ($hasFiguresCol): ?>
                            <td>
                                <?php if (!empty($score['figures_json'])): ?>
                                    <?php
                                    $figuresData = json_decode($score['figures_json'], true);
                                    if ($figuresData && is_array($figuresData) && json_last_error() === JSON_ERROR_NONE):
                                        // Handle both new format (with "figures" wrapper) and old format (direct categories)
                                        $figures = isset($figuresData['figures']) ? $figuresData['figures'] : $figuresData;
                                        
                                        if ($figures && is_array($figures)):
                                    ?>
                                        <div class="figures-display">
                                            <?php foreach ($figures as $category => $items): ?>
                                                <?php if (is_array($items) && !empty($items)): ?>
                                                    <div class="mb-1">
                                                        <small class="badge bg-light text-dark me-1 mb-1"><?= htmlspecialchars($category) ?>:</small>
                                                        <br>
                                                        <?php foreach ($items as $item): ?>
                                                            <?php if (!empty(trim($item))): ?>
                                                                <span class="fw-bold text-primary"><?= htmlspecialchars($item) ?></span>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-muted">No figures</span>
                                    <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">Invalid JSON</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        <?php endif; ?>
                        <td>
                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                    data-score-id="<?= $score['score_id'] ?>"
                                    data-participant-name="<?= htmlspecialchars($score['first_name'] . ' ' . $score['last_name']) ?>"
                                    data-bib="<?= $score['bib'] ?>"
                                    data-run="<?= $score['run_number'] ?>"
                                    data-score="<?= $score['score_value'] ?>"
                                    data-status="<?= $score['status'] ?>"
                                    <?php if ($hasFiguresCol): ?>
                                        data-figures='<?= htmlspecialchars($score['figures_json'] ?? '') ?>'
                                    <?php endif; ?>
                                    onclick="editScoreFromButton(this)">
                                <i class="fas fa-edit me-1"></i>Edit
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Debug: Table section complete -->

<!-- Edit Score Modal -->
<div class="modal fade" id="editScoreModal" tabindex="-1" aria-labelledby="editScoreModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white py-2">
                <h6 class="modal-title" id="editScoreModalLabel">
                    <i class="fas fa-edit me-2"></i>Edit Score
                </h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="editScoreForm">
                <div class="modal-body p-3">
                    <input type="hidden" name="score_id" id="edit_score_id">
                    <?php if ($hasFiguresCol): ?>
                        <input type="hidden" name="figures_json" id="edit_figures_json">
                    <?php endif; ?>
                    
                    <!-- Participant Info -->
                    <div class="alert alert-info mb-3">
                        <i class="fas fa-user me-2"></i>
                        <strong id="editParticipantInfo">Participant information will appear here</strong>
                    </div>
                    
                    <?php if ($user_type !== 'head_judge' && $user_role !== 'head_judge'): ?>
                    <div class="alert alert-warning mb-3">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <small><strong>Role Notice:</strong> You are modifying scores as a <?= htmlspecialchars($user_type ?: $user_role) ?>. 
                        Changes will be logged with your user ID.</small>
                    </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label for="edit_score_value" class="form-label">
                                <i class="fas fa-star me-1"></i>Score Value
                            </label>
                            <input type="number" class="form-control form-control-sm" name="score_value" id="edit_score_value" 
                                   min="0" max="99" step="1" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_status" class="form-label">
                                <i class="fas fa-flag me-1"></i>Status
                            </label>
                            <select name="status" id="edit_status" class="form-select form-select-sm" required>
                                <option value="OK">OK</option>
                                <option value="DNS">DNS (Did Not Start)</option>
                                <option value="DNF">DNF (Did Not Finish)</option>
                                <option value="DSQ">DSQ (Disqualified)</option>
                            </select>
                        </div>
                    </div>
                    
                    <?php if ($hasFiguresCol): ?>
                    <!-- Figures Section -->
                    <div class="mt-3" id="figuresSection" style="display: none;">
                        <h6><i class="fas fa-list-check me-2"></i>Figures</h6>
                        <div class="border rounded p-2 bg-light">
                            <div id="figureCategories">
                                <div class="text-center text-muted py-2">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading figure options...
                                </div>
                            </div>
                        </div>
                        
                        <!-- Current Figures Display -->
                        <div class="mt-2" id="currentFiguresDisplay" style="display: none;">
                            <h6 class="text-muted">Current Selection:</h6>
                            <div id="currentFiguresContent" class="figures-display">
                                <span class="text-muted">No figures selected</span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer py-2">
                    <div class="me-auto">
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteScore()">
                            <i class="fas fa-trash me-1"></i>Delete Score
                        </button>
                    </div>
                    <div>
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-save me-1"></i>Update Score
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
// Global variables
let FIGURE_DATA = { available: false, categories: [], itemsByCategory: {} };
let currentEditingEvent = null;
let figureClearHandlers = {};
let selectedScores = new Set();
let deletedScoresData = [];

// Row selection functions
document.addEventListener('DOMContentLoaded', function() {
    // Select all checkbox
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.row-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = this.checked;
                toggleRowSelection(cb);
            });
            updateSelectionUI();
        });
    }
    
    // Individual row checkboxes
    document.querySelectorAll('.row-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            toggleRowSelection(this);
            updateSelectionUI();
            
            // Update select all checkbox
            const allCheckboxes = document.querySelectorAll('.row-checkbox');
            const checkedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
            const selectAllCb = document.getElementById('selectAll');
            if (selectAllCb) {
                selectAllCb.checked = allCheckboxes.length === checkedCheckboxes.length && allCheckboxes.length > 0;
                selectAllCb.indeterminate = checkedCheckboxes.length > 0 && checkedCheckboxes.length < allCheckboxes.length;
            }
        });
    });
});

function toggleRowSelection(checkbox) {
    const scoreId = checkbox.dataset.scoreId;
    const row = checkbox.closest('tr');
    
    if (checkbox.checked) {
        selectedScores.add(scoreId);
        row.classList.add('selected');
    } else {
        selectedScores.delete(scoreId);
        row.classList.remove('selected');
    }
}

function updateSelectionUI() {
    const count = selectedScores.size;
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    const selectedCountSpan = document.getElementById('selectedCount');
    
    if (count > 0) {
        bulkActionsBar.classList.remove('d-none');
        selectedCountSpan.textContent = count;
    } else {
        bulkActionsBar.classList.add('d-none');
    }
}

function clearSelection() {
    selectedScores.clear();
    document.querySelectorAll('.row-checkbox').forEach(cb => {
        cb.checked = false;
        const row = cb.closest('tr');
        row.classList.remove('selected');
    });
    const selectAllCb = document.getElementById('selectAll');
    if (selectAllCb) {
        selectAllCb.checked = false;
        selectAllCb.indeterminate = false;
    }
    updateSelectionUI();
}

function bulkDeleteScores() {
    if (selectedScores.size === 0) {
        showNotification('No scores selected', 'warning');
        return;
    }
    
    const count = selectedScores.size;
    const confirmMsg = `Are you sure you want to delete ${count} score${count > 1 ? 's' : ''}?\n\nThis will:\n1. Delete the selected scores from the database\n2. Generate a JSON backup file with the deleted data\n3. Automatically download the backup file\n\nThis action cannot be undone!`;
    
    if (!confirm(confirmMsg)) {
        return;
    }
    
    // Collect score data for JSON export
    deletedScoresData = [];
    const scoreIds = Array.from(selectedScores);
    
    scoreIds.forEach(scoreId => {
        const checkbox = document.querySelector(`.row-checkbox[data-score-id="${scoreId}"]`);
        if (checkbox && checkbox.dataset.scoreData) {
            try {
                const scoreData = JSON.parse(checkbox.dataset.scoreData);
                deletedScoresData.push(scoreData);
            } catch (e) {
                console.error('Error parsing score data:', e);
            }
        }
    });
    
    // Show loading state
    const bulkActionsBar = document.getElementById('bulkActionsBar');
    const originalContent = bulkActionsBar.innerHTML;
    bulkActionsBar.innerHTML = `
        <div class="text-center text-white py-2">
            <i class="fas fa-spinner fa-spin me-2"></i>Deleting ${count} score${count > 1 ? 's' : ''}...
        </div>
    `;
    
    // Delete scores one by one
    let deletedCount = 0;
    let failedCount = 0;
    const promises = [];
    
    scoreIds.forEach(scoreId => {
        const formData = new FormData();
        formData.append('action', 'delete_score');
        formData.append('score_id', scoreId);
        
        const promise = fetch(window.location.href, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                deletedCount++;
            } else {
                failedCount++;
                console.error('Failed to delete score:', scoreId, data.message);
            }
        })
        .catch(error => {
            failedCount++;
            console.error('Error deleting score:', scoreId, error);
        });
        
        promises.push(promise);
    });
    
    // Wait for all deletions to complete
    Promise.all(promises).then(() => {
        // Generate and download JSON backup
        if (deletedScoresData.length > 0) {
            downloadDeletedScoresJSON();
        }
        
        // Show results
        let message = `Deleted ${deletedCount} score${deletedCount !== 1 ? 's' : ''} successfully`;
        if (failedCount > 0) {
            message += ` (${failedCount} failed)`;
        }
        if (deletedScoresData.length > 0) {
            message += '\n\nBackup JSON file has been downloaded.';
        }
        
        showNotification(message, failedCount > 0 ? 'warning' : 'success');
        
        // Refresh page after short delay
        setTimeout(() => {
            window.location.reload();
        }, 2000);
    });
}

function downloadDeletedScoresJSON() {
    const exportData = {
        export_info: {
            timestamp: new Date().toISOString(),
            deleted_by: '<?= $_SESSION['username'] ?? 'Unknown' ?>',
            user_id: '<?= $_SESSION['user_id'] ?? 'Unknown' ?>',
            total_records: deletedScoresData.length,
            event_filter: '<?= $selected_event ?? 'All Events' ?>',
            heat_filter: '<?= $filter_heat ?? 'All Heats' ?>',
            run_filter: '<?= $filter_run ?? 'All Runs' ?>'
        },
        deleted_scores: deletedScoresData
    };
    
    const jsonString = JSON.stringify(exportData, null, 2);
    const blob = new Blob([jsonString], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
    const filename = `deleted_scores_backup_${timestamp}.json`;
    
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

function clearFilters() {
    window.location.href = window.location.pathname;
}

function approveScore(scoreId, badgeElement) {
    if (!confirm('Are you sure you want to approve this score?')) {
        return;
    }
    
    updateApprovalStatus(scoreId, badgeElement, 'approve', 'Approving...');
}

function unapproveScore(scoreId, badgeElement) {
    if (!confirm('Are you sure you want to unapprove this score?')) {
        return;
    }
    
    updateApprovalStatus(scoreId, badgeElement, 'unapprove', 'Unapproving...');
}

function updateApprovalStatus(scoreId, badgeElement, action, loadingText) {
    // Show loading state
    const originalContent = badgeElement.innerHTML;
    badgeElement.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>' + loadingText;
    badgeElement.style.pointerEvents = 'none';
    
    // Send AJAX request
    const formData = new FormData();
    formData.append('action', action + '_score');
    formData.append('score_id', scoreId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update badge based on new status
            if (action === 'approve') {
                badgeElement.className = 'badge bg-success approval-clickable';
                badgeElement.innerHTML = '<i class="fas fa-check-circle me-1"></i>Approved';
                badgeElement.onclick = () => unapproveScore(scoreId, badgeElement);
                badgeElement.title = 'Click to unapprove';
                
                // Add approval date
                const parentCell = badgeElement.parentElement;
                let dateDiv = parentCell.querySelector('.approval-date');
                if (!dateDiv) {
                    dateDiv = document.createElement('div');
                    dateDiv.className = 'text-muted small mt-1 approval-date';
                    parentCell.appendChild(dateDiv);
                }
                dateDiv.textContent = data.approved_at || 'Just now';
            } else {
                badgeElement.className = 'badge bg-danger approval-clickable';
                badgeElement.innerHTML = '<i class="fas fa-times-circle me-1"></i>Not Approved';
                badgeElement.onclick = () => approveScore(scoreId, badgeElement);
                badgeElement.title = 'Click to approve';
                
                // Remove approval date
                const parentCell = badgeElement.parentElement;
                const dateDiv = parentCell.querySelector('.approval-date');
                if (dateDiv) {
                    dateDiv.remove();
                }
            }
            
            badgeElement.style.cursor = 'pointer';
            badgeElement.style.pointerEvents = 'auto';
            
            // Show success message
            const successText = action === 'approve' ? 'approved' : 'unapproved';
            showNotification(`Score ${successText} successfully!`, 'success');
        } else {
            // Restore original state on error
            badgeElement.innerHTML = originalContent;
            badgeElement.style.pointerEvents = 'auto';
            showNotification('Error: ' + (data.message || `Failed to ${action} score`), 'error');
        }
    })
    .catch(error => {
        // Restore original state on error
        badgeElement.innerHTML = originalContent;
        badgeElement.style.pointerEvents = 'auto';
        showNotification('Network error: ' + error.message, 'error');
    });
}

function showNotification(message, type) {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

function deleteScore() {
    const scoreId = document.getElementById('edit_score_id').value;
    const participantInfo = document.getElementById('editParticipantInfo').textContent;
    
    if (!scoreId) {
        showNotification('No score ID found', 'error');
        return;
    }
    
    // Show confirmation dialog
    if (!confirm(`Are you sure you want to delete this score?\n\n${participantInfo}\n\nThis action cannot be undone.`)) {
        return;
    }
    
    // Show loading state
    const deleteBtn = document.querySelector('#editScoreModal .btn-danger');
    const originalText = deleteBtn.innerHTML;
    deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Deleting...';
    deleteBtn.disabled = true;
    
    // Send delete request
    const formData = new FormData();
    formData.append('action', 'delete_score');
    formData.append('score_id', scoreId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('editScoreModal'));
            modal.hide();
            
            // Show success notification
            showNotification('Score deleted successfully! Refreshing page...', 'success');
            
            // Refresh page after short delay
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            // Restore button state
            deleteBtn.innerHTML = originalText;
            deleteBtn.disabled = false;
            showNotification('Error: ' + (data.message || 'Failed to delete score'), 'error');
        }
    })
    .catch(error => {
        // Restore button state
        deleteBtn.innerHTML = originalText;
        deleteBtn.disabled = false;
        showNotification('Network error: ' + error.message, 'error');
    });
}

function editScoreFromButton(button) {
    const scoreId = button.dataset.scoreId;
    const participantName = button.dataset.participantName;
    const bib = button.dataset.bib;
    const runNumber = button.dataset.run;
    const scoreValue = button.dataset.score;
    const status = button.dataset.status;
    const figuresJson = button.dataset.figures || '';
    
    editScore(scoreId, participantName, bib, runNumber, scoreValue, status, figuresJson);
}

function editScore(scoreId, participantName, bib, runNumber, scoreValue, status, figuresJson = '') {
    // Set basic form values
    document.getElementById('edit_score_id').value = scoreId;
    document.getElementById('edit_score_value').value = scoreValue;
    document.getElementById('edit_status').value = status;
    
    // Set participant info
    document.getElementById('editParticipantInfo').textContent = 
        `${participantName} (Bib ${bib}) - Run ${runNumber}`;
    
    <?php if ($hasFiguresCol): ?>
    // Handle figures if column exists
    if (figuresJson) {
        document.getElementById('edit_figures_json').value = figuresJson;
        setupFigureEditor(figuresJson);
    } else {
        document.getElementById('edit_figures_json').value = '';
        setupFigureEditor('');
    }
    <?php endif; ?>
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('editScoreModal'));
    modal.show();
    
    // Focus on score input
    modal._element.addEventListener('shown.bs.modal', function() {
        document.getElementById('edit_score_value').focus();
        document.getElementById('edit_score_value').select();
    }, { once: true });
}

<?php if ($hasFiguresCol): ?>
function setupFigureEditor(existingFiguresJson) {
    const figuresSection = document.getElementById('figuresSection');
    const currentDisplay = document.getElementById('currentFiguresDisplay');
    
    // Always show figures section for potential editing
    figuresSection.style.display = 'block';
    currentDisplay.style.display = 'block';
    
    // Load figure options for the current event
    const eventId = <?= json_encode($selected_event) ?>;
    if (eventId) {
        loadFigureOptions(eventId, existingFiguresJson);
    } else {
        document.getElementById('figureCategories').innerHTML = 
            '<div class="alert alert-warning">Please select an event to enable figure editing</div>';
    }
}

function loadFigureOptions(eventId, existingFiguresJson) {
    currentEditingEvent = eventId;
    
    const formData = new FormData();
    formData.append('action', 'get_format_figures');
    formData.append('event_id', eventId);
    
    fetch('../judge/head_judge.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.has_figures && data.figures) {
                FIGURE_DATA = {
                    available: true,
                    categories: Object.keys(data.figures),
                    itemsByCategory: data.figures
                };
                buildFigureEditor(existingFiguresJson);
            } else {
                document.getElementById('figureCategories').innerHTML = 
                    '<div class="alert alert-info">No figure options configured for this event</div>';
                FIGURE_DATA.available = false;
            }
        })
        .catch(error => {
            console.error('Error loading figures:', error);
            document.getElementById('figureCategories').innerHTML = 
                '<div class="alert alert-danger">Error loading figure options</div>';
        });
}

function buildFigureEditor(existingFiguresJson) {
    const container = document.getElementById('figureCategories');
    let existingFigures = {};
    
    // Parse existing figures and handle both formats
    if (existingFiguresJson) {
        try {
            const figuresData = JSON.parse(existingFiguresJson);
            // Handle both new format (with "figures" wrapper) and old format (direct categories)
            existingFigures = figuresData.figures || figuresData;
        } catch (e) {
            console.warn('Could not parse existing figures:', e);
            existingFigures = {};
        }
    }
    
    let html = '';
    
    FIGURE_DATA.categories.forEach(category => {
        const items = FIGURE_DATA.itemsByCategory[category] || [];
        if (items.length === 0) return;
        
        html += `
            <div class="figure-category mb-2">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="mb-0 text-primary">
                        <i class="fas fa-tag me-2"></i>${category}
                    </h6>
                    <button type="button" class="btn btn-sm btn-outline-secondary" 
                            onclick="clearFigureCategory('${category}')">
                        <i class="fas fa-times"></i> Clear
                    </button>
                </div>
                <div class="figure-chips d-flex flex-wrap gap-1">
        `;
        
        items.forEach(item => {
            const isSelected = existingFigures[category] && 
                              Array.isArray(existingFigures[category]) && 
                              existingFigures[category].includes(item.name);
            const activeClass = isSelected ? 'active' : '';
            
            html += `
                <button type="button" 
                        class="btn btn-sm btn-outline-primary figure-chip ${activeClass}" 
                        data-category="${category}" 
                        data-item="${item.name}"
                        onclick="toggleFigureChip(this)">
                    ${item.name}
                </button>
            `;
        });
        
        html += `
                </div>
            </div>
        `;
    });
    
    if (html) {
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="alert alert-info">No figure categories available</div>';
    }
    
    // Update current figures display
    updateCurrentFiguresDisplay();
}

function toggleFigureChip(button) {
    button.classList.toggle('active');
    updateFiguresJson();
    updateCurrentFiguresDisplay();
}

function clearFigureCategory(category) {
    const chips = document.querySelectorAll(`[data-category="${category}"]`);
    chips.forEach(chip => chip.classList.remove('active'));
    updateFiguresJson();
    updateCurrentFiguresDisplay();
}

function updateFiguresJson() {
    const figuresData = {};
    const activeChips = document.querySelectorAll('.figure-chip.active');
    
    activeChips.forEach(chip => {
        const category = chip.dataset.category;
        const item = chip.dataset.item;
        
        if (!figuresData[category]) {
            figuresData[category] = [];
        }
        figuresData[category].push(item);
    });
    
    // Only include categories with items
    const cleanedFigures = {};
    Object.keys(figuresData).forEach(category => {
        if (figuresData[category].length > 0) {
            cleanedFigures[category] = figuresData[category];
        }
    });
    
    // Save in new format with figures wrapper and validation data
    const finalData = {
        figures: cleanedFigures,
        validation: {
            diversity_valid: true,
            validation_timestamp: Date.now(),
            run_number: "manual_edit",
            client_validated: true,
            diversity_rules_checked: 0
        }
    };
    
    document.getElementById('edit_figures_json').value = 
        Object.keys(cleanedFigures).length > 0 ? JSON.stringify(finalData) : '';
}

function updateCurrentFiguresDisplay() {
    const content = document.getElementById('currentFiguresContent');
    const activeChips = document.querySelectorAll('.figure-chip.active');
    
    if (activeChips.length === 0) {
        content.innerHTML = '<span class="text-muted">No figures selected</span>';
        return;
    }
    
    const figuresByCategory = {};
    activeChips.forEach(chip => {
        const category = chip.dataset.category;
        const item = chip.dataset.item;
        
        if (!figuresByCategory[category]) {
            figuresByCategory[category] = [];
        }
        figuresByCategory[category].push(item);
    });
    
    let html = '';
    Object.keys(figuresByCategory).forEach(category => {
        html += `
            <div class="mb-1">
                <small class="fw-bold text-primary">${category}:</small><br>
                ${figuresByCategory[category].map(item => 
                    `<span class="badge bg-light text-dark me-1 mb-1">${item}</span>`
                ).join('')}
            </div>
        `;
    });
    
    content.innerHTML = html;
}
<?php endif; ?>

// Auto-refresh functionality
let refreshIntervalId = null;
let lastRefreshTimestamp = null;

function handleRefreshIntervalChange() {
    const intervalSelect = document.getElementById('refreshInterval');
    const seconds = parseInt(intervalSelect.value);
    
    // Clear existing interval
    if (refreshIntervalId) {
        clearInterval(refreshIntervalId);
        refreshIntervalId = null;
    }
    
    // Set up new interval if not "Off"
    if (seconds > 0) {
        refreshIntervalId = setInterval(() => {
            console.log('⏰ Auto-refresh timer fired (interval: ' + seconds + 's)');
            refreshScoresTable();
        }, seconds * 1000);
        
        console.log(`✅ Auto-refresh ENABLED: every ${seconds} seconds`);
        
        // Visual feedback
        const timeElement = document.getElementById('lastRefreshTime');
        if (timeElement) {
            timeElement.style.color = '#28a745';
            timeElement.title = 'Auto-refresh is active';
        }
    } else {
        console.log('⛔ Auto-refresh DISABLED');
        
        // Visual feedback
        const timeElement = document.getElementById('lastRefreshTime');
        if (timeElement) {
            timeElement.style.color = '#6c757d';
            timeElement.title = 'Auto-refresh is off';
        }
    }
}

function refreshScoresTable() {
    const refreshIcon = document.getElementById('refreshIcon');
    
    // Find ALL tables on the page
    const allTables = document.querySelectorAll('.table tbody');
    console.log('🔍 Total tables with tbody on page:', allTables.length);
    
    // Find the VISIBLE table
    let tbody = null;
    allTables.forEach((tb, index) => {
        const height = tb.offsetHeight;
        const parent = tb.closest('.table-responsive');
        console.log(`   Table ${index}: height=${height}px, parent height=${parent ? parent.offsetHeight : 'N/A'}px`);
        if (height > 0 && !tbody) {
            tbody = tb;
            console.log(`   ✅ Using table ${index} (first visible one)`);
        }
    });
    
    if (!tbody) {
        console.log('❌ ERROR: No visible tbody found, using first one as fallback');
        tbody = document.querySelector('.table tbody');
    }
    
    if (!tbody) {
        console.log('ERROR: tbody not found');
        return;
    }
    
    // Show loading animation
    refreshIcon.classList.add('fa-spin');
    
    // Build query string from current URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('ajax_refresh', '1');
    const fetchUrl = '?' + urlParams.toString();
    
    console.log('🔄 Fetching AJAX data from:', fetchUrl);
    
    // Fetch updated table data
    fetch(fetchUrl, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        console.log('✅ Response received. Status:', response.status, 'OK:', response.ok);
        return response.text();
    })
    .then(html => {
        // Debug: Log response size and preview
        console.log('📦 AJAX response:', html.length, 'characters');
        console.log('📄 First 200 chars:', html.substring(0, 200));
        
        // Parse the HTML response
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const newTbody = doc.querySelector('.table tbody');
        const scoresCountText = doc.querySelector('#scoresCount')?.textContent;
        
        console.log('🔍 Found tbody:', newTbody ? 'YES (' + newTbody.querySelectorAll('tr').length + ' rows)' : 'NO');
        console.log('🔍 Found scoresCount:', scoresCountText ? scoresCountText : 'NO');
        
        if (newTbody) {
            // Log current state
            const currentRowCount = tbody.querySelectorAll('tr').length;
            console.log('📊 Current table has', currentRowCount, 'rows');
            console.log('📊 New data has', newTbody.querySelectorAll('tr').length, 'rows');
            
            // Preserve checkbox states
            const previouslySelected = new Set();
            tbody.querySelectorAll('.row-checkbox:checked').forEach(cb => {
                previouslySelected.add(cb.dataset.scoreId);
            });
            
            console.log('💾 Preserving', previouslySelected.size, 'selected checkboxes');
            
            // Update table body
            const oldHTML = tbody.innerHTML.substring(0, 100);
            tbody.innerHTML = newTbody.innerHTML;
            const newHTML = tbody.innerHTML.substring(0, 100);
            
            console.log('🔄 Updated tbody. Old start:', oldHTML);
            console.log('🔄 Updated tbody. New start:', newHTML);
            console.log('📊 After update, table has', tbody.querySelectorAll('tr').length, 'rows');
            
            // Debug: Show actual content
            const firstRow = tbody.querySelector('tr');
            if (firstRow) {
                console.log('👁️ First row HTML:', firstRow.outerHTML.substring(0, 300));
                console.log('👁️ First row visible?', firstRow.offsetHeight > 0 ? 'YES (height: ' + firstRow.offsetHeight + 'px)' : 'NO - HIDDEN!');
                
                // Check parent visibility
                const table = tbody.closest('table');
                const tableResponsive = tbody.closest('.table-responsive');
                console.log('📐 Table height:', table ? table.offsetHeight + 'px' : 'NOT FOUND');
                console.log('📐 Table-responsive height:', tableResponsive ? tableResponsive.offsetHeight + 'px' : 'NOT FOUND');
                console.log('📐 Tbody height:', tbody.offsetHeight + 'px');
                
                // Check computed styles
                const rowStyle = window.getComputedStyle(firstRow);
                console.log('🎨 Row display:', rowStyle.display);
                console.log('🎨 Row visibility:', rowStyle.visibility);
                console.log('🎨 Row opacity:', rowStyle.opacity);
            } else {
                console.log('❌ No rows found in tbody after update!');
            }
            
            // Restore checkbox states
            tbody.querySelectorAll('.row-checkbox').forEach(cb => {
                if (previouslySelected.has(cb.dataset.scoreId)) {
                    cb.checked = true;
                    toggleRowSelection(cb);
                }
                
                // Re-attach event listener
                cb.addEventListener('change', function() {
                    toggleRowSelection(this);
                    updateSelectionUI();
                    
                    const allCheckboxes = document.querySelectorAll('.row-checkbox');
                    const checkedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
                    const selectAllCb = document.getElementById('selectAll');
                    if (selectAllCb) {
                        selectAllCb.checked = allCheckboxes.length === checkedCheckboxes.length && allCheckboxes.length > 0;
                        selectAllCb.indeterminate = checkedCheckboxes.length > 0 && checkedCheckboxes.length < allCheckboxes.length;
                    }
                });
            });
            
            // Update scores count
            if (scoresCountText) {
                const countElement = document.getElementById('scoresCount');
                if (countElement) {
                    countElement.textContent = scoresCountText;
                }
            }
            
            // Update last refresh time
            lastRefreshTimestamp = new Date();
            updateRefreshTimeDisplay();
            
            console.log('✅ Table refreshed successfully');
        } else {
            console.error('❌ ERROR: Could not find tbody in AJAX response');
        }
    })
    .catch(error => {
        console.error('❌ AJAX Error:', error);
        showNotification('Failed to refresh table data: ' + error.message, 'error');
    })
    .finally(() => {
        // Remove loading animation
        refreshIcon.classList.remove('fa-spin');
    });
}

function updateRefreshTimeDisplay() {
    const timeElement = document.getElementById('lastRefreshTime');
    if (!timeElement || !lastRefreshTimestamp) return;
    
    const now = new Date();
    const diff = Math.floor((now - lastRefreshTimestamp) / 1000);
    
    let timeText;
    if (diff < 60) {
        timeText = `${diff}s ago`;
    } else if (diff < 3600) {
        const minutes = Math.floor(diff / 60);
        timeText = `${minutes}m ago`;
    } else {
        timeText = lastRefreshTimestamp.toLocaleTimeString();
    }
    
    timeElement.textContent = timeText;
}

// Initialize auto-refresh on page load
document.addEventListener('DOMContentLoaded', function() {
    // Set initial last refresh time
    lastRefreshTimestamp = new Date();
    updateRefreshTimeDisplay();
    
    // Start auto-refresh if interval is set
    handleRefreshIntervalChange();
    
    // Update "time ago" display every 5 seconds
    setInterval(updateRefreshTimeDisplay, 5000);
});
</script>

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

<?php
} // End of if (!$ajax_refresh_mode)

// AJAX refresh mode - output only the table section
if ($ajax_refresh_mode) {
    ?>
    <div class="table-responsive">
        <table class="table table-bordered table-hover table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th style="width: 40px;">
                        <input type="checkbox" id="selectAll" class="form-check-input" title="Select All">
                    </th>
                    <th><i class="fas fa-trophy me-1"></i>Event</th>
                    <th><i class="fas fa-user me-1"></i>Participant</th>
                    <th><i class="fas fa-fire me-1"></i>Heat</th>
                    <th><i class="fas fa-running me-1"></i>Run</th>
                    <th><i class="fas fa-user-tie me-1"></i>Judge</th>
                    <?php if ($hasControlPointCol): ?>
                        <th><i class="fas fa-crosshairs me-1"></i>Control Point</th>
                    <?php endif; ?>
                    <th><i class="fas fa-star me-1"></i>Score</th>
                    <th><i class="fas fa-flag me-1"></i>Status</th>
                    <th><i class="fas fa-calendar me-1"></i>Created</th>
                    <?php if ($hasApprovalCols): ?>
                        <th><i class="fas fa-check-circle me-1"></i>Approval</th>
                    <?php endif; ?>
                    <?php if ($hasFiguresCol): ?>
                        <th><i class="fas fa-list-check me-1"></i>Figures</th>
                    <?php endif; ?>
                    <th><i class="fas fa-edit me-1"></i>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($scores)): ?>
                    <tr>
                        <td colspan="<?= 9 + ($hasControlPointCol ? 1 : 0) + ($hasApprovalCols ? 1 : 0) + ($hasFiguresCol ? 1 : 0) ?>" class="text-center text-muted py-4">
                            <i class="fas fa-search fa-2x mb-2 opacity-50"></i><br>
                            <?= $selected_event ? 'No scores found for the selected filters.' : 'Please select an event to view scores.' ?>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($scores as $score): ?>
                    <tr data-score-id="<?= $score['score_id'] ?>">
                        <td class="text-center">
                            <input type="checkbox" class="form-check-input row-checkbox" 
                                   data-score-id="<?= $score['score_id'] ?>"
                                   data-score-data='<?= htmlspecialchars(json_encode($score), ENT_QUOTES) ?>'>
                        </td>
                        <td>
                            <strong class="text-primary"><?= htmlspecialchars($score['event_name']) ?></strong>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-primary me-2"><?= htmlspecialchars($score['bib']) ?></span>
                                <div>
                                    <strong><?= htmlspecialchars($score['first_name']) ?> <?= htmlspecialchars($score['last_name']) ?></strong>
                                </div>
                            </div>
                        </td>
                        <td><span class="badge bg-info">Heat <?= htmlspecialchars($score['heat_number']) ?></span></td>
                        <td><span class="badge bg-success">Run <?= $score['run_number'] ?></span></td>
                        <td><?= htmlspecialchars($score['judge_name']) ?></td>
                        <?php if ($hasControlPointCol): ?>
                            <td>
                                <?php if ($score['control_point_name']): ?>
                                    <span class="badge control-point-badge">
                                        <?= htmlspecialchars($score['control_point_name']) ?>
                                        <?php if ($score['control_point_weight'] != 1.00): ?>
                                            <small>(×<?= $score['control_point_weight'] ?>)</small>
                                        <?php endif; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        <?php endif; ?>
                        <td>
                            <span class="fs-5 fw-bold text-primary"><?= $score['score_value'] ?></span>
                        </td>
                        <td>
                            <span class="badge bg-<?= $score['status'] == 'OK' ? 'success' : 'warning' ?>">
                                <?= $score['status'] ?>
                            </span>
                        </td>
                        <td>
                            <div class="small">
                                <div class="text-muted">
                                    <i class="fas fa-plus-circle me-1"></i>
                                    <?= date('M j, Y', strtotime($score['created_at'])) ?>
                                </div>
                                <div class="text-muted" style="font-size: 0.7rem;">
                                    <?= date('H:i', strtotime($score['created_at'])) ?>
                                </div>
                                <?php if ($score['updated_at'] && $score['updated_at'] !== $score['created_at']): ?>
                                    <div class="text-warning" style="font-size: 0.7rem;">
                                        <i class="fas fa-edit me-1"></i>Updated: <?= date('M j, H:i', strtotime($score['updated_at'])) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </td>
                        <?php if ($hasApprovalCols): ?>
                        <td>
                            <?php if ($hasApprovalCols && isset($score['is_approved'])): ?>
                                <?php
                                if ($score['is_approved'] === '1' || $score['is_approved'] === 1 || $score['is_approved'] === true) {
                                    $approvalBadgeClass = 'bg-success';
                                    $approvalIcon = 'fas fa-check-circle';
                                    $approvalText = 'Approved';
                                    $clickAction = 'unapproveScore';
                                    $clickTitle = 'Click to unapprove';
                                } elseif ($score['is_approved'] === '0' || $score['is_approved'] === 0 || $score['is_approved'] === false) {
                                    $approvalBadgeClass = 'bg-danger';
                                    $approvalIcon = 'fas fa-times-circle';
                                    $approvalText = 'Not Approved';
                                    $clickAction = 'approveScore';
                                    $clickTitle = 'Click to approve';
                                } else {
                                    $approvalBadgeClass = 'bg-warning';
                                    $approvalIcon = 'fas fa-clock';
                                    $approvalText = 'Pending';
                                    $clickAction = 'approveScore';
                                    $clickTitle = 'Click to approve';
                                }
                                ?>
                                <span class="badge <?= $approvalBadgeClass ?> approval-clickable" 
                                      onclick="<?= $clickAction ?>(<?= $score['score_id'] ?>, this)" 
                                      style="cursor: pointer;" 
                                      title="<?= $clickTitle ?>">
                                    <i class="<?= $approvalIcon ?> me-1"></i><?= $approvalText ?>
                                </span>
                                <?php if ($score['approved_at']): ?>
                                    <div class="text-muted small mt-1">
                                        <?= date('M j, H:i', strtotime($score['approved_at'])) ?>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                        <?php if ($hasFiguresCol): ?>
                            <td>
                                <?php if (!empty($score['figures_json'])): ?>
                                    <?php
                                    $figuresData = json_decode($score['figures_json'], true);
                                    if ($figuresData && is_array($figuresData) && json_last_error() === JSON_ERROR_NONE):
                                        // Handle both new format (with "figures" wrapper) and old format (direct categories)
                                        $figures = isset($figuresData['figures']) ? $figuresData['figures'] : $figuresData;
                                        
                                        if ($figures && is_array($figures)):
                                    ?>
                                        <div class="figures-display">
                                            <?php foreach ($figures as $category => $items): ?>
                                                <?php if (is_array($items) && !empty($items)): ?>
                                                    <div class="mb-1">
                                                        <small class="badge bg-light text-dark me-1 mb-1"><?= htmlspecialchars($category) ?>:</small>
                                                        <br>
                                                        <?php foreach ($items as $item): ?>
                                                            <?php if (!empty(trim($item))): ?>
                                                                <span class="fw-bold text-primary"><?= htmlspecialchars($item) ?></span>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-muted">No figures</span>
                                    <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">Invalid JSON</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        <?php endif; ?>
                        <td>
                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                    data-score-id="<?= $score['score_id'] ?>"
                                    data-participant-name="<?= htmlspecialchars($score['first_name'] . ' ' . $score['last_name']) ?>"
                                    data-bib="<?= $score['bib'] ?>"
                                    data-run="<?= $score['run_number'] ?>"
                                    data-score="<?= $score['score_value'] ?>"
                                    data-status="<?= $score['status'] ?>"
                                    <?php if ($hasFiguresCol): ?>
                                        data-figures='<?= htmlspecialchars($score['figures_json'] ?? '') ?>'
                                    <?php endif; ?>
                                    onclick="editScoreFromButton(this)">
                                <i class="fas fa-edit me-1"></i>Edit
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
    exit; // Stop execution after outputting AJAX content
}
?>