<?php
// Test version with bypassed authentication
session_start();

// Mock authentication for testing
$_SESSION['user_logged_in'] = true;
$_SESSION['user_type'] = 'head_judge';
$_SESSION['user_id'] = 1;

// Include database connection
include '../includes/db.php';

// 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;

// 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;
}

$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 - fixed column names
$figuresSelect = $hasFiguresCol ? ", s.figures_json" : "";
$controlPointJoin = $hasControlPointCol ? "LEFT JOIN event_control_points ecp ON s.control_point_id = ecp.id" : "";
$controlPointSelect = $hasControlPointCol ? ", ecp.description as control_point_name, ecp.weight as control_point_weight" : ", NULL as control_point_name, NULL as control_point_weight";

// 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
           $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) - fixed column names
    if ($hasControlPointCol) {
        try {
            $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);
        } catch (Exception $e) {
            // If description column doesn't exist, try other common column names
            $control_points = [];
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Head Judge Override Panel - Test Version</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<!-- style skin holder -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .score-override-card {
            border-left: 4px solid #007bff;
        }
        .control-point-badge {
            background: linear-gradient(45deg, #6f42c1, #e83e8c);
            color: white;
            border: none;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
<div class="container-fluid container-StyleScore p-4">
    <div class="row mb-4">
        <div class="col">
            <div class="alert alert-info">
                <strong>Test Version:</strong> Authentication bypassed for development. Found <?= count($scores) ?> scores.
                <?php if ($hasFiguresCol): ?>
                    <span class="badge bg-success">Figures Supported</span>
                <?php endif; ?>
                <?php if ($hasControlPointCol): ?>
                    <span class="badge bg-primary">Control Points Supported</span>
                <?php endif; ?>
            </div>
            <h2><i class="fas fa-gavel me-2"></i>Head Judge Override Panel</h2>
            <p class="text-muted mb-0">Comprehensive score management with figure tracking and control point information</p>
        </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-4 score-override-card">
        <div class="border-0 shadow-none card-header">
            <h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filters & Search</h5>
        </div>
        <div class="border-0 shadow-none card-body">
            <form method="get" class="row g-3">
                <div class="col-md-3">
                    <label for="event_id" class="form-label">Event</label>
                    <select name="event_id" id="event_id" class="form-select" 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">Heat</label>
                    <select name="heat" id="heat" class="form-select" 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-2">
                    <label for="run" class="form-label">Run</label>
                    <select name="run" id="run" class="form-select" 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-2">
                    <label for="judge" class="form-label">Judge</label>
                    <select name="judge" id="judge" class="form-select" 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">Control Point</label>
                    <select name="control_point" id="control_point" class="form-select" 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-1 d-flex align-items-end">
                    <button type="button" class="btn btn-outline-secondary" onclick="window.location.href = window.location.pathname">
                        <i class="fas fa-eraser me-1"></i>Clear
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Simple Results Table -->
    <div class="table-responsive">
        <table class="table table-bordered table-hover table-striped">
            <thead class="table-dark">
                <tr>
                    <th>Event</th>
                    <th>Participant</th>
                    <th>Heat</th>
                    <th>Run</th>
                    <th>Judge</th>
                    <?php if ($hasControlPointCol): ?>
                        <th>Control Point</th>
                    <?php endif; ?>
                    <th>Score</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($scores)): ?>
                    <tr>
                        <td colspan="<?= 7 + ($hasControlPointCol ? 1 : 0) ?>" class="text-center text-muted py-4">
                            <?= $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>
                        <td><?= htmlspecialchars($score['event_name']) ?></td>
                        <td>
                            <span class="badge bg-primary me-2"><?= htmlspecialchars($score['bib']) ?></span>
                            <?= htmlspecialchars($score['first_name']) ?> <?= htmlspecialchars($score['last_name']) ?>
                        </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>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>


</body>
</html>
