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

// Test the logic for fetching students for exam ID 68
$exam_id = 68;

// Get exam details
$stmt = $pdo->prepare("
    SELECT e.*, c.name as class_name, c.section
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    WHERE e.id = ?
");
$stmt->execute([$exam_id]);
$exam_details = $stmt->fetch();

echo "<h2>Exam Details:</h2>";
if ($exam_details) {
    echo "<p>ID: " . $exam_details['id'] . "</p>";
    echo "<p>Name: " . $exam_details['name'] . "</p>";
    echo "<p>Class ID: " . $exam_details['class_id'] . "</p>";
    echo "<p>Session: " . $exam_details['session'] . "</p>";
    echo "<p>Group: " . ($exam_details['group_name'] ?? 'N/A') . "</p>";
    
    // Get students for this exam
    $params = [$exam_details['class_id'], $exam_details['session']];
    
    if ($exam_details['group_name']) {
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.guardian_name
            FROM students s
            WHERE s.class_id = ? AND s.session = ? AND s.group_name = ? AND s.status = 'active'
            ORDER BY s.roll_number
        ");
        $params[] = $exam_details['group_name'];
    } else {
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.guardian_name
            FROM students s
            WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
            ORDER BY s.roll_number
        ");
    }
    
    $stmt->execute($params);
    $students = $stmt->fetchAll();
    
    echo "<h3>Students Found: " . count($students) . "</h3>";
    
    if (!empty($students)) {
        echo "<ul>";
        foreach ($students as $student) {
            echo "<li>" . $student['first_name'] . " " . $student['last_name'] . " (Roll: " . $student['roll_number'] . ")</li>";
        }
        echo "</ul>";
    } else {
        echo "<p>No students found</p>";
    }
} else {
    echo "<p>Exam not found</p>";
}
?>