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

// Copy the generate_marksheet_content function logic here for testing
function test_generate_marksheet_content($pdo, $student_id, $session, $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section, s.group_name
        FROM students s
        JOIN classes c ON s.class_id = c.id
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();

    if (!$student) {
        return "ছাত্র-ছাত্রীর তথ্য পাওয়া যায়নি";
    }

    echo "=== STUDENT INFO ===\n";
    echo "Name: {$student['first_name']} {$student['last_name']}\n";
    echo "Roll: {$student['roll_number']}\n";
    echo "Class: {$student['class_name']} {$student['section']}\n";
    echo "Group: {$student['group_name']}\n\n";

    // Get all subjects selected by the student from student_subjects table
    $stmt = $pdo->prepare(
        "SELECT ss.subject_id, s.name as subject_name, s.code as subject_code, ss.is_fourth_subject\n" .
        "FROM student_subjects ss\n" .
        "JOIN subjects s ON ss.subject_id = s.id\n" .
        "WHERE ss.student_id = ?\n" .
        "ORDER BY s.name\n"
    );
    $stmt->execute([$student_id]);
    $all_student_subjects = $stmt->fetchAll();

    echo "=== ASSIGNED SUBJECTS ===\n";
    foreach ($all_student_subjects as $subject) {
        echo "- {$subject['subject_name']} (ID: {$subject['subject_id']}, is_fourth: " . ($subject['is_fourth_subject'] ? 'Yes' : 'No') . ")\n";
    }
    echo "\n";

    // Get results for the student
    $stmt = $pdo->prepare(
        "SELECT r.*, sub.name as subject_name, sub.code as subject_code\n" .
        "FROM results r\n" .
        "LEFT JOIN subjects sub ON r.subject_id = sub.id\n" .
        "WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?\n" .
        "AND r.id IN (\n" .
        "    SELECT MAX(id)\n" .
        "    FROM results\n" .
        "    WHERE student_id = ? AND session = ? AND exam_type = ?\n" .
        "    GROUP BY subject_id\n" .
        ")\n" .
        "ORDER BY sub.name\n"
    );
    $stmt->execute([$student_id, $session, $exam_type, $student_id, $session, $exam_type]);
    $results_with_marks = $stmt->fetchAll();

    echo "=== RESULTS FROM DATABASE ===\n";
    foreach ($results_with_marks as $result) {
        echo "- {$result['subject_name']} (ID: {$result['subject_id']})\n";
    }
    echo "\n";

    // Create a map of results by subject_id for easy lookup
    $results_map = [];
    foreach ($results_with_marks as $result) {
        $results_map[$result['subject_id']] = $result;
    }

    // Create a map of subject information by subject_id
    $subject_info_map = [];
    foreach ($all_student_subjects as $subject) {
        $subject_info_map[$subject['subject_id']] = $subject;
    }

    // Create combined results array with all subjects
    $results = [];
    $has_missing_marks = false;

    foreach ($all_student_subjects as $subject) {
        $subject_id = $subject['subject_id'];

        if (isset($results_map[$subject_id])) {
            $result = $results_map[$subject_id];
            $result['is_fourth_subject'] = $subject['is_fourth_subject'];
            $results[] = $result;
        } else {
            // Create placeholder
            $placeholder_result = [
                'subject_id' => $subject_id,
                'subject_name' => $subject['subject_name'],
                'subject_code' => $subject['subject_code'],
                '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' => 100,
                'pass_marks' => 33,
                'grade' => 'F',
                'grade_point' => 0.00,
                'class_max_marks' => 0,
                'is_fourth_subject' => $subject['is_fourth_subject']
            ];
            $results[] = $placeholder_result;
            $has_missing_marks = true;
        }
    }

    echo "=== COMBINED RESULTS BEFORE GROUPING ===\n";
    foreach ($results as $result) {
        echo "- {$result['subject_name']} (ID: {$result['subject_id']}, is_fourth: " . ($result['is_fourth_subject'] ? 'Yes' : 'No') . ")\n";
    }
    echo "\n";

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

    foreach ($results as $result) {
        $subject_name = $result['subject_name'];
        echo "Checking subject: '$subject_name'\n";

        // Check if this is a Bangla subject - be more specific to avoid false matches
        if (preg_match('/^(বাংলা|Bangla)(\s|$)/i', $subject_name)) {
            echo "  -> Matched as Bangla subject\n";
            $bangla_results[] = $result;
        }
        // Check if this is an English subject - be more specific to avoid false matches
        else if (preg_match('/^(ইংরেজি|English)(\s|$)/i', $subject_name)) {
            echo "  -> Matched as English subject\n";
            $english_results[] = $result;
        }
        // For other subjects, add directly
        else {
            echo "  -> Other subject\n";
            $grouped_results[] = $result;
        }
    }

    echo "=== GROUPING RESULTS ===\n";
    echo "Bangla subjects: " . count($bangla_results) . "\n";
    foreach ($bangla_results as $r) echo "  - {$r['subject_name']}\n";

    echo "English subjects: " . count($english_results) . "\n";
    foreach ($english_results as $r) echo "  - {$r['subject_name']}\n";

    echo "Other subjects: " . count($grouped_results) . "\n";
    foreach ($grouped_results as $r) echo "  - {$r['subject_name']}\n";
    echo "\n";

    // Process combined subjects
    $top_subjects = [];

    if (!empty($bangla_results)) {
        $combined_bangla = combineBanglaSubjects($bangla_results);
        $top_subjects[] = $combined_bangla;
        echo "Combined Bangla: {$combined_bangla['subject_name']}\n";
    }

    if (!empty($english_results)) {
        $combined_english = combineEnglishSubjects($english_results);
        $top_subjects[] = $combined_english;
        echo "Combined English: {$combined_english['subject_name']}\n";
    }

    // Combine the top subjects with the rest
    if (!empty($bangla_results) || !empty($english_results)) {
        $results = $top_subjects;
        foreach ($grouped_results as $result) {
            $results[] = $result;
        }
        echo "\nUsing combined subjects + other subjects\n";
    } else {
        $results = $grouped_results;
        echo "\nUsing original grouped results (no combined subjects)\n";
    }

    echo "\n=== FINAL SUBJECTS FOR DISPLAY ===\n";
    foreach ($results as $result) {
        $subject_name = isset($result['subject_name']) ? $result['subject_name'] : 'Unknown';
        $is_fourth = isset($result['is_fourth_subject']) ? ($result['is_fourth_subject'] ? 'Yes' : 'No') : 'Unknown';
        echo "- {$subject_name} (is_fourth: {$is_fourth})\n";
    }
    echo "\nTotal subjects for display: " . count($results) . "\n";

    return $results;
}

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

    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']];
        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';
        if (!isset($result['is_fourth_subject'])) $result['is_fourth_subject'] = false;
        return $result;
    }

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

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

    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];

    return $combined;
}

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

    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']];
        $result['mcq_marks_array'] = [$result['mcq_marks']];
        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';
        if (!isset($result['is_fourth_subject'])) $result['is_fourth_subject'] = false;
        return $result;
    }

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

    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['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }

    return $combined;
}

try {
    // Get a student ID from class 10
    $stmt = $pdo->prepare('SELECT id FROM students WHERE class_id = ? AND status = "active" ORDER BY roll_number LIMIT 1');
    $stmt->execute([10]);
    $test_student = $stmt->fetch();
    $student_id = $test_student['id'];

    echo "Testing full marksheet generation for student ID: $student_id\n\n";

    $results = test_generate_marksheet_content($pdo, $student_id, '2025', 'final');

} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}
?>
