<?php
/**
 * AJAX endpoint for event summary results
 * Returns consolidated event results in various formats
 */

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

try {
    $event_id = $_GET['event_id'] ?? '';
    $type = $_GET['type'] ?? 'final';
    $format = $_GET['format'] ?? 'table';
    
    if (!$event_id) {
        echo json_encode(['error' => 'Missing event_id parameter']);
        exit;
    }
    
    $response = [
        'success' => true,
        'event_id' => $event_id,
        'type' => $type,
        'format' => $format,
        'results' => []
    ];
    
    if ($type === 'final') {
        // Get final results - best score per participant
        $results_stmt = $pdo->prepare("
            SELECT 
                ep.bib_number,
                CONCAT(p.first_name, ' ', p.last_name) as participant_name,
                ep.heat_number,
                MAX(CASE WHEN s.status = 'OK' THEN s.score_value ELSE NULL END) as best_score,
                AVG(CASE WHEN s.status = 'OK' THEN s.score_value ELSE NULL END) as average_score,
                COUNT(s.id) as completed_runs,
                (SELECT COUNT(DISTINCT r2.run_number) 
                 FROM runs r2 
                 WHERE r2.event_participant_id = ep.id) as total_runs,
                GROUP_CONCAT(
                    CASE WHEN s.status = 'OK' THEN s.score_value ELSE NULL END 
                    ORDER BY r.run_number SEPARATOR ', '
                ) as all_scores
            FROM event_participants ep
            JOIN participants p ON ep.participant_id = p.id
            LEFT JOIN runs r ON r.event_participant_id = ep.id
            LEFT JOIN scores s ON s.run_id = r.id
            WHERE ep.event_id = ?
            GROUP BY ep.id, ep.bib_number, p.first_name, p.last_name, ep.heat_number
            HAVING best_score IS NOT NULL
            ORDER BY best_score DESC, average_score DESC
        ");
        $results_stmt->execute([$event_id]);
        $results = $results_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Format results
        $response['results'] = array_map(function($result, $index) {
            return [
                'rank' => $index + 1,
                'bib_number' => $result['bib_number'],
                'participant_name' => $result['participant_name'],
                'heat_number' => $result['heat_number'],
                'best_score' => $result['best_score'] ? round($result['best_score'], 2) : 0,
                'average_score' => $result['average_score'] ? round($result['average_score'], 2) : 0,
                'completed_runs' => $result['completed_runs'],
                'total_runs' => $result['total_runs'],
                'all_scores' => $result['all_scores']
            ];
        }, $results, array_keys($results));
        
    } elseif ($type === 'by_heat') {
        // Get results grouped by heat
        $heat_results_stmt = $pdo->prepare("
            SELECT 
                ep.heat_number,
                ep.bib_number,
                CONCAT(p.first_name, ' ', p.last_name) as participant_name,
                MAX(CASE WHEN s.status = 'OK' THEN s.score_value ELSE NULL END) as best_score,
                AVG(CASE WHEN s.status = 'OK' THEN s.score_value ELSE NULL END) as average_score,
                COUNT(s.id) as completed_runs
            FROM event_participants ep
            JOIN participants p ON ep.participant_id = p.id
            LEFT JOIN runs r ON r.event_participant_id = ep.id
            LEFT JOIN scores s ON s.run_id = r.id
            WHERE ep.event_id = ?
            GROUP BY ep.heat_number, ep.id, ep.bib_number, p.first_name, p.last_name
            ORDER BY ep.heat_number ASC, best_score DESC
        ");
        $heat_results_stmt->execute([$event_id]);
        $heat_results = $heat_results_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by heat
        $grouped_results = [];
        foreach ($heat_results as $result) {
            $heat = $result['heat_number'];
            if (!isset($grouped_results[$heat])) {
                $grouped_results[$heat] = [];
            }
            $grouped_results[$heat][] = [
                'bib_number' => $result['bib_number'],
                'participant_name' => $result['participant_name'],
                'best_score' => $result['best_score'] ? round($result['best_score'], 2) : 0,
                'average_score' => $result['average_score'] ? round($result['average_score'], 2) : 0,
                'completed_runs' => $result['completed_runs']
            ];
        }
        
        $response['results'] = $grouped_results;
        
    } elseif ($type === 'by_run') {
        // Get results by individual run
        $run_results_stmt = $pdo->prepare("
            SELECT 
                r.run_number,
                ep.heat_number,
                ep.bib_number,
                CONCAT(p.first_name, ' ', p.last_name) as participant_name,
                s.score_value,
                s.status,
                s.created_at,
                u.username as judge_name
            FROM runs r
            JOIN event_participants ep ON r.event_participant_id = ep.id
            JOIN participants p ON ep.participant_id = p.id
            LEFT JOIN scores s ON s.run_id = r.id
            LEFT JOIN users u ON s.judge_id = u.id
            WHERE ep.event_id = ?
            ORDER BY r.run_number ASC, ep.heat_number ASC, ep.bib_number ASC
        ");
        $run_results_stmt->execute([$event_id]);
        $run_results = $run_results_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by run number
        $grouped_by_run = [];
        foreach ($run_results as $result) {
            $run = $result['run_number'];
            if (!isset($grouped_by_run[$run])) {
                $grouped_by_run[$run] = [];
            }
            $grouped_by_run[$run][] = [
                'heat_number' => $result['heat_number'],
                'bib_number' => $result['bib_number'],
                'participant_name' => $result['participant_name'],
                'score_value' => $result['score_value'],
                'status' => $result['status'],
                'judge_name' => $result['judge_name'],
                'created_at' => $result['created_at']
            ];
        }
        
        $response['results'] = $grouped_by_run;
    }
    
    // Get event metadata
    $event_stmt = $pdo->prepare("SELECT name, date FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event_info = $event_stmt->fetch(PDO::FETCH_ASSOC);
    
    $response['event_info'] = [
        'name' => $event_info['name'] ?? 'Unknown Event',
        'date' => $event_info['date'] ?? null
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Database error: ' . $e->getMessage(),
        'success' => false
    ]);
}
?>
