<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'teacher') {
    die('Access denied. Please login as teacher.');
}

$teacher_user_id = $_SESSION['user_id'];

echo "<h2>🔍 Exam ID Preservation Test for Multi-Paper Marks Entry</h2>";
echo "<hr>";

// Step 1: Check current assignments
echo "<h3>📋 Current Teacher Assignments</h3>";
$stmt_assignments = $pdo->prepare("
    SELECT 
        cst.*,
        s.subject_name,
        c.class_name,
        CASE 
            WHEN es.exam_id IS NOT NULL THEN '✅ IN EXAM 41'
            ELSE '❌ NOT IN EXAM 41'
        END as exam_status
    FROM class_subject_teachers cst
    LEFT JOIN subjects s ON cst.subject_id = s.subject_id
    LEFT JOIN classes c ON cst.class_id = c.class_id
    LEFT JOIN exam_subjects es ON es.subject_id = cst.subject_id AND es.exam_id = 41
    WHERE cst.teacher_user_id = ? 
      AND cst.academic_year = '2025' 
      AND cst.term = 'TERM 3'
    ORDER BY s.subject_name
");
$stmt_assignments->execute([$teacher_user_id]);
$assignments = $stmt_assignments->fetchAll(PDO::FETCH_ASSOC);

echo "<table border='1' cellpadding='5' style='border-collapse: collapse; margin: 10px 0;'>";
echo "<tr style='background-color: #f0f0f0;'>";
echo "<th>Subject ID</th><th>Subject Name</th><th>Class</th><th>Status</th>";
echo "</tr>";

foreach ($assignments as $assignment) {
    $bg_color = (strpos($assignment['exam_status'], '✅') === 0) ? '#e8f5e8' : '#fff3cd';
    echo "<tr style='background-color: {$bg_color};'>";
    echo "<td>{$assignment['subject_id']}</td>";
    echo "<td>{$assignment['subject_name']}</td>";
    echo "<td>{$assignment['class_name']}</td>";
    echo "<td>{$assignment['exam_status']}</td>";
    echo "</tr>";
}
echo "</table>";

echo "<p><strong>📊 Summary: " . count(array_filter($assignments, function($a) { return strpos($a['exam_status'], '✅') === 0; })) . " subjects assigned to Exam 41</strong></p>";

// Step 2: Test backend duplicate handling
echo "<h3>🔧 Backend Duplicate Entry Test</h3>";
echo "<p><strong>Testing if ajax_save_marks.php can handle duplicate entries properly...</strong></p>";

// Create test data
$test_data = [
    'exam_id' => '41',
    'subject_id' => '8',
    'class_id' => '63',
    'stream_id' => '42',
    'paper_id' => '1',
    'academic_year' => '2025',
    'term' => 'TERM 3',
    'school_id' => '2',
    'marks' => json_encode([
        [
            'student_id' => '548',
            'paper_id' => '1',
            'mark' => '85'
        ]
    ])
];

echo "<div style='background-color: #f8f9fa; padding: 15px; border-left: 4px solid #17a2b8; margin: 10px 0;'>";
echo "<h4>Test Data for Duplicate Entry Handling:</h4>";
foreach ($test_data as $key => $value) {
    echo "<strong>{$key}:</strong> " . (is_string($value) && strlen($value) > 100 ? substr($value, 0, 100) . '...' : $value) . "<br>";
}
echo "</div>";

// Step 3: Instructions for testing
echo "<h3>🎯 Testing Instructions</h3>";
echo "<div style='background-color: #d4edda; padding: 15px; border-left: 4px solid #28a745; margin: 10px 0;'>";
echo "<h4>✅ What to Test Now:</h4>";
echo "<ol>";
echo "<li><strong>Switch between papers:</strong> In a multi-paper subject, switch from Paper 1 to Paper 2 and back</li>";
echo "<li><strong>Save marks for each paper:</strong> Enter marks for Paper 1, save them, then enter marks for Paper 2</li>";
echo "<li><strong>Check console logs:</strong> Open browser console (F12) to see detailed logging</li>";
echo "<li><strong>Verify no errors:</strong> Should see 'saved/updated' messages instead of 'invalid or missing exam_id'</li>";
echo "</ol>";
echo "</div>";

echo "<div style='background-color: #fff3cd; padding: 15px; border-left: 4px solid #ffc107; margin: 10px 0;'>";
echo "<h4>🔍 What the Console Should Show:</h4>";
echo "<pre style='background-color: #f8f9fa; padding: 10px; border-radius: 4px;'>";
echo "=== PRE-SAVE VALIDATION ===\n";
echo "currentExamId: 41\n";
echo "Selected paper ID: 2\n";
echo "currentExamId before paper change: 41\n";
echo "✅ currentExamId is preserved: 41\n";
echo "✅ All validation passed. Ready to save with:\n";
echo "- exam_id: 41\n";
echo "- academic_year: 2025\n";
echo "- term: TERM 3\n";
echo "- paper_id: 2\n";
echo "✅ Marks saved/updated successfully\n";
echo "</pre>";
echo "</div>";

echo "<h3>🛠️ If Issues Persist</h3>";
echo "<p>If you still see 'invalid or missing exam_id' errors:</p>";
echo "<ol>";
echo "<li>Refresh the page completely (Ctrl+F5)</li>";
echo "<li>Clear browser cache</li>";
echo "<li>Try in an incognito/private browser window</li>";
echo "<li>Check the browser console for any JavaScript errors</li>";
echo "</ol>";

?>

<style>
body {
    font-family: Arial, sans-serif;
    margin: 20px;
    background-color: #f9f9f9;
}
h2, h3 {
    color: #333;
}
table {
    width: 100%;
    max-width: 800px;
}
th {
    background-color: #f0f0f0;
    text-align: left;
}
</style>