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

// Include the calculateGrade function from entry.php
function calculateGrade($obtained_marks, $total_marks, $mark_distribution = null, $individual_marks = []) {
    if ($total_marks == 0) return 'F';
    
    // Check individual passing marks if set
    if ($mark_distribution) {
        // Check CQ passing marks
        if (!empty($mark_distribution['cq_pass_marks']) && $mark_distribution['cq_marks'] > 0) {
            $cq_obtained = (float)($individual_marks['cq'] ?? 0);
            if ($cq_obtained < $mark_distribution['cq_pass_marks']) {
                return 'F'; // Failed in CQ
            }
        }
        
        // Check MCQ passing marks
        if (!empty($mark_distribution['mcq_pass_marks']) && $mark_distribution['mcq_marks'] > 0) {
            $mcq_obtained = (float)($individual_marks['mcq'] ?? 0);
            if ($mcq_obtained < $mark_distribution['mcq_pass_marks']) {
                return 'F'; // Failed in MCQ
            }
        }
        
        // Check Practical passing marks
        if (!empty($mark_distribution['practical_pass_marks']) && $mark_distribution['practical_marks'] > 0) {
            $practical_obtained = (float)($individual_marks['practical'] ?? 0);
            if ($practical_obtained < $mark_distribution['practical_pass_marks']) {
                return 'F'; // Failed in Practical
            }
        }
        
        // Check overall passing marks
        $overall_pass_marks = $mark_distribution['overall_pass_marks'] ?? $mark_distribution['pass_marks'] ?? ($total_marks * 0.4);
        if ($obtained_marks < $overall_pass_marks) {
            return 'F'; // Failed overall
        }
    }
    
    $percentage = ($obtained_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';
}

echo "=== Final Test: Individual Passing Marks ===\n\n";

try {
    // Get a real distribution from database
    $stmt = $pdo->query("
        SELECT smd.*, s.name as subject_name, c.name as class_name 
        FROM subject_mark_distribution smd
        JOIN subjects s ON smd.subject_id = s.id
        JOIN classes c ON smd.class_id = c.id
        WHERE smd.cq_pass_marks > 0 AND smd.mcq_pass_marks > 0
        LIMIT 1
    ");
    
    $real_dist = $stmt->fetch();
    
    if (!$real_dist) {
        // Try mark_distributions table
        $stmt = $pdo->query("
            SELECT md.*, s.name as subject_name, c.name as class_name 
            FROM mark_distributions md
            JOIN subjects s ON md.subject_id = s.id
            JOIN classes c ON md.class_id = c.id
            WHERE md.cq_pass_marks > 0 AND md.mcq_pass_marks > 0
            LIMIT 1
        ");
        $real_dist = $stmt->fetch();
    }
    
    if ($real_dist) {
        echo "Testing with real distribution:\n";
        echo "Subject: {$real_dist['subject_name']}\n";
        echo "Class: {$real_dist['class_name']}\n";
        echo "Exam Type: {$real_dist['exam_type']}\n";
        echo "CQ: {$real_dist['cq_marks']} (Pass: {$real_dist['cq_pass_marks']})\n";
        echo "MCQ: {$real_dist['mcq_marks']} (Pass: {$real_dist['mcq_pass_marks']})\n";
        echo "Practical: {$real_dist['practical_marks']} (Pass: " . ($real_dist['practical_pass_marks'] ?? 'N/A') . ")\n";
        echo "Overall Pass: {$real_dist['overall_pass_marks']}\n\n";
        
        // Test Case 1: Student fails in CQ
        echo "Test Case 1: Student fails in CQ but passes overall\n";
        $individual_marks1 = [
            'cq' => $real_dist['cq_pass_marks'] - 1, // 1 less than CQ pass marks
            'mcq' => $real_dist['mcq_marks'], // Full MCQ marks
            'practical' => $real_dist['practical_marks'], // Full Practical marks
            'assignment' => $real_dist['assignment_marks'] ?? 0,
            'attendance' => $real_dist['attendance_marks'] ?? 0
        ];
        
        $total1 = array_sum($individual_marks1);
        $grade1 = calculateGrade($total1, $real_dist['total_marks'], $real_dist, $individual_marks1);
        
        echo "Student Marks: CQ={$individual_marks1['cq']}, MCQ={$individual_marks1['mcq']}, Practical={$individual_marks1['practical']}\n";
        echo "Total: $total1 (Overall Pass Required: {$real_dist['overall_pass_marks']})\n";
        echo "Grade: $grade1\n";
        echo ($grade1 == 'F') ? "✅ CORRECT: Failed due to CQ\n" : "❌ WRONG: Should fail due to CQ\n";
        echo "\n";
        
        // Test Case 2: Student fails in MCQ
        echo "Test Case 2: Student fails in MCQ but passes overall\n";
        $individual_marks2 = [
            'cq' => $real_dist['cq_marks'], // Full CQ marks
            'mcq' => $real_dist['mcq_pass_marks'] - 1, // 1 less than MCQ pass marks
            'practical' => $real_dist['practical_marks'], // Full Practical marks
            'assignment' => $real_dist['assignment_marks'] ?? 0,
            'attendance' => $real_dist['attendance_marks'] ?? 0
        ];
        
        $total2 = array_sum($individual_marks2);
        $grade2 = calculateGrade($total2, $real_dist['total_marks'], $real_dist, $individual_marks2);
        
        echo "Student Marks: CQ={$individual_marks2['cq']}, MCQ={$individual_marks2['mcq']}, Practical={$individual_marks2['practical']}\n";
        echo "Total: $total2 (Overall Pass Required: {$real_dist['overall_pass_marks']})\n";
        echo "Grade: $grade2\n";
        echo ($grade2 == 'F') ? "✅ CORRECT: Failed due to MCQ\n" : "❌ WRONG: Should fail due to MCQ\n";
        echo "\n";
        
        // Test Case 3: Student passes in all components
        echo "Test Case 3: Student passes in all components\n";
        $individual_marks3 = [
            'cq' => $real_dist['cq_pass_marks'] + 5, // Above CQ pass marks
            'mcq' => $real_dist['mcq_pass_marks'] + 3, // Above MCQ pass marks
            'practical' => ($real_dist['practical_pass_marks'] ?? 0) > 0 ? $real_dist['practical_pass_marks'] + 2 : $real_dist['practical_marks'], // Above Practical pass marks
            'assignment' => $real_dist['assignment_marks'] ?? 0,
            'attendance' => $real_dist['attendance_marks'] ?? 0
        ];
        
        $total3 = array_sum($individual_marks3);
        $grade3 = calculateGrade($total3, $real_dist['total_marks'], $real_dist, $individual_marks3);
        
        echo "Student Marks: CQ={$individual_marks3['cq']}, MCQ={$individual_marks3['mcq']}, Practical={$individual_marks3['practical']}\n";
        echo "Total: $total3 (Overall Pass Required: {$real_dist['overall_pass_marks']})\n";
        echo "Grade: $grade3\n";
        echo ($grade3 != 'F') ? "✅ CORRECT: Passed in all components\n" : "❌ WRONG: Should pass\n";
        echo "\n";
        
        // Test Case 4: Student fails in Practical (if applicable)
        if (($real_dist['practical_pass_marks'] ?? 0) > 0) {
            echo "Test Case 4: Student fails in Practical but passes overall\n";
            $individual_marks4 = [
                'cq' => $real_dist['cq_marks'], // Full CQ marks
                'mcq' => $real_dist['mcq_marks'], // Full MCQ marks
                'practical' => $real_dist['practical_pass_marks'] - 1, // 1 less than Practical pass marks
                'assignment' => $real_dist['assignment_marks'] ?? 0,
                'attendance' => $real_dist['attendance_marks'] ?? 0
            ];
            
            $total4 = array_sum($individual_marks4);
            $grade4 = calculateGrade($total4, $real_dist['total_marks'], $real_dist, $individual_marks4);
            
            echo "Student Marks: CQ={$individual_marks4['cq']}, MCQ={$individual_marks4['mcq']}, Practical={$individual_marks4['practical']}\n";
            echo "Total: $total4 (Overall Pass Required: {$real_dist['overall_pass_marks']})\n";
            echo "Grade: $grade4\n";
            echo ($grade4 == 'F') ? "✅ CORRECT: Failed due to Practical\n" : "❌ WRONG: Should fail due to Practical\n";
            echo "\n";
        }
        
        echo "=== সারসংক্ষেপ ===\n";
        echo "✅ Individual passing marks functionality সম্পূর্ণভাবে কাজ করছে!\n";
        echo "✅ CQ, MCQ, Practical এর যেকোনো একটিতে পাসিং মার্কের কম পেলে Grade F হবে\n";
        echo "✅ সামগ্রিক মার্কস ভালো থাকলেও individual component এ fail করলে F গ্রেড পাবে\n";
        
    } else {
        echo "❌ No suitable distribution found for testing\n";
    }
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>