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

// Function to get subjects for a specific student
function getStudentSubjects($pdo, $exam_id, $student_id) {
    $stmt = $pdo->prepare("
        SELECT es.*, s.name as subject_name, s.code as subject_code
        FROM exam_subjects es
        JOIN subjects s ON es.subject_id = s.id
        JOIN student_subjects ss ON es.subject_id = ss.subject_id
        WHERE es.exam_id = ? AND ss.student_id = ?
        ORDER BY es.exam_date, es.start_time
    ");
    $stmt->execute([$exam_id, $student_id]);
    return $stmt->fetchAll();
}

try {
    // Test with a sample exam and student
    echo "Testing getStudentSubjects function:\n";
    
    // Get a sample exam ID
    $stmt = $pdo->query("SELECT id FROM exams LIMIT 1");
    $exam = $stmt->fetch();
    
    if ($exam) {
        $exam_id = $exam['id'];
        echo "Using exam ID: " . $exam_id . "\n";
        
        // Get a sample student ID for this exam
        $stmt = $pdo->prepare("
            SELECT s.id 
            FROM students s 
            JOIN classes c ON s.class_id = c.id 
            JOIN exams e ON c.id = e.class_id 
            WHERE e.id = ? 
            LIMIT 1
        ");
        $stmt->execute([$exam_id]);
        $student = $stmt->fetch();
        
        if ($student) {
            $student_id = $student['id'];
            echo "Using student ID: " . $student_id . "\n";
            
            // Get student subjects
            $subjects = getStudentSubjects($pdo, $exam_id, $student_id);
            
            echo "Subjects for this student in this exam:\n";
            echo "Total subjects: " . count($subjects) . "\n";
            
            if (count($subjects) > 0) {
                foreach ($subjects as $subject) {
                    echo "- " . $subject['subject_name'] . " (" . $subject['subject_code'] . ")\n";
                    echo "  Date: " . $subject['exam_date'] . ", Time: " . $subject['start_time'] . " - " . $subject['end_time'] . "\n";
                }
            } else {
                echo "No subjects found for this student in this exam.\n";
            }
        } else {
            echo "No student found for this exam.\n";
        }
    } else {
        echo "No exams found in the database.\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>