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

// Function to get grade point
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;
        default: return 0.00;
    }
}

// Simulate marksheet GPA calculation for student 6279
$student_id = 6279;
$session = 2025;
$exam_type = 'final';

echo "Debugging marksheet GPA calculation for student $student_id...\n\n";

// Get student
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

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

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

// Group subjects
$combined_subjects = [];
$bangla_results = [];
$english_results = [];
$other_results = [];

foreach ($results as $result) {
    $is_bangla = false;
    if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
        stripos($result['subject_name'], 'History') === false &&
        stripos($result['subject_name'], 'Introduction') === false) {
        $is_bangla = true;
    }
    if ($is_bangla) {
        $bangla_results[] = $result;
    }
    else if ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
             stripos($result['subject_name'], 'Literature') === false) {
        $english_results[] = $result;
    }
    else {
        $other_results[] = $result;
    }
}

// Combine Bangla
if (!empty($bangla_results)) {
    $combined_bangla = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F', // Default
        'grade_point' => 0.00
    ];

    foreach ($bangla_results as $result) {
        $combined_bangla['cq_marks'] += $result['cq_marks'];
        $combined_bangla['cq_marks_array'][] = $result['cq_marks'];
        $combined_bangla['mcq_marks'] += $result['mcq_marks'];
        $combined_bangla['mcq_marks_array'][] = $result['mcq_marks'];
        $combined_bangla['practical_marks'] += $result['practical_marks'];
        $combined_bangla['assignment_marks'] += $result['assignment_marks'];
        $combined_bangla['attendance_marks'] += $result['attendance_marks'];
        $combined_bangla['marks_obtained'] += $result['marks_obtained'];
        $combined_bangla['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined_bangla['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }

    $count = count($bangla_results);
    if ($count > 0) {
        $combined_bangla['cq_marks'] = $combined_bangla['cq_marks'] / $count;
        $combined_bangla['mcq_marks'] = $combined_bangla['mcq_marks'] / $count;
        $combined_bangla['full_marks'] = $combined_bangla['full_marks'] / $count;
        $combined_bangla['pass_marks'] = $combined_bangla['pass_marks'] / $count;
    }

    $combined_subjects[] = $combined_bangla;
    // Combined subjects are not fourth subjects
    $combined_bangla['is_fourth_subject'] = false;
}

// Combine English
if (!empty($english_results)) {
    $combined_english = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F', // Default
        'grade_point' => 0.00
    ];

    foreach ($english_results as $result) {
        $combined_english['cq_marks'] += $result['cq_marks'];
        $combined_english['cq_marks_array'][] = $result['cq_marks'];
        $combined_english['mcq_marks'] += $result['mcq_marks'];
        $combined_english['mcq_marks_array'][] = $result['mcq_marks'];
        $combined_english['practical_marks'] += $result['practical_marks'];
        $combined_english['assignment_marks'] += $result['assignment_marks'];
        $combined_english['attendance_marks'] += $result['attendance_marks'];
        $combined_english['marks_obtained'] += $result['marks_obtained'];
        $combined_english['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined_english['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }

    $count = count($english_results);
    if ($count > 0) {
        $combined_english['cq_marks'] = $combined_english['cq_marks'] / $count;
        $combined_english['mcq_marks'] = $combined_english['mcq_marks'] / $count;
        $combined_english['full_marks'] = $combined_english['full_marks'] / $count;
        $combined_english['pass_marks'] = $combined_english['pass_marks'] / $count;
    }

    $combined_subjects[] = $combined_english;
    // Combined subjects are not fourth subjects
    $combined_english['is_fourth_subject'] = false;
}

// Merge results
$results = array_merge($combined_subjects, $other_results);

// Ensure all subjects have required fields and grade_point calculated
foreach ($results as &$result) {
    // Add subject-based GP (Grade Point) - this should happen for all subjects
    $result['grade_point'] = getGradePoint($result['grade']);
}

// Apply custom grading (this overrides grade_point for combined subjects)
foreach ($results as &$result) {
    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
        // Calculate Bangla grade using subject-wise setup
        $cq_average = 0;
        if (count($result['cq_marks_array']) >= 2) {
            $cq_average = ($result['cq_marks_array'][0] + $result['cq_marks_array'][1]) / 2;
        } else if (count($result['cq_marks_array']) == 1) {
            $cq_average = $result['cq_marks_array'][0];
        }

        // Get pass marks from setup (use first Bangla subject ID)
        $bangla_subject_id = !empty($bangla_results) ? $bangla_results[0]['subject_id'] : null;
        $cq_pass = 22; // default
        $mcq_pass = 9;  // default

        if ($bangla_subject_id) {
            $stmt = $pdo->prepare("SELECT cq_pass_marks, mcq_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
            $stmt->execute([$bangla_subject_id, $student['class_id'], $session, $exam_type]);
            $setup = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($setup) {
                $cq_pass = $setup['cq_pass_marks'] ?? 22;
                $mcq_pass = $setup['mcq_pass_marks'] ?? 9;
            }
        }

        if ($cq_average > $cq_pass && $result['mcq_marks'] > $mcq_pass) {
            $overall_marks = $cq_average + $result['mcq_marks'];
            $percentage = ($overall_marks / $result['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';
        }

        $result['grade'] = $grade;
        $result['grade_point'] = $grade == 'A+' ? 5.00 : ($grade == 'A' ? 4.00 : ($grade == 'A-' ? 3.50 : ($grade == 'B' ? 3.00 : ($grade == 'C' ? 2.00 : ($grade == 'D' ? 1.00 : 0.00)))));
        echo "Combined Bangla: CQ avg=$cq_average (> $cq_pass), MCQ={$result['mcq_marks']} (> $mcq_pass), Grade=$grade\n";

    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
        // Calculate English grade using subject-wise setup
        $cq_average = 0;
        if (count($result['cq_marks_array']) >= 2) {
            $cq_average = ($result['cq_marks_array'][0] + $result['cq_marks_array'][1]) / 2;
        } else if (count($result['cq_marks_array']) == 1) {
            $cq_average = $result['cq_marks_array'][0];
        }

        // Get pass marks from setup (use first English subject ID)
        $english_subject_id = !empty($english_results) ? $english_results[0]['subject_id'] : null;
        $cq_pass = 32; // default

        if ($english_subject_id) {
            $stmt = $pdo->prepare("SELECT cq_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
            $stmt->execute([$english_subject_id, $student['class_id'], $session, $exam_type]);
            $setup = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($setup) {
                $cq_pass = $setup['cq_pass_marks'] ?? 32;
            }
        }

        if ($cq_average > $cq_pass) {
            $percentage = ($cq_average / $result['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';
        }

        $result['grade'] = $grade;
        $result['grade_point'] = $grade == 'A+' ? 5.00 : ($grade == 'A' ? 4.00 : ($grade == 'A-' ? 3.50 : ($grade == 'B' ? 3.00 : ($grade == 'C' ? 2.00 : ($grade == 'D' ? 1.00 : 0.00)))));
        echo "Combined English: CQ avg=$cq_average (> $cq_pass), Grade=$grade\n";
    }
}

// Now calculate GPA
$total_marks = 0;
$total_obtained = 0;
$total_subjects = count($results);
$passed_subjects = 0;
$total_grade_points = 0;
$gpa_subjects = 0;
$has_failed_in_non_fourth_subject = false;
$fourth_subject_found = false;

foreach ($results as $result) {
    $total_marks += $result['full_marks'];
    $total_obtained += $result['marks_obtained'];

    // Check if this subject is a fourth subject
    $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ?");
    $stmt->execute([$student_id, $result['subject_id']]);
    $subject_info = $stmt->fetch();
    $is_fourth_subject = $subject_info && $subject_info['is_fourth_subject'] ? true : false;

    if ($result['grade'] == 'F' && !$is_fourth_subject) {
        $has_failed_in_non_fourth_subject = true;
        echo "FAILED in non-fourth subject: {$result['subject_name']} (Grade: {$result['grade']})\n";
    }

    if ($result['grade'] != 'F') {
        $passed_subjects++;

        if ($is_fourth_subject) {
            $fourth_subject_found = true;
            $adjusted_grade_point = ($result['grade_point'] > 2.00) ? 2.00 : $result['grade_point'];
            $total_grade_points += $adjusted_grade_point;
            echo "4th subject {$result['subject_name']}: Grade={$result['grade']}, Points added=$adjusted_grade_point\n";
        } else {
            $total_grade_points += $result['grade_point'];
            echo "Regular subject {$result['subject_name']}: Grade={$result['grade']}, Points added={$result['grade_point']}\n";
        }
        $gpa_subjects++;
    } else {
        echo "Failed subject {$result['subject_name']}: Grade={$result['grade']}, Points added=0\n";
    }
}

$percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;

echo "\nSummary:\n";
echo "Total subjects: $total_subjects\n";
echo "Passed subjects: $passed_subjects\n";
echo "GPA subjects: $gpa_subjects\n";
echo "Fourth subject found: " . ($fourth_subject_found ? 'Yes' : 'No') . "\n";
echo "Failed in non-fourth subject: " . ($has_failed_in_non_fourth_subject ? 'YES' : 'NO') . "\n";
echo "Total grade points: $total_grade_points\n";

if ($has_failed_in_non_fourth_subject) {
    $gpa = 0.00;
    echo "GPA: 0.00 (failed in non-fourth subject)\n";
} else {
    if ($gpa_subjects > 0) {
        if ($fourth_subject_found) {
            $gpa = $total_grade_points / ($gpa_subjects - 1);
        } else {
            $gpa = $total_grade_points / $gpa_subjects;
        }

        if ($fourth_subject_found && $gpa > 5.00) {
            $gpa = 5.00;
        }

        $gpa = round($gpa, 2);
        echo "GPA: $gpa\n";
    } else {
        echo "GPA: 0.00 (no subjects passed)\n";
    }
}
?>
