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

// Test marksheet grouping logic for student 6279
$student_id = 6279;
$session = 2025;
$exam_type = 'final';

echo "Testing marksheet grouping logic for student $student_id...\n\n";

$stmt = $pdo->prepare("
    SELECT r.*, sub.name as subject_name
    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(PDO::FETCH_ASSOC);

// Group subjects like in marksheet
$bangla_results = [];
$english_results = [];
$other_results = [];

foreach ($results as $result) {
    // Check if this is a Bangla subject (Bangla 1st/2nd Paper or Bangla Grammar, but not History subjects)
    $is_bangla = false;
    if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
        stripos($result['subject_name'], 'History') === false &&
        stripos($result['subject_name'], 'Introduction') === false) {
        $is_bangla = true;
    }

    if ($is_bangla) {
        $bangla_results[] = $result;
    }
    // Check if this is an English subject (English 1st/2nd Paper or English Grammar)
    else if ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
             stripos($result['subject_name'], 'Literature') === false) {
        $english_results[] = $result;
    }
    // All other subjects
    else {
        $other_results[] = $result;
    }
}

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

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

echo "\nOther subjects: " . count($other_results) . "\n";
foreach ($other_results as $r) {
    echo "  - " . $r['subject_name'] . "\n";
}
?>
