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

$student_id = 6279;
$session = 2025;
$exam_type = 'final';

// Simulate the marksheet GPA calculation
echo "=== MARKSHEET GPA CALCULATION DEBUG ===\n\n";

// Get results using the same logic as the marksheet
$stmt = $pdo->prepare("
    SELECT
        COALESCE(r.id, NULL) as result_id,
        COALESCE(r.marks_obtained, 0) as marks_obtained,
        COALESCE(r.cq_marks, 0) as cq_marks,
        COALESCE(r.mcq_marks, 0) as mcq_marks,
        COALESCE(r.practical_marks, 0) as practical_marks,
        COALESCE(r.assignment_marks, 0) as assignment_marks,
        COALESCE(r.attendance_marks, 0) as attendance_marks,
        COALESCE(r.grade, 'F') as grade,
        COALESCE(r.remarks, '') as remarks,
        ss.subject_id,
        sub.name as subject_name,
        sub.code as subject_code,
        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_with_marks = $stmt->fetchAll();

// Process results (simplified)
$results = [];
foreach ($results_with_marks as $result) {
    $result['cq_marks_array'] = !empty($result['cq_marks']) ? [$result['cq_marks']] : [];
    $result['grade_point'] = getGradePoint($result['grade']);
    $results[] = $result;
}

// Group subjects (simplified)
$bangla_results = [];
$english_results = [];
$other_results = [];

foreach ($results as $result) {
    $subject_name = strtolower($result['subject_name']);
    $is_bangla = (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
                 stripos($result['subject_name'], 'History') === false &&
                 stripos($result['subject_name'], 'Introduction') === false;
    $is_english = (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                  stripos($result['subject_name'], 'Literature') === false;

    if ($is_bangla) {
        $bangla_results[] = $result;
    } else if ($is_english) {
        $english_results[] = $result;
    } else {
        $other_results[] = $result;
    }
}

// Create combined subjects
$combined_subjects = [];
if (!empty($bangla_results)) {
    $combined_bangla = combineBanglaSubjects($bangla_results);
    $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';
    $combined_subjects[] = $combined_bangla;
}
if (!empty($english_results)) {
    $combined_english = combineEnglishSubjects($english_results);
    $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';
    $combined_subjects[] = $combined_english;
}

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

// Apply custom grading for combined subjects
foreach ($results as &$result) {
    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
        $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'] ?? 100, $result['pass_marks'] ?? 33);
        $result['grade'] = $custom_grade;
        $result['grade_point'] = getGradePoint($custom_grade);
    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
        $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'] ?? 100, $result['pass_marks'] ?? 33);
        $result['grade'] = $custom_grade;
        $result['grade_point'] = getGradePoint($custom_grade);
    }
}
unset($result);

// GPA calculation with the fix
$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_grade_point = 0;
$fourth_subject_found = false;

// Check if combined subjects exist
$has_combined_bangla = false;
$has_combined_english = false;
foreach ($results as $check_result) {
    if ($check_result['subject_name'] == 'বাংলা(একত্রে)') {
        $has_combined_bangla = true;
    }
    if ($check_result['subject_name'] == 'ইংরেজি(একত্রে)') {
        $has_combined_english = true;
    }
}

echo "Subjects to process for GPA:\n";
foreach ($results as $result) {
    // Skip individual Bangla subjects if combined Bangla exists
    if ($has_combined_bangla && (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
        stripos($result['subject_name'], 'History') === false && stripos($result['subject_name'], 'Introduction') === false &&
        $result['subject_name'] != 'বাংলা(একত্রে)') {
        echo "SKIPPING: " . $result['subject_name'] . " (individual Bangla, combined exists)\n";
        continue;
    }

    // Skip individual English subjects if combined English exists
    if ($has_combined_english && (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
        stripos($result['subject_name'], 'Literature') === false && $result['subject_name'] != 'ইংরেজি(একত্রে)') {
        echo "SKIPPING: " . $result['subject_name'] . " (individual English, combined exists)\n";
        continue;
    }

    $total_marks += $result['full_marks'] ?? 100;
    $total_obtained += $result['marks_obtained'] ?? 0;

    $is_fourth = isset($result['is_fourth_subject']) && $result['is_fourth_subject'];

    echo "PROCESSING: " . $result['subject_name'] . " (grade: " . $result['grade'] . ", is_fourth: " . ($is_fourth ? 'yes' : 'no') . ", marks: " . ($result['marks_obtained'] ?? 0) . ")\n";

    if ($result['grade'] == 'F' && !$is_fourth && isset($result['marks_obtained']) && $result['marks_obtained'] > 0) {
        $has_failed_in_non_fourth_subject = true;
        echo "  *** FAILED in non-fourth subject: " . $result['subject_name'] . "\n";
    }

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

        if ($is_fourth) {
            $fourth_subject_found = true;
            if ($result['grade_point'] > 2.00) {
                $total_grade_points += ($result['grade_point'] - 2.00);
                echo "  Added " . ($result['grade_point'] - 2.00) . " points (4th subject bonus)\n";
            } else {
                echo "  Added 0 points (4th subject, no bonus)\n";
            }
        } else {
            $total_grade_points += $result['grade_point'];
            echo "  Added " . $result['grade_point'] . " points (regular subject)\n";
        }
        $gpa_subjects++;
    }
}

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

if ($has_failed_in_non_fourth_subject) {
    $overall_grade = 'F';
    $gpa = 0.00;
} else {
    $overall_grade = 'A+';
    if ($gpa_subjects > 0) {
        if ($fourth_subject_found) {
            $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
            $gpa = $total_grade_points / $divisor;
        } else {
            $gpa = $total_grade_points / $gpa_subjects;
        }

        if ($fourth_subject_found && $gpa > 5.00) {
            $gpa = 5.00;
        }
        if ($gpa > 5.00) {
            $gpa = 5.00;
        }
        $gpa = round($gpa, 2);
        $final_gpa = $gpa;
    } else {
        $gpa = 0.00;
        $final_gpa = $gpa;
    }
}

echo "\n=== FINAL RESULTS ===\n";
echo "Total Grade Points: $total_grade_points\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 "Final GPA: $gpa\n";
echo "GPA-based Grade: " . calculateGradeFromGPA($gpa) . "\n";

// Helper functions
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;
    }
}

function combineBanglaSubjects($bangla_results) {
    if (empty($bangla_results)) return null;

    $combined = [
        'subject_name' => 'বাংলা(একত্রে)',
        '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',
        'grade_point' => 0.00
    ];

    $considered_results = array_slice($bangla_results, 0, 2);

    foreach ($bangla_results as $result) {
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }

    $cq_total = 0;
    $mcq_total = 0;
    foreach ($considered_results as $result) {
        $cq_total += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks'];
        $mcq_total += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks'];
    }

    $count = count($considered_results);
    if ($count > 0) {
        $combined['cq_marks'] = $cq_total / $count;
        $combined['mcq_marks'] = $mcq_total / $count;
    }

    $total_marks_sum = 0;
    foreach ($bangla_results as $result) {
        $total_marks_sum += $result['marks_obtained'];
    }
    $combined['marks_obtained'] = $total_marks_sum;

    $total_count = count($bangla_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }

    return $combined;
}

function combineEnglishSubjects($english_results) {
    if (empty($english_results)) return null;

    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        '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',
        'grade_point' => 0.00
    ];

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

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

    return $combined;
}

function calculateBanglaGrade($cq_marks_array, $mcq_marks, $total_marks, $pass_marks) {
    $cq_average = 0;
    if (!empty($cq_marks_array)) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }

    if ($cq_average > 22 && $mcq_marks > 9) {
        $overall_marks = $cq_average + $mcq_marks;
        $percentage = ($overall_marks / $total_marks) * 100;

        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        return 'F';
    }
}

function calculateEnglishGrade($cq_marks_array, $total_marks, $pass_marks) {
    $cq_average = 0;
    if (!empty($cq_marks_array)) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }

    if ($cq_average > 32) {
        $percentage = ($cq_average / $total_marks) * 100;

        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        return 'F';
    }
}

function calculateGradeFromGPA($gpa) {
    if ($gpa >= 5.00) return 'A+';
    elseif ($gpa >= 4.00) return 'A';
    elseif ($gpa >= 3.50) return 'A-';
    elseif ($gpa >= 3.00) return 'B';
    elseif ($gpa >= 2.00) return 'C';
    elseif ($gpa >= 1.00) return 'D';
    else return 'F';
}
?>
