<?php
session_start();
require_once 'config/database.php';

$student_roll = '20250020';
$class_id = 10;
$session = 2025;
$exam_type = 'final';

echo "<h2>Debugging Student Grade Issue</h2>\n";
echo "<p>Student Roll: $student_roll</p>\n";
echo "<p>Class ID: $class_id</p>\n";
echo "<p>Session: $session</p>\n";
echo "<p>Exam Type: " . htmlspecialchars($exam_type) . "</p>\n";

// Get student info
$stmt = $pdo->prepare("
    SELECT s.* FROM students s 
    WHERE s.student_id = ? AND s.class_id = ? AND s.status = 'active'
");
$stmt->execute([$student_roll, $class_id]);
$student = $stmt->fetch();

if (!$student) {
    echo "<p>Student not found!</p>\n";
    exit();
}

echo "<h3>Student Info:</h3>\n";
echo "<p>Name: " . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . "</p>\n";
echo "<p>ID: " . $student['id'] . "</p>\n";
echo "<p>Roll: " . $student['student_id'] . "</p>\n";

// Get student's subjects
$stmt = $pdo->prepare("
    SELECT sub.id, sub.name, sub.code
    FROM student_subjects ss
    JOIN subjects sub ON ss.subject_id = sub.id
    WHERE ss.student_id = ?
    ORDER BY sub.name
");
$stmt->execute([$student['id']]);
$student_subjects = $stmt->fetchAll();

echo "<h3>Student's Subjects (" . count($student_subjects) . "):</h3>\n";
echo "<ul>\n";
foreach ($student_subjects as $subj) {
    echo "<li>" . htmlspecialchars($subj['name']) . " (ID: " . $subj['id'] . ", Code: " . $subj['code'] . ")</li>\n";
}
echo "</ul>\n";

// Get student's results
$stmt = $pdo->prepare("
    SELECT r.*, sub.name as subject_name
    FROM results r
    JOIN subjects sub ON r.subject_id = sub.id
    WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
    ORDER BY sub.name
");
$stmt->execute([$student['id'], $session, $exam_type]);
$results = $stmt->fetchAll();

echo "<h3>Student's Results (" . count($results) . "):</h3>\n";
if (empty($results)) {
    echo "<p>No results found for this student in session $session and exam type '" . htmlspecialchars($exam_type) . "'</p>\n";
} else {
    echo "<table border='1'>\n";
    echo "<tr><th>Subject</th><th>Marks Obtained</th><th>Grade</th><th>Grade Point</th><th>4th Subject</th></tr>\n";
    
    $total_grade_points = 0;
    $gpa_subjects = 0;
    $fourth_subject_found = false;
    $fourth_subject_grade_point = 0;
    
    foreach ($results as $result) {
        // Check if this subject is a fourth subject
        $stmt_check = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
        $stmt_check->execute([$student['id'], $result['subject_id']]);
        $subject_info = $stmt_check->fetch();
        $is_fourth_subject = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
        
        if ($is_fourth_subject) {
            $fourth_subject_found = true;
            $fourth_subject_grade_point = getGradePoint($result['grade']);
        }
        
        echo "<tr>";
        echo "<td>" . htmlspecialchars($result['subject_name']) . "</td>";
        echo "<td>" . $result['marks_obtained'] . "</td>";
        echo "<td>" . $result['grade'] . "</td>";
        echo "<td>" . getGradePoint($result['grade']) . "</td>";
        echo "<td>" . ($is_fourth_subject ? 'YES' : 'NO') . "</td>";
        echo "</tr>\n";
        
        // Add to GPA calculation if not failed and not fourth subject
        if ($result['grade'] != 'F') {
            if ($is_fourth_subject) {
                // Fourth subject points are handled separately
            } else {
                $total_grade_points += getGradePoint($result['grade']);
                $gpa_subjects++;
            }
        }
    }
    
    echo "</table>\n";
    
    // Calculate GPA according to Jessore Board rules
    echo "<h3>GPA Calculation:</h3>\n";
    echo "<p>Total Grade Points: $total_grade_points</p>\n";
    echo "<p>GPA Subjects (excluding failed and 4th): $gpa_subjects</p>\n";
    echo "<p>Fourth Subject Found: " . ($fourth_subject_found ? 'YES' : 'NO') . "</p>\n";
    
    if ($fourth_subject_found) {
        echo "<p>Fourth Subject Grade Point: $fourth_subject_grade_point</p>\n";
        $adjusted_grade_point = ($fourth_subject_grade_point > 2.00) ? ($fourth_subject_grade_point - 2.00) : $fourth_subject_grade_point;
        echo "<p>Adjusted Fourth Subject Point: $adjusted_grade_point</p>\n";
        $total_grade_points += $adjusted_grade_point;
        echo "<p>Total Points with 4th subject adjustment: $total_grade_points</p>\n";
    }
    
    if ($gpa_subjects > 0) {
        if ($fourth_subject_found) {
            // When 4th subject exists, divide by (gpa_subjects)
            $gpa = ($gpa_subjects > 0) ? round($total_grade_points / $gpa_subjects, 2) : 0.00;
        } else {
            // Normal calculation
            $gpa = round($total_grade_points / $gpa_subjects, 2);
        }
        echo "<p>Calculated GPA: $gpa</p>\n";
    } else {
        echo "<p>GPA: 0.00 (No passing subjects)</p>\n";
    }
}

// Grade point function (copied from the system)
function getGradePoint($grade) {
    switch (strtoupper($grade)) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        case 'F': return 0.00;
        default: return 0.00;
    }
}

echo "<p><a href='reports/tabulation_sheet.php?class_id=$class_id&session=$session&exam_type=" . urlencode($exam_type) . "'>View Tabulation Sheet</a></p>\n";
?>