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

echo "<!DOCTYPE html>
<html lang='bn'>
<head>
    <meta charset='UTF-8'>
    <title>Debug Individual Passing Marks</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body class='bg-light'>
    <div class='container mt-4'>
        <div class='card'>
            <div class='card-header bg-warning text-dark'>
                <h4>Debug: Individual Passing Marks Issue</h4>
            </div>
            <div class='card-body'>";

try {
    // Check subject_mark_distribution table
    echo "<h5>1. subject_mark_distribution table এ individual passing marks:</h5>";
    
    $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
        ORDER BY smd.session DESC, c.name, s.name, smd.exam_type
        LIMIT 10
    ");
    
    $distributions = $stmt->fetchAll();
    
    if (count($distributions) > 0) {
        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped table-sm'>";
        echo "<thead><tr><th>Subject</th><th>Class</th><th>Session</th><th>Exam Type</th><th>CQ Total</th><th>CQ Pass</th><th>MCQ Total</th><th>MCQ Pass</th><th>Practical Total</th><th>Practical Pass</th><th>Overall Pass</th></tr></thead>";
        echo "<tbody>";
        foreach ($distributions as $dist) {
            $cq_pass_status = ($dist['cq_pass_marks'] > 0) ? 'SET' : 'NOT SET';
            $mcq_pass_status = ($dist['mcq_pass_marks'] > 0) ? 'SET' : 'NOT SET';
            $practical_pass_status = ($dist['practical_pass_marks'] > 0) ? 'SET' : 'NOT SET';
            
            $row_class = '';
            if ($dist['cq_pass_marks'] <= 0 && $dist['mcq_pass_marks'] <= 0 && $dist['practical_pass_marks'] <= 0) {
                $row_class = 'table-danger'; // No individual passing marks set
            }
            
            echo "<tr class='$row_class'>";
            echo "<td>{$dist['subject_name']}</td>";
            echo "<td>{$dist['class_name']}</td>";
            echo "<td>{$dist['session']}</td>";
            echo "<td>{$dist['exam_type']}</td>";
            echo "<td>{$dist['cq_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['cq_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['cq_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['mcq_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['mcq_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['mcq_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['practical_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['practical_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['practical_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['overall_pass_marks']}</td>";
            echo "</tr>";
        }
        echo "</tbody></table>";
        echo "</div>";
        
        // Count distributions without individual passing marks
        $no_individual_count = 0;
        foreach ($distributions as $dist) {
            if (($dist['cq_pass_marks'] ?? 0) <= 0 && ($dist['mcq_pass_marks'] ?? 0) <= 0 && ($dist['practical_pass_marks'] ?? 0) <= 0) {
                $no_individual_count++;
            }
        }
        
        if ($no_individual_count > 0) {
            echo "<div class='alert alert-warning'>";
            echo "<strong>⚠️ সমস্যা পাওয়া গেছে:</strong> $no_individual_count টি distribution এ individual passing marks সেট করা নেই (লাল রঙের row গুলো)।";
            echo "</div>";
        }
        
    } else {
        echo "<div class='alert alert-info'>No distributions found in subject_mark_distribution table.</div>";
    }
    
    // Check mark_distributions table
    echo "<h5>2. mark_distributions table এ individual passing marks:</h5>";
    
    $stmt2 = $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
        ORDER BY md.session DESC, c.name, s.name, md.exam_type
        LIMIT 10
    ");
    
    $distributions2 = $stmt2->fetchAll();
    
    if (count($distributions2) > 0) {
        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped table-sm'>";
        echo "<thead><tr><th>Subject</th><th>Class</th><th>Session</th><th>Exam Type</th><th>CQ Total</th><th>CQ Pass</th><th>MCQ Total</th><th>MCQ Pass</th><th>Practical Total</th><th>Practical Pass</th><th>Overall Pass</th></tr></thead>";
        echo "<tbody>";
        foreach ($distributions2 as $dist) {
            $row_class = '';
            if (($dist['cq_pass_marks'] ?? 0) <= 0 && ($dist['mcq_pass_marks'] ?? 0) <= 0 && ($dist['practical_pass_marks'] ?? 0) <= 0) {
                $row_class = 'table-danger'; // No individual passing marks set
            }
            
            echo "<tr class='$row_class'>";
            echo "<td>{$dist['subject_name']}</td>";
            echo "<td>{$dist['class_name']}</td>";
            echo "<td>{$dist['session']}</td>";
            echo "<td>{$dist['exam_type']}</td>";
            echo "<td>{$dist['cq_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['cq_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['cq_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['mcq_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['mcq_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['mcq_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['practical_marks']}</td>";
            echo "<td><span class='badge bg-" . (($dist['practical_pass_marks'] > 0) ? 'success' : 'danger') . "'>" . ($dist['practical_pass_marks'] ?? 'NULL') . "</span></td>";
            echo "<td>{$dist['overall_pass_marks']}</td>";
            echo "</tr>";
        }
        echo "</tbody></table>";
        echo "</div>";
    } else {
        echo "<div class='alert alert-info'>No distributions found in mark_distributions table.</div>";
    }
    
    // Test a specific case
    echo "<h5>3. Test Case: Simulate Grade Calculation</h5>";
    
    // Get a distribution with individual passing marks
    $test_dist = null;
    foreach (array_merge($distributions, $distributions2) as $dist) {
        if (($dist['cq_pass_marks'] ?? 0) > 0 || ($dist['mcq_pass_marks'] ?? 0) > 0 || ($dist['practical_pass_marks'] ?? 0) > 0) {
            $test_dist = $dist;
            break;
        }
    }
    
    if ($test_dist) {
        echo "<div class='alert alert-info'>";
        echo "<strong>Testing with:</strong> {$test_dist['subject_name']} - {$test_dist['class_name']} - {$test_dist['exam_type']}<br>";
        echo "CQ: {$test_dist['cq_marks']} (Pass: " . ($test_dist['cq_pass_marks'] ?? 'NULL') . ")<br>";
        echo "MCQ: {$test_dist['mcq_marks']} (Pass: " . ($test_dist['mcq_pass_marks'] ?? 'NULL') . ")<br>";
        echo "Practical: {$test_dist['practical_marks']} (Pass: " . ($test_dist['practical_pass_marks'] ?? 'NULL') . ")<br>";
        echo "Overall Pass: {$test_dist['overall_pass_marks']}<br>";
        echo "</div>";
        
        // Include calculateGrade function
        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';
        }
        
        // Test case: Student fails in CQ but passes overall
        $individual_marks = [
            'cq' => ($test_dist['cq_pass_marks'] ?? 0) - 1, // 1 mark less than CQ pass marks
            'mcq' => $test_dist['mcq_marks'], // Full MCQ marks
            'practical' => $test_dist['practical_marks'], // Full Practical marks
            'assignment' => $test_dist['assignment_marks'] ?? 0,
            'attendance' => $test_dist['attendance_marks'] ?? 0
        ];
        
        $total_obtained = array_sum($individual_marks);
        $grade = calculateGrade($total_obtained, $test_dist['total_marks'], $test_dist, $individual_marks);
        
        echo "<div class='alert alert-" . ($grade == 'F' ? 'success' : 'danger') . "'>";
        echo "<strong>Test Result:</strong><br>";
        echo "Student Marks: CQ={$individual_marks['cq']}, MCQ={$individual_marks['mcq']}, Practical={$individual_marks['practical']}<br>";
        echo "Total Obtained: $total_obtained<br>";
        echo "Grade: <strong>$grade</strong><br>";
        if ($grade == 'F') {
            echo "✅ <strong>Correct!</strong> Student failed because of individual component failure.";
        } else {
            echo "❌ <strong>Problem!</strong> Student should have failed due to individual component failure.";
        }
        echo "</div>";
        
    } else {
        echo "<div class='alert alert-warning'>";
        echo "<strong>⚠️ কোন distribution পাওয়া যায়নি যেখানে individual passing marks সেট করা আছে!</strong><br>";
        echo "এটাই মূল সমস্যা। আপনাকে individual passing marks সেট করতে হবে।";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>";
    echo "Error: " . $e->getMessage();
    echo "</div>";
}

echo "            </div>
            <div class='card-footer'>
                <a href='marks/setup.php' class='btn btn-primary'>Go to Marks Setup</a>
                <a href='marks/entry.php' class='btn btn-secondary'>Go to Marks Entry</a>
            </div>
        </div>
    </div>
</body>
</html>";
?>