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

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

// Get parameters
$ep_id = $_GET['ep_id'] ?? '';
$judge_id = $_GET['judge_id'] ?? '';

// Debug logging
error_log("ajax_get_figure_history.php called with ep_id: $ep_id, judge_id: $judge_id");

if (!$ep_id || !$judge_id) {
    error_log("Missing parameters - ep_id: $ep_id, judge_id: $judge_id");
    echo json_encode([]);
    exit;
}

try {
    // Check if figures_json column exists
    $hasFiguresCol = false;
    try {
        $pdo->query("SELECT figures_json FROM scores WHERE 1=0");
        $hasFiguresCol = true;
        error_log("figures_json column exists");
    } catch (Exception $e) {
        $hasFiguresCol = false;
        error_log("figures_json column does not exist: " . $e->getMessage());
    }
    
    if (!$hasFiguresCol) {
        error_log("No figures_json column, returning empty array");
        echo json_encode([]);
        exit;
    }
    
    // First, let's check if there are any scores for this participant at all
    $check_stmt = $pdo->prepare("
        SELECT COUNT(*) as total_scores, 
               COUNT(CASE WHEN s.figures_json IS NOT NULL AND s.figures_json != '' AND s.figures_json != '{}' THEN 1 END) as with_figures
        FROM scores s
        JOIN runs r ON s.run_id = r.id
        WHERE r.event_participant_id = ?
    ");
    
    $check_stmt->execute([$ep_id]);
    $counts = $check_stmt->fetch(PDO::FETCH_ASSOC);
    error_log("Found {$counts['total_scores']} total scores, {$counts['with_figures']} with figures (from all judges)");
    
    // Fetch scores with figures for this participant from ANY judge (figures are objective)
    $stmt = $pdo->prepare("
        SELECT s.run_id, s.figures_json, r.run_number, s.created_at, s.updated_at, s.judge_id
        FROM scores s
        JOIN runs r ON s.run_id = r.id
        WHERE r.event_participant_id = ? 
        AND s.figures_json IS NOT NULL 
        AND s.figures_json != ''
        AND s.figures_json != '{}'
        AND s.figures_json NOT LIKE '%\"Rotation\":{}%'
        ORDER BY r.run_number ASC, s.created_at DESC
    ");
    
    $stmt->execute([$ep_id]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    error_log("Query returned " . count($results) . " results (from any judge)");
    
    if (count($results) > 0) {
        error_log("Sample result: " . json_encode($results[0]));
    }
    
    // Remove duplicates (keep latest score per run, prefer current judge if available)
    $unique_runs = [];
    foreach ($results as $score) {
        $run_num = $score['run_number'];
        if (!isset($unique_runs[$run_num])) {
            $unique_runs[$run_num] = $score;
        } else {
            // If we already have a score for this run, prefer the one from current judge
            if ($score['judge_id'] == $judge_id) {
                $unique_runs[$run_num] = $score;
            }
        }
    }
    
    error_log("Final unique runs: " . count($unique_runs));
    
    // Return array of scores with figures
    echo json_encode(array_values($unique_runs));
    
} catch (Exception $e) {
    error_log("Error in ajax_get_figure_history.php: " . $e->getMessage());
    echo json_encode([]);
}
?>
