<?php
// Test script to verify class_max_marks calculation for Bangla subjects
session_start();
require_once 'config/database.php';
require_once 'includes/site_settings.php';

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? 'ঠিকানা: গ্রাম/থানা, জেলা, বাংলাদেশ';
$logo_image = $settings['logo_image'] ?? null;
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get search parameters
$class_id = $_GET['class_id'] ?? 10;  // Default to class 10
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? 'final';

echo "<h2>Testing Bangla Class Maximum Marks Calculation</h2>";
echo "<p>Class: $class_id, Session: $session, Exam Type: $exam_type</p>";

try {
    // Get all students in the class
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, roll_number FROM students WHERE class_id = ? AND status = 'active' ORDER BY roll_number");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();

    echo "<h3>Students in Class:</h3>";
    foreach ($students as $student) {
        echo "- {$student['roll_number']}: {$student['first_name']} {$student['last_name']} (ID: {$student['id']})<br>";
    }

    // Find Bangla subjects in this class
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.name, s.code
        FROM subjects s
        JOIN results r ON s.id = r.subject_id
        WHERE s.name LIKE '%বাংলা%' AND r.session = ? AND r.exam_type = ?
    ");
    $stmt->execute([$session, $exam_type]);
    $bangla_subjects = $stmt->fetchAll();

    echo "<h3>Bangla Subjects Found:</h3>";
    foreach ($bangla_subjects as $subject) {
        echo "- {$subject['name']} (ID: {$subject['id']}, Code: {$subject['code']})<br>";
    }

    // For each student, get their Bangla results
    echo "<h3>Student Bangla Results:</h3>";
    foreach ($students as $student) {
        echo "<h4>Student: {$student['first_name']} {$student['last_name']} (Roll: {$student['roll_number']})</h4>";
        
        // Get all Bangla results for this student
        $stmt = $pdo->prepare("
            SELECT r.*, s.name as subject_name, s.code as subject_code
            FROM results r
            JOIN subjects s ON r.subject_id = s.id
            WHERE r.student_id = ? AND s.name LIKE '%বাংলা%' AND r.session = ? AND r.exam_type = ?
            ORDER BY s.name
        ");
        $stmt->execute([$student['id'], $session, $exam_type]);
        $student_bangla_results = $stmt->fetchAll();

        if (empty($student_bangla_results)) {
            echo "<p>No Bangla results found for this student</p>";
            continue;
        }

        $total_cq = 0;
        $total_mcq = 0;
        foreach ($student_bangla_results as $result) {
            echo "- {$result['subject_name']}: CQ={$result['cq_marks']}, MCQ={$result['mcq_marks']}, Total=" . ($result['cq_marks'] + $result['mcq_marks']) . "<br>";
            $total_cq += $result['cq_marks'];
            $total_mcq += $result['mcq_marks'];
        }
        
        echo "<strong>Combined Total: " . ($total_cq + $total_mcq) . "</strong><br><br>";
    }

    // Now calculate the maximum combined Bangla marks across all students
    $max_combined_marks = 0;
    $max_student = null;
    
    foreach ($students as $student) {
        // Get all Bangla results for this student
        $stmt = $pdo->prepare("
            SELECT r.*, s.name as subject_name, s.code as subject_code
            FROM results r
            JOIN subjects s ON r.subject_id = s.id
            WHERE r.student_id = ? AND s.name LIKE '%বাংলা%' AND r.session = ? AND r.exam_type = ?
            ORDER BY s.name
        ");
        $stmt->execute([$student['id'], $session, $exam_type]);
        $student_bangla_results = $stmt->fetchAll();

        if (!empty($student_bangla_results)) {
            // Simulate combineBanglaSubjects function
            $combined = [
                'cq_marks' => 0,
                'mcq_marks' => 0,
                '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 Bangla subjects
            foreach ($student_bangla_results as $result) {
                $combined['cq_marks'] += $result['cq_marks'];
                $combined['mcq_marks'] += $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['cq_marks'] + $result['mcq_marks']; // Only CQ+MCQ for combined
                $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
                $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
            }

            $student_combined_total = $combined['cq_marks'] + $combined['mcq_marks'];
            if ($student_combined_total > $max_combined_marks) {
                $max_combined_marks = $student_combined_total;
                $max_student = $student;
            }
        }
    }

    echo "<h3>Class Maximum Combined Bangla Marks:</h3>";
    if ($max_student) {
        echo "<p><strong>Maximum: $max_combined_marks</strong> by {$max_student['first_name']} {$max_student['last_name']} (Roll: {$max_student['roll_number']})</p>";
    } else {
        echo "<p>No Bangla results found in class</p>";
    }

} catch (Exception $e) {
    echo '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>';
}
?>