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

$student_id = 6192;
$session = 2025;
$exam_type = 'test';

// Get student details
$stmt = $pdo->prepare("
    SELECT s.*, c.name as class_name, c.section, c.id as class_id
    FROM students s 
    JOIN classes c ON s.class_id = c.id 
    WHERE s.id = ?
");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

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

echo "Student: " . $student['first_name'] . " " . $student['last_name'] . " (ID: " . $student['id'] . ")\n";
echo "Class: " . $student['class_name'] . " " . $student['section'] . " (ID: " . $student['class_id'] . ")\n\n";

// Get results for the student - FIXED to avoid duplicates
$stmt = $pdo->prepare("
    SELECT r.*, sub.name as subject_name, sub.code as subject_code, sub.id as subject_id
    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();

echo "Results (after deduplication):\n";
foreach ($results as $result) {
    echo $result['subject_name'] . " (ID: " . $result['subject_id'] . ") - Marks: " . $result['marks_obtained'] . " - Grade: " . $result['grade'] . " - CQ: " . $result['cq_marks'] . " - MCQ: " . $result['mcq_marks'] . "\n";
}

// Group Bangla and English subjects together
$grouped_results = [];
$combined_subjects = [];
$bangla_results = [];
$english_results = [];

foreach ($results as $result) {
    // Check if this is a Bangla subject (Bangla or Bangla Grammar)
    if (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) {
        $bangla_results[] = $result;
    }
    // Check if this is an English subject (English or English Grammar)
    else if (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) {
        $english_results[] = $result;
    }
    // For other subjects, add directly
    else {
        $grouped_results[] = $result;
    }
}

echo "\nBangla Results:\n";
foreach ($bangla_results as $result) {
    echo $result['subject_name'] . " - Marks: " . $result['marks_obtained'] . " - Grade: " . $result['grade'] . " - CQ: " . $result['cq_marks'] . " - MCQ: " . $result['mcq_marks'] . "\n";
}

echo "\nEnglish Results:\n";
foreach ($english_results as $result) {
    echo $result['subject_name'] . " - Marks: " . $result['marks_obtained'] . " - Grade: " . $result['grade'] . " - CQ: " . $result['cq_marks'] . " - MCQ: " . $result['mcq_marks'] . "\n";
}

// Store the original results for use in maximum marks calculation
$original_bangla_results = $bangla_results;
$original_english_results = $english_results;

// Process Bangla subjects as a combined subject
if (!empty($bangla_results)) {
    // Combine Bangla and Bangla Grammar into one subject
    $combined_bangla = combineBanglaSubjects($bangla_results);
    // Use localized name for combined Bangla
    $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';
    $combined_bangla['subject_id'] = 'combined_bangla';
    $combined_subjects[] = $combined_bangla;
    
    echo "\nCombined Bangla Subject:\n";
    echo "Name: " . $combined_bangla['subject_name'] . "\n";
    echo "Marks: " . $combined_bangla['marks_obtained'] . "\n";
    echo "CQ Marks Array: " . json_encode($combined_bangla['cq_marks_array']) . "\n";
    echo "MCQ Marks: " . $combined_bangla['mcq_marks'] . "\n";
}

// Process English subjects as a combined subject
if (!empty($english_results)) {
    // Combine English and English Grammar into one subject
    $combined_english = combineEnglishSubjects($english_results);
    // Use localized name for combined English
    $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';
    $combined_english['subject_id'] = 'combined_english';
    $combined_subjects[] = $combined_english;
    
    echo "\nCombined English Subject:\n";
    echo "Name: " . $combined_english['subject_name'] . "\n";
    echo "Marks: " . $combined_english['marks_obtained'] . "\n";
    echo "CQ Marks Array: " . json_encode($combined_english['cq_marks_array']) . "\n";
    echo "MCQ Marks: " . $combined_english['mcq_marks'] . "\n";
}

// Combine subjects should appear first, then other subjects
$results = array_merge($combined_subjects, $grouped_results);

echo "\nAll Results After Combination:\n";
foreach ($results as $result) {
    echo $result['subject_name'] . " (ID: " . (isset($result['subject_id']) ? $result['subject_id'] : 'N/A') . ") - Marks: " . $result['marks_obtained'] . " - Grade: " . $result['grade'] . "\n";
}

// Enhance results with fourth subject information
foreach ($results as &$result) {
    // Check if this subject is a fourth subject
    if ($result['subject_id'] == 'combined_bangla') {
        // For combined Bangla, check if any of the original Bangla subjects is a fourth subject
        $is_fourth_subject = false;
        foreach ($original_bangla_results as $bangla_result) {
            $stmt = $pdo->prepare("
                SELECT is_fourth_subject 
                FROM student_subjects 
                WHERE student_id = ? AND subject_id = ?
                LIMIT 1
            ");
            $stmt->execute([$student_id, $bangla_result['subject_id']]);
            $subject_info = $stmt->fetch();
            if ($subject_info && $subject_info['is_fourth_subject']) {
                $is_fourth_subject = true;
                break;
            }
        }
        $result['is_fourth_subject'] = $is_fourth_subject;
        echo $result['subject_name'] . " - Fourth Subject: " . ($is_fourth_subject ? 'Yes' : 'No') . "\n";
    } else if ($result['subject_id'] == 'combined_english') {
        // For combined English, check if any of the original English subjects is a fourth subject
        $is_fourth_subject = false;
        foreach ($original_english_results as $english_result) {
            $stmt = $pdo->prepare("
                SELECT is_fourth_subject 
                FROM student_subjects 
                WHERE student_id = ? AND subject_id = ?
                LIMIT 1
            ");
            $stmt->execute([$student_id, $english_result['subject_id']]);
            $subject_info = $stmt->fetch();
            if ($subject_info && $subject_info['is_fourth_subject']) {
                $is_fourth_subject = true;
                break;
            }
        }
        $result['is_fourth_subject'] = $is_fourth_subject;
        echo $result['subject_name'] . " - Fourth Subject: " . ($is_fourth_subject ? 'Yes' : 'No') . "\n";
    } else {
        // For regular subjects
        $stmt = $pdo->prepare("
            SELECT is_fourth_subject 
            FROM student_subjects 
            WHERE student_id = ? AND subject_id = ?
            LIMIT 1
        ");
        $stmt->execute([$student_id, $result['subject_id']]);
        $subject_info = $stmt->fetch();
        
        $result['is_fourth_subject'] = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
        echo $result['subject_name'] . " - Fourth Subject: " . ($result['is_fourth_subject'] ? 'Yes' : 'No') . "\n";
    }
    
    // Apply custom grading for combined Bangla and English subjects
    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
        // For combined Bangla: CQ average > 22 AND MCQ average > 9 to pass
        $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
        $result['grade'] = $custom_grade;
        $result['grade_point'] = getGradePoint($custom_grade);
        echo $result['subject_name'] . " - Custom Grade: " . $custom_grade . " - GP: " . $result['grade_point'] . "\n";
    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
        // For combined English: CQ average > 32 to pass
        $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'], $result['pass_marks']);
        $result['grade'] = $custom_grade;
        $result['grade_point'] = getGradePoint($custom_grade);
        echo $result['subject_name'] . " - Custom Grade: " . $custom_grade . " - GP: " . $result['grade_point'] . "\n";
    } else {
        // Add subject-based GP (Grade Point)
        $result['grade_point'] = getGradePoint($result['grade']);
        echo $result['subject_name'] . " - Grade: " . $result['grade'] . " - GP: " . $result['grade_point'] . "\n";
    }
}
unset($result); // Break the reference with the last element

// Calculate totals and GPA with Jessore Board 4th subject rules
$total_marks = 0;
$total_obtained = 0;
$total_subjects = count($results);
$passed_subjects = 0;
$total_grade_points = 0;
$gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects)
$has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
$fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
$fourth_subject_found = false; // Track if 4th subject exists

echo "\nGPA Calculation:\n";
foreach ($results as $result) {
    $total_marks += 100; // Assuming full marks is 100 for each subject
    $total_obtained += $result['marks_obtained'];
    
    // Check if student failed in this subject and it's not a fourth subject
    if ($result['grade'] == 'F' && !$result['is_fourth_subject']) {
        $has_failed_in_non_fourth_subject = true;
        echo $result['subject_name'] . " - Failed in non-fourth subject\n";
    }
    
    if ($result['grade'] != 'F') {
        $passed_subjects++;
        
        // Handle 4th subject GPA adjustment according to Jessore Board rules
        if ($result['is_fourth_subject']) {
            $fourth_subject_found = true;
            $fourth_subject_grade_point = $result['grade_point'];
            // For 4th subject: if GPA > 2.00, subtract 2.00, otherwise subtract 0
            $adjusted_grade_point = ($result['grade_point'] > 2.00) ? ($result['grade_point'] - 2.00) : $result['grade_point'];
            $total_grade_points += $adjusted_grade_point;
            echo $result['subject_name'] . " (Fourth Subject) - GP: " . $result['grade_point'] . " - Adjusted GP: " . $adjusted_grade_point . "\n";
        } else {
            // Regular subject - add full grade point
            $total_grade_points += $result['grade_point'];
            echo $result['subject_name'] . " - GP: " . $result['grade_point'] . "\n";
        }
        $gpa_subjects++; // Count subjects for GPA calculation
    } else {
        echo $result['subject_name'] . " - Failed (GP: 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 "Total Marks: " . $total_marks . "\n";
echo "Total Obtained: " . $total_obtained . "\n";
echo "Percentage: " . $percentage . "%\n";
echo "Total Grade Points: " . $total_grade_points . "\n";
echo "GPA Subjects: " . $gpa_subjects . "\n";
echo "Has Fourth Subject: " . ($fourth_subject_found ? 'Yes' : 'No') . "\n";
echo "Failed in Non-Fourth Subject: " . ($has_failed_in_non_fourth_subject ? 'Yes' : 'No') . "\n";

// If student failed in any non-fourth subject, overall grade is F and GPA is 0
if ($has_failed_in_non_fourth_subject) {
    $overall_grade = 'F';
    $gpa = 0.00;
    echo "Final Result: Failed (due to failing in non-fourth subject)\n";
    echo "GPA: " . $gpa . "\n";
} else {
    $overall_grade = calculateOverallGrade($percentage, $passed_subjects, $total_subjects);
    
    // Calculate GPA (Grade Point Average) with Jessore Board rules
    if ($gpa_subjects > 0) {
        // For Jessore Board: if 6 subjects including 4th subject, divide by 5
        // Otherwise, use normal calculation
        if ($total_subjects >= 6 && $fourth_subject_found) {
            // When there are 6 or more subjects and 4th subject exists, divide by (total_subjects - 1)
            $gpa = round($total_grade_points / ($total_subjects - 1), 2);
            echo "Using Jessore Board rule: Dividing by " . ($total_subjects - 1) . "\n";
        } else {
            // Normal calculation
            $gpa = round($total_grade_points / $gpa_subjects, 2);
            echo "Using normal calculation: Dividing by " . $gpa_subjects . "\n";
        }
    } else {
        $gpa = 0.00; // GPA is 0.00 if all subjects are failed
    }
    
    echo "Final Result: " . $overall_grade . "\n";
    echo "GPA: " . $gpa . "\n";
}

// Function to combine Bangla subjects
function combineBanglaSubjects($bangla_results) {
    if (empty($bangla_results)) return null;
    
    // If only one Bangla subject, return it as is but mark it as combined
    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_bangla';
        return $result;
    }
    
    // For multiple Bangla subjects, combine them
    $combined = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all Bangla subjects
    foreach ($bangla_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual 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);
    }
    
    // Average the marks for proper grading
    $count = count($bangla_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count;
        $combined['marks_obtained'] = $combined['marks_obtained'] / $count;
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

// Function to combine English subjects
function combineEnglishSubjects($english_results) {
    if (empty($english_results)) return null;
    
    // If only one English subject, return it as is but mark it as combined
    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_english';
        return $result;
    }
    
    // For multiple English subjects, combine them
    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all English subjects
    foreach ($english_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual 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);
    }
    
    // Average the marks for proper grading
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count;
        $combined['marks_obtained'] = $combined['marks_obtained'] / $count;
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

function calculateOverallGrade($percentage, $passed_subjects, $total_subjects) {
    // If failed in any subject, overall grade is F
    if ($passed_subjects < $total_subjects) {
        return 'F';
    }
    
    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';
}

function calculateBanglaGrade($cq_marks_array, $mcq_marks, $total_marks, $pass_marks) {
    // Calculate average of CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 1) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }
    
    // For Bangla: CQ average > 22 AND MCQ > 9 to pass
    if ($cq_average > 22 && $mcq_marks > 9) {
        // Calculate overall marks
        $overall_marks = $cq_average + $mcq_marks;
        
        // Calculate percentage based on total 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 {
        // If criteria not met, return F
        return 'F';
    }
}

function calculateEnglishGrade($cq_marks_array, $total_marks, $pass_marks) {
    // Calculate average of CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 1) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }
    
    // For English: CQ average > 32 to pass
    if ($cq_average > 32) {
        // Calculate percentage based on total marks (using CQ marks only for English)
        $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 {
        // If criteria not met, return F
        return 'F';
    }
}

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;
    }
}
?>