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

$student_id = 6279;
$session = '2025';
$exam_type = 'test';

echo "<h1>Testing Bulk Marksheet Logic for Student $student_id</h1>\n";

// Step 1: Check if student exists
$stmt = $pdo->prepare("
    SELECT s.*, c.name as class_name, c.section
    FROM students s
    JOIN classes c ON s.class_id = c.id
    WHERE s.id = ?
");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    echo "<p style='color: red;'>❌ Student not found!</p>\n";
    exit;
}

echo "<p style='color: green;'>✅ Student found: {$student['first_name']} {$student['last_name']}</p>\n";
echo "<p>Class ID: {$student['class_id']} (URL has class_id=10)</p>\n";
if ($student['class_id'] != 10) {
    echo "<p style='color: red;'>⚠️ Class ID mismatch! Student is in class {$student['class_id']}, but URL specifies class 10.</p>\n";
}

// Step 2: Get student's subjects
$stmt = $pdo->prepare("
    SELECT ss.subject_id, s.name as subject_name, s.code as subject_code
    FROM student_subjects ss
    JOIN subjects s ON ss.subject_id = s.id
    WHERE ss.student_id = ? AND s.status = 'active'
    ORDER BY s.name
");
$stmt->execute([$student_id]);
$all_student_subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "<p>📚 Student has " . count($all_student_subjects) . " subjects:</p>\n<ul>\n";
foreach ($all_student_subjects as $subject) {
    echo "<li>{$subject['subject_name']} (ID: {$subject['subject_id']})</li>\n";
}
echo "</ul>\n";

// Step 3: Get results for the student
$stmt = $pdo->prepare(
    "SELECT r.*, sub.name as subject_name, sub.code as subject_code, ss.is_fourth_subject
    FROM results r
    LEFT JOIN subjects sub ON r.subject_id = sub.id
    LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_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_with_marks = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "<p>📊 Found " . count($results_with_marks) . " results in database:</p>\n";
if (count($results_with_marks) > 0) {
    echo "<ul>\n";
    foreach ($results_with_marks as $result) {
        echo "<li>{$result['subject_name']}: " . ($result['cq_marks'] + $result['mcq_marks']) . " marks</li>\n";
    }
    echo "</ul>\n";
} else {
    echo "<p style='color: orange;'>⚠️ No results found in database for this session/exam combination.</p>\n";
}

// Step 4: Create results map
$results_map = [];
foreach ($results_with_marks as $result) {
    $results_map[$result['subject_id']] = $result;
}

echo "<p>🗺️ Results map has " . count($results_map) . " entries.</p>\n";

// Step 5: Create combined results array
$results = [];
$has_missing_marks = false;

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

    if (isset($results_map[$subject_id])) {
        $results[] = $results_map[$subject_id];
        echo "<p>✅ Subject {$subject['subject_name']} has marks in database.</p>\n";
    } else {
        echo "<p style='color: orange;'>⚠️ Subject {$subject['subject_name']} has no marks - creating placeholder.</p>\n";
        $placeholder_result = [
            'subject_id' => $subject_id,
            'subject_name' => $subject['subject_name'],
            'subject_code' => $subject['subject_code'],
            'cq_marks' => 0,
            'mcq_marks' => 0,
            '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' => false
        ];

        // Try to get mark distribution
        $stmt = $pdo->prepare("
            SELECT total_marks, overall_pass_marks
            FROM subject_mark_distribution
            WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
            LIMIT 1
        ");
        $stmt->execute([$subject_id, $student['class_id'], $session, $exam_type]);
        $smd = $stmt->fetch();

        if ($smd) {
            $placeholder_result['full_marks'] = $smd['total_marks'];
            $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
        }

        $results[] = $placeholder_result;
        $has_missing_marks = true;
    }
}

echo "<h2>Final Results</h2>\n";
echo "<p>📈 Total results processed: " . count($results) . "</p>\n";

if (count($results) > 0) {
    echo "<p style='color: green;'>✅ Results should display properly!</p>\n";
} else {
    echo "<p style='color: red;'>❌ No results to display - this is the bug!</p>\n";
}

echo "<p>Has missing marks: " . ($has_missing_marks ? 'Yes' : 'No') . "</p>\n";

// Test the condition that controls display
$should_display_individual_view = ($student && !empty($results));
echo "<h3>Display Logic Test</h3>\n";
echo "<p>Student exists: " . ($student ? 'Yes' : 'No') . "</p>\n";
echo "<p>Results count: " . count($results) . "</p>\n";
echo "<p>Should display individual view: " . ($should_display_individual_view ? 'Yes' : 'No') . "</p>\n";

// Test the subject grouping logic
$bangla_results = [];
$english_results = [];
$science_math_ict_subjects = [];
$middle_subjects = [];
$economics_subjects = [];
$career_edu = [];
$agri_edu = [];

foreach ($results as $result) {
    $subject_name = strtolower($result['subject_name']);

    // Check if this is a Bangla subject
    if ((stripos($result['subject_name'], 'বাংলা') !== false && stripos($result['subject_name'], 'বাংলাদেশ') === false) ||
        (stripos($result['subject_name'], 'Bangla') !== false && stripos($result['subject_name'], 'Bangladesh') === false)) {
        $bangla_results[] = $result;
    }
    // Check if this is an English subject
    else if (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) {
        $english_results[] = $result;
    }
    // Check for Science, Math, and ICT subjects
    else if (strpos($subject_name, 'science') !== false || strpos($subject_name, 'বিজ্ঞান') !== false ||
             strpos($subject_name, 'math') !== false || strpos($subject_name, 'গণিত') !== false ||
             strpos($subject_name, 'ict') !== false) {
        $science_math_ict_subjects[] = $result;
    }
    // Check for Economics subjects
    else if (strpos($subject_name, 'economics') !== false || strpos($subject_name, 'অর্থনীতি') !== false) {
        $economics_subjects[] = $result;
    }
    // Check for Career Education
    else if (strpos($subject_name, 'career') !== false || strpos($subject_name, 'ক্যারিয়ার') !== false) {
        $career_edu[] = $result;
    }
    // Check for Agricultural Education
    else if (strpos($subject_name, 'agricultural') !== false || strpos($subject_name, 'কৃষি') !== false) {
        $agri_edu[] = $result;
    }
    // All other subjects
    else {
        $middle_subjects[] = $result;
    }
}

echo "<h3>Subject Grouping</h3>\n";
echo "<p>Bangla subjects: " . count($bangla_results) . "</p>\n";
echo "<p>English subjects: " . count($english_results) . "</p>\n";
echo "<p>Science/Math/ICT: " . count($science_math_ict_subjects) . "</p>\n";
echo "<p>Middle subjects: " . count($middle_subjects) . "</p>\n";
echo "<p>Economics: " . count($economics_subjects) . "</p>\n";
echo "<p>Career Edu: " . count($career_edu) . "</p>\n";
echo "<p>Agri Edu: " . count($agri_edu) . "</p>\n";

// Combine subjects
$separate_subjects = array_merge($bangla_results, $english_results);
$combined_middle = array_merge($science_math_ict_subjects, $middle_subjects, $economics_subjects);
if (!empty($career_edu)) {
    $combined_middle = array_merge($combined_middle, $career_edu);
}
if (!empty($agri_edu)) {
    $combined_middle = array_merge($combined_middle, $agri_edu);
}

$final_results = array_merge($separate_subjects, $combined_middle);

echo "<h3>Final Combination</h3>\n";
echo "<p>Separate subjects (Bangla+English): " . count($separate_subjects) . "</p>\n";
echo "<p>Combined middle: " . count($combined_middle) . "</p>\n";
echo "<p>Final results: " . count($final_results) . "</p>\n";

if ($should_display_individual_view) {
    echo "<p style='color: green;'>✅ Individual student view should be displayed!</p>\n";
} else {
    echo "<p style='color: red;'>❌ Individual student view will NOT be displayed - this is why it's not working!</p>\n";
}
?>
