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

$ep_id = (int)($_GET['ep_id'] ?? 0);
$heat_number = (int)($_GET['heat_number'] ?? 0);
$run_number = isset($_GET['run_number']) ? (int)$_GET['run_number'] : null;
$current_judge_only = isset($_GET['current_judge_only']) && $_GET['current_judge_only'];

// Current judge id (used to sort current judge first)
$current_judge_id = (int)($_GET['current_judge_id'] ?? ($_SESSION['judge_id'] ?? 0));

header('Content-Type: application/json');

if (!$ep_id || !$heat_number) {
    echo json_encode([]);
    exit;
}

// Resolve event_id for participant
$stmt = $pdo->prepare("SELECT event_id FROM event_participants WHERE id = ?");
$stmt->execute([$ep_id]);
$event_id = (int)$stmt->fetchColumn();
if (!$event_id) {
    echo json_encode([]);
    exit;
}

/*
Schema assumptions:
- scores.judge_id = domain judge id (same value stored in judge_assignments.judge_id).
- users.judge_id optionally stores that domain judge id.
- Some installs may have scores.judge_id equal to users.id; handle both via dual LEFT JOINs.
- judge_assignments has event_control_point_id referencing event_control_points.id (see DDL below).
*/
// 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; 
}

$sql = "
    SELECT 
        s.score_value,
        s.status," . 
        ($hasFiguresCol ? "
        s.figures_json," : "") . "
        r.run_number,
        s.judge_id,
        COALESCE(u1.username, u2.username, CONCAT('Judge ', s.judge_id)) AS judge_name,
        COALESCE(ecp.control_point_name, '—') AS control_point_name,
        COALESCE(s.updated_at, s.created_at) AS updated_at
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    JOIN event_participants ep ON r.event_participant_id = ep.id
    -- Prefer users.judge_id mapping
    LEFT JOIN users u1 ON u1.judge_id = s.judge_id
    -- Fallback: scores.judge_id equals users.id
    LEFT JOIN users u2 ON u2.id = s.judge_id
    LEFT JOIN judge_assignments ja 
        ON ja.event_id = ep.event_id
       AND ja.judge_id = s.judge_id
       AND (ja.heat_number IS NULL OR ja.heat_number = ep.heat_number)
    LEFT JOIN event_control_points ecp 
        ON ecp.id = ja.control_point_id
    WHERE ep.event_id = :event_id
      AND ep.heat_number = :heat_number
      AND ep.id = :ep_id";

// Add filters
$params = [
    ':event_id' => $event_id,
    ':heat_number' => $heat_number,
    ':ep_id' => $ep_id,
    ':current_judge_id' => $current_judge_id
];

if ($current_judge_only) {
    $sql .= " AND s.judge_id = :current_judge_id";
}

if ($run_number !== null) {
    $sql .= " AND r.run_number = :run_number";
    $params[':run_number'] = $run_number;
}

$sql .= "
    ORDER BY 
        (s.judge_id = :current_judge_id) DESC,  -- current judge first
        r.run_number ASC,
        COALESCE(s.updated_at, s.created_at) DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
