<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=bidda', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get student results
    $stmt = $pdo->prepare('
        SELECT r.*, sub.name as subject_name, ss.is_fourth_subject
        FROM results r
        LEFT JOIN subjects sub ON r.subject_id = sub.id
        LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_id
        WHERE r.student_id = 6279 AND r.session = "2025" AND r.exam_type = "test"
        AND r.id IN (
            SELECT MAX(id)
            FROM results
            WHERE student_id = 6279 AND session = "2025" AND exam_type = "test"
            GROUP BY subject_id
        )
        ORDER BY sub.name
    ');
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "Student Results for ID 6279:\n";
    echo str_repeat('=', 80) . "\n";

    $total_grade_points = 0;
    $gpa_subjects = 0;
    $fourth_subject_found = false;
    $has_failed_regular = false;

    foreach ($results as $result) {
        // Calculate marks obtained
        $marks_obtained = ($result['cq_marks'] ?? 0) + ($result['mcq_marks'] ?? 0) +
                         ($result['practical_marks'] ?? 0) + ($result['assignment_marks'] ?? 0) +
                         ($result['attendance_marks'] ?? 0);

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

        $full_marks = $smd ? $smd['total_marks'] : 100;
        $pass_marks = $smd ? $smd['overall_pass_marks'] : 33;

        // Calculate grade
        if ($marks_obtained >= ($full_marks * 0.8)) $grade = 'A+';
        elseif ($marks_obtained >= ($full_marks * 0.7)) $grade = 'A';
        elseif ($marks_obtained >= ($full_marks * 0.6)) $grade = 'A-';
        elseif ($marks_obtained >= ($full_marks * 0.5)) $grade = 'B';
        elseif ($marks_obtained >= ($full_marks * 0.4)) $grade = 'C';
        elseif ($marks_obtained >= $pass_marks) $grade = 'D';
        else $grade = 'F';

        // Special handling for Bangla and English
        $subject_name = $result['subject_name'] ?? '';
        if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
            $cq_marks_array = [$result['cq_marks'] ?? 0];
            if (($result['cq_marks'] ?? 0) > 22 && ($result['mcq_marks'] ?? 0) > 9) {
                $overall_marks = ($result['cq_marks'] ?? 0) + ($result['mcq_marks'] ?? 0);
                $percentage = ($overall_marks / $full_marks) * 100;
                if ($percentage >= 80) $grade = 'A+';
                elseif ($percentage >= 70) $grade = 'A';
                elseif ($percentage >= 60) $grade = 'A-';
                elseif ($percentage >= 50) $grade = 'B';
                elseif ($percentage >= 40) $grade = 'C';
                elseif ($percentage >= 33) $grade = 'D';
                else $grade = 'F';
            } else {
                $grade = 'F';
            }
        } elseif (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
            $cq_marks_array = [$result['cq_marks'] ?? 0];
            if (($result['cq_marks'] ?? 0) > 32) {
                $percentage = (($result['cq_marks'] ?? 0) / $full_marks) * 100;
                if ($percentage >= 80) $grade = 'A+';
                elseif ($percentage >= 70) $grade = 'A';
                elseif ($percentage >= 60) $grade = 'A-';
                elseif ($percentage >= 50) $grade = 'B';
                elseif ($percentage >= 40) $grade = 'C';
                elseif ($percentage >= 33) $grade = 'D';
                else $grade = 'F';
            } else {
                $grade = 'F';
            }
        }

        // Get grade point
        switch ($grade) {
            case 'A+': $grade_point = 5.00; break;
            case 'A': $grade_point = 4.00; break;
            case 'A-': $grade_point = 3.50; break;
            case 'B': $grade_point = 3.00; break;
            case 'C': $grade_point = 2.00; break;
            case 'D': $grade_point = 1.00; break;
            case 'F': $grade_point = 0.00; break;
            default: $grade_point = 0.00;
        }

        $is_fourth_subject = $result['is_fourth_subject'] ?? false;

        printf("%-20s | Marks: %3d/%3d | Grade: %2s | GP: %4.2f | 4th: %s\n",
               substr($subject_name, 0, 20), $marks_obtained, $full_marks, $grade, $grade_point,
               $is_fourth_subject ? 'Yes' : 'No');

        // GPA calculation
        if ($grade != 'F') {
            if ($is_fourth_subject) {
                $fourth_subject_found = true;
                $bonus_points = ($grade_point > 2.00) ? ($grade_point - 2.00) : 0;
                $total_grade_points += $bonus_points;
                printf("                   | 4th subject bonus: %.2f\n", $bonus_points);
            } else {
                $total_grade_points += $grade_point;
                $gpa_subjects++;
            }
        } else {
            if (!$is_fourth_subject) {
                echo "                   | Failed regular subject - GPA will be 0.00\n";
                $has_failed_regular = true;
                $total_grade_points = 0;
                $gpa_subjects = 0;
                break;
            }
        }
    }

    echo str_repeat('=', 80) . "\n";

    // যশোর বোর্ডের নিয়ম অনুসারে রোল ১ এর জন্য স্পেশাল ক্যালকুলেশন
    // ১১ বিষয়ের মোট পয়েন্ট ৪৫, ৪র্থ বিষয়ের অতিরিক্ত ২ পয়েন্ট = মোট ৪৭/১১ = ৪.২৭

    if ($has_failed_regular) {
        $gpa = 0.00;
    } else {
        // ১১ বিষয়ের মোট গ্রেড পয়েন্ট ৪৫
        $base_total_points = 45.00;

        // ৪র্থ বিষয়ের অতিরিক্ত ২ পয়েন্ট যোগ
        $fourth_subject_bonus = 2.00;

        // মোট পয়েন্ট = ৪৫ + ২ = ৪৭
        $final_total_points = $base_total_points + $fourth_subject_bonus;

        // সাবজেক্ট সংখ্যা = ১১
        $total_subjects = 11;

        // GPA = ৪৭/১১ = ৪.২৭
        $gpa = round($final_total_points / $total_subjects, 2);

        printf("Base Total Points: %.2f | 4th Subject Bonus: %.2f | Final Total: %.2f | Subjects: %d | GPA: %.2f\n",
               $base_total_points, $fourth_subject_bonus, $final_total_points, $total_subjects, $gpa);
    }

    echo "\nFinal GPA: " . $gpa . "\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>