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

error_log("=== DEBUG: GPA Calculation ===\n\n", 3, "debug_gpa.log");

function getGradePoint($grade) {
    switch ($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;
    }
}

function calculateGPA_debug($results, $student_id) {
    error_log("Calculating GPA for student $student_id\n", 3, "debug_gpa.log");
    $total_grade_points = 0;
    $gpa_subjects = 0; 
    $has_failed_in_non_fourth_subject = false; 
    $fourth_subject_grade_point = 0; 
    $fourth_subject_found = false; 
    
    foreach ($results as $result) {
        $subject_name = $result['subject_name'];
        error_log("  Processing subject: $subject_name\n", 3, "debug_gpa.log");
        if (($result['grade'] ?? '') != 'F') {
            $grade_point = $result['grade_point'] ?? 0.00;
            error_log("    Grade: " . $result['grade'] . ", Grade Point: $grade_point\n", 3, "debug_gpa.log");
            
            if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $grade_point;
                error_log("    This is a 4th subject.\n", 3, "debug_gpa.log");
                if ($grade_point > 2.00) {
                    $bonus = $grade_point - 2.00;
                    $total_grade_points += $bonus;
                    error_log("    Bonus points: $bonus. Total points: $total_grade_points\n", 3, "debug_gpa.log");
                }
            } else {
                $total_grade_points += $grade_point;
                $gpa_subjects++;
                error_log("    Regular subject. Total points: $total_grade_points, GPA subjects: $gpa_subjects\n", 3, "debug_gpa.log");
            }
        } else {
            error_log("    Grade is F.\n", 3, "debug_gpa.log");
            if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                $has_failed_in_non_fourth_subject = true;
                error_log("    Failed in a non-fourth subject.\n", 3, "debug_gpa.log");
            }
        }
    }
    
    if ($has_failed_in_non_fourth_subject) {
        error_log("  Student has failed in a non-fourth subject. GPA is 0.00\n", 3, "debug_gpa.log");
        return 0.00;
    }
    
    if ($gpa_subjects == 0) {
        error_log("  No subjects for GPA calculation. GPA is 0.00\n", 3, "debug_gpa.log");
        return 0.00;
    }
    
    if ($fourth_subject_found) {
        $gpa = $total_grade_points / $gpa_subjects;
        error_log("  4th subject found. GPA = $total_grade_points / $gpa_subjects = $gpa\n", 3, "debug_gpa.log");
    } else {
        $gpa = $total_grade_points / $gpa_subjects;
        error_log("  No 4th subject. GPA = $total_grade_points / $gpa_subjects = $gpa\n", 3, "debug_gpa.log");
    }
    
    if ($gpa > 5.00) {
        $gpa = 5.00;
        error_log("  GPA capped at 5.00\n", 3, "debug_gpa.log");
    }
    
    $final_gpa = round($gpa, 2);
    error_log("  Final GPA: $final_gpa\n", 3, "debug_gpa.log");
    return $final_gpa;
}

$student_id = 6279;
$session = '2025';
$exam_type = 'test';
$class_id = 10;

// Get results for the student - FIXED to avoid duplicates
$stmt = $pdo->prepare(
    "SELECT r.*, sub.name as subject_name, sub.code as subject_code, ss.is_fourth_subject\n    FROM results r\n    LEFT JOIN subjects sub ON r.subject_id = sub.id\n    LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_id\n    WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?\n    AND r.id IN (\n        SELECT MAX(id)\n        FROM results\n        WHERE student_id = ? AND session = ? AND exam_type = ?\n        GROUP BY subject_id\n    )\n    ORDER BY sub.name\n");
$stmt->execute([$student_id, $session, $exam_type, $student_id, $session, $exam_type]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process results to calculate grades and grade points
foreach ($results as &$result) {
    $result['marks_obtained'] = ($result['cq_marks'] ?? 0) + ($result['mcq_marks'] ?? 0) +
                               ($result['practical_marks'] ?? 0) + ($result['assignment_marks'] ?? 0) +
                               ($result['attendance_marks'] ?? 0);

    $stmt_dist = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
    $stmt_dist->execute([$result['subject_id'], $class_id, $session, $exam_type]);
    $smd = $stmt_dist->fetch();

    if ($smd) {
        $result['full_marks'] = $smd['total_marks'];
        $result['pass_marks'] = $smd['overall_pass_marks'];
    } else {
        $result['full_marks'] = 100;
        $result['pass_marks'] = 33;
    }
    
    if ($result['marks_obtained'] >= ($result['full_marks'] * 0.8)) {
        $effective_grade = 'A+';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.7)) {
        $effective_grade = 'A';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.6)) {
        $effective_grade = 'A-';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.5)) {
        $effective_grade = 'B';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.4)) {
        $effective_grade = 'C';
    } elseif ($result['marks_obtained'] >= $result['pass_marks']) {
        $effective_grade = 'D';
    } else {
        $effective_grade = 'F';
    }

    $result['grade'] = $effective_grade;
    $result['grade_point'] = getGradePoint($effective_grade);

    $result['is_fourth_subject'] = $result['is_fourth_subject'] ?? false;
}
unset($result); 

$gpa = calculateGPA_debug($results, $student_id);

echo "GPA for student $student_id is: $gpa\n";

?>