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

// Simulate the URL parameters
$_GET['student_id'] = '6279';
$_GET['session'] = '2025';
$_GET['exam_type'] = 'final';

$student_id = $_GET['student_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';

echo "Parameters: student_id=$student_id, session=$session, exam_type=$exam_type\n";
echo "Condition check: " . ($student_id && $session && $exam_type ? 'TRUE' : 'FALSE') . "\n\n";

if ($student_id && $session && $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section
        FROM students s
        JOIN classes c ON s.class_id = c.id
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();

    if ($student) {
        echo "Student found: {$student['first_name']} {$student['last_name']}\n";

        // Get results for the student
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(r.id, NULL) as result_id,
                COALESCE(r.marks_obtained, 0) as marks_obtained,
                COALESCE(r.grade, 'F') as grade,
                ss.subject_id,
                sub.name as subject_name,
                ss.is_fourth_subject
            FROM student_subjects ss
            LEFT JOIN subjects sub ON ss.subject_id = sub.id
            LEFT JOIN (
                SELECT *
                FROM results
                WHERE student_id = ? AND session = ? AND exam_type = ?
                AND id IN (
                    SELECT MAX(id)
                    FROM results
                    WHERE student_id = ? AND session = ? AND exam_type = ?
                    GROUP BY subject_id
                )
            ) r ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
            WHERE ss.student_id = ? AND sub.status = 'active'
            ORDER BY CASE WHEN ss.is_fourth_subject = 1 THEN 1 ELSE 0 END, sub.name
        ");
        $stmt->execute([$student_id, $session, $exam_type, $student_id, $session, $exam_type, $student_id]);
        $results = $stmt->fetchAll();

        echo "Results count: " . count($results) . "\n";
        echo "Results array:\n";
        foreach ($results as $i => $result) {
            echo "  [$i] {$result['subject_name']} (Grade: {$result['grade']})\n";
        }

        // Check if results array is empty
        if (empty($results)) {
            echo "\nERROR: Results array is empty!\n";
        }
    } else {
        echo "Student not found!\n";
    }
} else {
    echo "Condition not met - missing parameters\n";
}
?>

