<?php
/**
 * AJAX endpoint for judge scoring overview
 * Returns all scores for a specific judge and event, grouped by participant
 */

header('Content-Type: application/json');
require_once '../includes/auth.php';
require_once '../includes/db.php';

try {
    $event_id = $_GET['event_id'] ?? '';
    $judge_id = $_GET['judge_id'] ?? '';
    
    if (!$event_id || !$judge_id) {
        echo json_encode(['error' => 'Missing event_id or judge_id parameter']);
        exit;
    }
    
    // Get all scores for this judge and event
    $scores_stmt = $pdo->prepare("
        SELECT 
            s.id as score_id,
            s.score_value,
            s.status,
            s.figures_json,
            s.created_at,
            r.run_number,
            ep.heat_number,
            ep.bib_number,
            p.first_name,
            p.last_name,
            CONCAT(p.first_name, ' ', p.last_name) as participant_name
        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
        WHERE s.judge_id = ? AND ep.event_id = ?
        ORDER BY ep.bib_number ASC, r.run_number ASC
    ");
    $scores_stmt->execute([$judge_id, $event_id]);
    $scores = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate summary statistics
    $total_scores = count($scores);
    $valid_scores = array_filter($scores, function($score) {
        return $score['status'] === 'OK' && $score['score_value'] !== null;
    });
    
    $average_score = 0;
    if (count($valid_scores) > 0) {
        $sum = array_sum(array_column($valid_scores, 'score_value'));
        $average_score = round($sum / count($valid_scores), 2);
    }
    
    // Get participant count
    $participants_stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT ep.id) as participant_count
        FROM event_participants ep
        WHERE ep.event_id = ?
    ");
    $participants_stmt->execute([$event_id]);
    $participant_count = $participants_stmt->fetchColumn();
    
    // Get event info
    $event_stmt = $pdo->prepare("SELECT name, date FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event_info = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get judge info
    $judge_stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $judge_stmt->execute([$judge_id]);
    $judge_name = $judge_stmt->fetchColumn();
    
    // Format scores for response
    $formatted_scores = array_map(function($score) {
        return [
            'score_id' => $score['score_id'],
            'score_value' => $score['score_value'],
            'status' => $score['status'],
            'figures_json' => $score['figures_json'],
            'created_at' => $score['created_at'],
            'run_number' => $score['run_number'],
            'heat_number' => $score['heat_number'],
            'bib_number' => $score['bib_number'],
            'participant_name' => $score['participant_name'],
            'first_name' => $score['first_name'],
            'last_name' => $score['last_name']
        ];
    }, $scores);
    
    $response = [
        'success' => true,
        'event' => [
            'id' => $event_id,
            'name' => $event_info['name'] ?? 'Unknown Event',
            'date' => $event_info['date'] ?? null
        ],
        'judge' => [
            'id' => $judge_id,
            'name' => $judge_name ?? 'Unknown Judge'
        ],
        'summary' => [
            'total_scores' => $total_scores,
            'average_score' => $average_score,
            'participant_count' => $participant_count,
            'completed_participants' => count(array_unique(array_column($scores, 'bib_number')))
        ],
        'scores' => $formatted_scores
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Database error: ' . $e->getMessage(),
        'success' => false
    ]);
}
?>
