<?php
require_once '../config/database.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Get leaderboard for Flutter exam
try {
    $exam_code = $_GET['exam_code'] ?? 'FLUTTER2026';
    
    $stmt = $pdo->prepare("
        SELECT 
            l.full_name as student_name,
            ar.total_score as score,
            ar.maximum_score as max_score,
            ROUND((ar.total_score / ar.maximum_score) * 100, 1) as percentage,
            ar.pass_status as passed,
            ar.graded_at as completed_at
        FROM assessment_results ar
        JOIN learners l ON ar.learner_id = l.learner_id
        JOIN assessments a ON ar.assessment_id = a.assessment_id
        WHERE a.exam_code = ?
        ORDER BY ar.total_score DESC, ar.graded_at ASC
        LIMIT 50
    ");
    $stmt->execute([$exam_code]);
    $leaderboard = $stmt->fetchAll();
    
    // Add rank to each entry
    $rank = 1;
    foreach ($leaderboard as &$entry) {
        $entry['rank'] = $rank++;
        $entry['passed'] = (bool)$entry['passed'];
    }
    
    echo json_encode([
        'success' => true,
        'exam_code' => $exam_code,
        'total_participants' => count($leaderboard),
        'leaderboard' => $leaderboard
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error', 'message' => $e->getMessage()]);
}
?>
