<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Get filter parameters
$examFilter = $_GET['exam'] ?? '';
$statusFilter = $_GET['status'] ?? 'pending';

// Get instructor's exams for filter dropdown
$stmt = $db->prepare("
    SELECT id, title
    FROM exams
    WHERE instructor_id = ?
    ORDER BY title
");
$stmt->execute([$userId]);
$exams = $stmt->fetchAll();

// Build query for submissions needing grading
$query = "
    SELECT 
        ea.id as attempt_id,
        ea.exam_id,
        ea.student_id,
        ea.completed_at,
        ea.score,
        ea.max_score,
        ea.percentage,
        ea.graded_at,
        ea.graded_by,
        e.title as exam_title,
        u.username as student_name,
        up.first_name,
        up.last_name,
        COUNT(DISTINCT eq.question_id) as total_questions,
        COUNT(DISTINCT CASE 
            WHEN q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks') 
            THEN eq.question_id 
        END) as manual_questions,
        SUM(CASE 
            WHEN q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks') 
            THEN eq.points 
            ELSE 0 
        END) as manual_points
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN users u ON ea.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN exam_questions eq ON e.id = eq.exam_id
    LEFT JOIN questions q ON eq.question_id = q.id
    WHERE e.instructor_id = ? AND ea.status = 'completed'
";

$params = [$userId];

if ($examFilter) {
    $query .= " AND e.id = ?";
    $params[] = $examFilter;
}

if ($statusFilter === 'pending') {
    $query .= " AND ea.graded_at IS NULL";
} elseif ($statusFilter === 'graded') {
    $query .= " AND ea.graded_at IS NOT NULL";
}

$query .= " GROUP BY ea.id ORDER BY ea.completed_at DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$submissions = $stmt->fetchAll();

$page_title = 'Grade Exams - ' . $lms_config['lms']['site_name'];
$active_link = 'grading';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: #10b981; }
        .toast-error { background-color: #ef4444; }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <?php include '../includes/sidebar.php'; ?>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

        <?php include '../includes/mobile_menu.php'; ?>

        <!-- Page Header -->
        <div class="p-6 border-b border-accent-subtle bg-white">
            <h1 class="text-3xl font-bold text-text-dark mb-2">
                <i class="fas fa-clipboard-check text-primary-blue mr-3"></i>Grade Exams
            </h1>
            <p class="text-gray-600">Review and grade essay and short answer questions</p>
        </div>

        <div class="p-6 space-y-8">
            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <?php
            $pendingCount = 0;
            $gradedCount = 0;
            $totalManualPoints = 0;
            
            foreach ($submissions as $sub) {
                if ($sub['graded_at']) {
                    $gradedCount++;
                } else {
                    $pendingCount++;
                }
                if (!$sub['graded_at']) {
                    $totalManualPoints += $sub['manual_points'];
                }
            }
            ?>
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-600 font-medium">Pending Grading</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $pendingCount; ?></p>
                    </div>
                    <div class="bg-yellow-100 rounded-full p-4">
                        <i class="fas fa-clock text-yellow-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-600 font-medium">Graded</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $gradedCount; ?></p>
                    </div>
                    <div class="bg-green-100 rounded-full p-4">
                        <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-600 font-medium">Total Submissions</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo count($submissions); ?></p>
                    </div>
                    <div class="bg-blue-100 rounded-full p-4">
                        <i class="fas fa-file-alt text-blue-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="bg-white rounded-xl shadow-lg p-6">
            <form method="GET" class="flex flex-wrap gap-4">
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Exam</label>
                    <select name="exam" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Exams</option>
                        <?php foreach ($exams as $exam): ?>
                            <option value="<?php echo $exam['id']; ?>" <?php echo $examFilter == $exam['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($exam['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                    <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="all" <?php echo $statusFilter == 'all' ? 'selected' : ''; ?>>All</option>
                        <option value="pending" <?php echo $statusFilter == 'pending' ? 'selected' : ''; ?>>Pending Grading</option>
                        <option value="graded" <?php echo $statusFilter == 'graded' ? 'selected' : ''; ?>>Graded</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                        <i class="fas fa-filter mr-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Submissions List -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-800">Exam Submissions</h2>
            </div>

            <?php if (empty($submissions)): ?>
                <div class="p-12 text-center">
                    <i class="fas fa-inbox text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-900 mb-2">No submissions found</h3>
                    <p class="text-gray-600">There are no exam submissions matching your filters.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Exam</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Submitted</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Questions</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Score</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($submissions as $submission): ?>
                                <tr class="hover:bg-gray-50 transition">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-shrink-0 h-10 w-10 bg-blue-100 rounded-full flex items-center justify-center">
                                                <span class="text-blue-600 font-semibold">
                                                    <?php echo strtoupper(substr($submission['first_name'] ?? $submission['student_name'], 0, 1)); ?>
                                                </span>
                                            </div>
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($submission['first_name'] && $submission['last_name'] ? 
                                                        $submission['first_name'] . ' ' . $submission['last_name'] : 
                                                        $submission['student_name']); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900"><?php echo htmlspecialchars($submission['exam_title']); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900"><?php echo date('M j, Y', strtotime($submission['completed_at'])); ?></div>
                                        <div class="text-xs text-gray-500"><?php echo date('g:i A', strtotime($submission['completed_at'])); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900"><?php echo $submission['total_questions']; ?> total</div>
                                        <?php if ($submission['manual_questions'] > 0): ?>
                                            <div class="text-xs text-orange-600 font-medium">
                                                <?php echo $submission['manual_questions']; ?> need grading
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($submission['graded_at']): ?>
                                            <div class="text-sm font-medium text-gray-900">
                                                <?php echo round($submission['score'], 1); ?>/<?php echo $submission['max_score']; ?>
                                            </div>
                                            <div class="text-xs text-gray-500"><?php echo round($submission['percentage'], 1); ?>%</div>
                                        <?php else: ?>
                                            <span class="text-sm text-gray-500">Not graded</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($submission['graded_at']): ?>
                                            <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                                                <i class="fas fa-check-circle mr-1"></i> Graded
                                            </span>
                                        <?php else: ?>
                                            <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
                                                <i class="fas fa-clock mr-1"></i> Pending
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <button 
                                            onclick="gradeSubmission(<?php echo $submission['attempt_id']; ?>)"
                                            class="text-blue-600 hover:text-blue-900 mr-3"
                                        >
                                            <i class="fas fa-edit mr-1"></i>
                                            <?php echo $submission['graded_at'] ? 'Review' : 'Grade'; ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
        </div>
    </main>
</div>

<!-- Grading Modal -->
<div id="gradingModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50 overflow-y-auto">
    <div class="bg-white rounded-xl shadow-2xl max-w-6xl w-full mx-4 my-8 max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b border-gray-200 p-6 z-10">
            <div class="flex justify-between items-center">
                <h2 class="text-2xl font-bold text-gray-900">Grade Exam Submission</h2>
                <button onclick="closeGradingModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
        </div>
        <div id="gradingContent" class="p-6">
            <!-- Content will be loaded here -->
        </div>
    </div>
</div>

<script>
function gradeSubmission(attemptId) {
    document.getElementById('gradingModal').classList.remove('hidden');
    document.getElementById('gradingModal').classList.add('flex');
    document.getElementById('gradingContent').innerHTML = '<div class="text-center py-12"><i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i><p class="mt-4 text-gray-600">Loading submission...</p></div>';

    fetch('../../api/grading/get_submission.php?attempt_id=' + attemptId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderGradingInterface(data.submission, data.questions);
            } else {
                alert('Error loading submission: ' + data.message);
                closeGradingModal();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while loading the submission.');
            closeGradingModal();
        });
}

function renderGradingInterface(submission, questions) {
    const answers = JSON.parse(submission.answers || '{}');
    let html = `
        <div class="space-y-6">
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-sm text-gray-600">Student</p>
                        <p class="font-semibold text-gray-900">${submission.student_name}</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Exam</p>
                        <p class="font-semibold text-gray-900">${submission.exam_title}</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Submitted</p>
                        <p class="font-semibold text-gray-900">${new Date(submission.completed_at).toLocaleString()}</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Current Score</p>
                        <p class="font-semibold text-gray-900">${submission.score || 0}/${submission.max_score || 0} (${submission.percentage || 0}%)</p>
                    </div>
                </div>
            </div>

            <form id="gradingForm" onsubmit="saveGrades(event, ${submission.attempt_id})">
    `;

    questions.forEach((q, index) => {
        const studentAnswer = answers[q.question_id] || '';
        const isManualGrading = ['essay', 'short_answer', 'code', 'fill_blanks'].includes(q.question_type);
        
        html += `
            <div class="border border-gray-200 rounded-lg p-6 ${isManualGrading ? 'bg-yellow-50' : 'bg-gray-50'}">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Question ${index + 1}</h3>
                    <div class="flex items-center gap-4">
                        <span class="text-sm text-gray-600">Type: <span class="font-medium">${q.question_type.replace('_', ' ')}</span></span>
                        <span class="text-sm text-gray-600">Points: <span class="font-medium">${q.points}</span></span>
                    </div>
                </div>

                <div class="mb-4">
                    <p class="text-gray-800 whitespace-pre-wrap">${q.content}</p>
                </div>

                <div class="mb-4 bg-white border border-gray-300 rounded-lg p-4">
                    <h4 class="font-medium text-gray-900 mb-2">Student's Answer:</h4>
                    ${renderStudentAnswer(q, studentAnswer)}
                </div>

                ${isManualGrading ? `
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Points Earned (Max: ${q.points})
                            </label>
                            <input 
                                type="number" 
                                name="score_${q.question_id}" 
                                min="0" 
                                max="${q.points}" 
                                step="0.5"
                                value="${q.earned_points || 0}"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                required
                            />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Feedback (Optional)
                            </label>
                            <textarea 
                                name="feedback_${q.question_id}"
                                rows="2"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                placeholder="Provide feedback for this answer..."
                            >${q.feedback || ''}</textarea>
                        </div>
                    </div>
                ` : `
                    <div class="bg-green-50 border border-green-200 rounded-lg p-3">
                        <p class="text-sm text-green-800">
                            <i class="fas fa-check-circle mr-2"></i>
                            Auto-graded: ${q.earned_points || 0}/${q.points} points
                        </p>
                    </div>
                `}
            </div>
        `;
    });

    html += `
                <div class="border-t border-gray-200 pt-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Overall Feedback (Optional)
                    </label>
                    <textarea 
                        name="overall_feedback"
                        rows="4"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        placeholder="Provide overall feedback for the student..."
                    >${submission.feedback || ''}</textarea>
                </div>

                <div class="flex justify-end gap-4 mt-6">
                    <button 
                        type="button" 
                        onclick="closeGradingModal()" 
                        class="px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
                    >
                        Cancel
                    </button>
                    <button 
                        type="submit" 
                        class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
                    >
                        <i class="fas fa-save mr-2"></i>Save Grades
                    </button>
                </div>
            </form>
        </div>
    `;

    document.getElementById('gradingContent').innerHTML = html;
}

function renderStudentAnswer(question, answer) {
    if (!answer) {
        return '<p class="text-gray-500 italic">No answer provided</p>';
    }

    if (question.question_type === 'mcq_single' || question.question_type === 'true_false') {
        const option = question.options.find(opt => opt.id == answer);
        return `<p class="text-gray-800">${option ? option.option_text : answer}</p>`;
    } else if (question.question_type === 'mcq_multiple') {
        if (Array.isArray(answer)) {
            const selectedOptions = question.options.filter(opt => answer.includes(String(opt.id)));
            return '<ul class="list-disc list-inside">' + 
                selectedOptions.map(opt => `<li class="text-gray-800">${opt.option_text}</li>`).join('') + 
                '</ul>';
        }
    } else if (question.question_type === 'essay' || question.question_type === 'short_answer') {
        return `<div class="prose max-w-none text-gray-800 whitespace-pre-wrap">${answer}</div>`;
    } else if (question.question_type === 'code') {
        return `<pre class="bg-gray-900 text-green-400 p-4 rounded-lg overflow-x-auto"><code>${answer}</code></pre>`;
    }

    return `<p class="text-gray-800">${answer}</p>`;
}

function saveGrades(event, attemptId) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const questionScores = {};
    const questionFeedback = {};
    
    for (let [key, value] of formData.entries()) {
        if (key.startsWith('score_')) {
            const questionId = key.replace('score_', '');
            questionScores[questionId] = parseFloat(value);
        } else if (key.startsWith('feedback_')) {
            const questionId = key.replace('feedback_', '');
            questionFeedback[questionId] = value;
        }
    }
    
    const overallFeedback = formData.get('overall_feedback');
    
    const submitBtn = event.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Saving...';
    
    fetch('../../api/grading/index.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'save_grades',
            attempt_id: attemptId,
            question_scores: questionScores,
            question_feedback: questionFeedback,
            feedback: overallFeedback
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Grades saved successfully!');
            closeGradingModal();
            location.reload();
        } else {
            alert('Error saving grades: ' + data.message);
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Grades';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while saving grades.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Grades';
    });
}

function closeGradingModal() {
    document.getElementById('gradingModal').classList.add('hidden');
    document.getElementById('gradingModal').classList.remove('flex');
}

// Mobile Menu Functionality
const mobileMenuButton = document.getElementById('mobileMenuButton');
const closeMobileMenu = document.getElementById('closeMobileMenu');
const mobileMenu = document.getElementById('mobileMenu');

if (mobileMenuButton && closeMobileMenu && mobileMenu) {
    mobileMenuButton.addEventListener('click', () => {
        mobileMenu.classList.remove('-translate-x-full');
    });

    closeMobileMenu.addEventListener('click', () => {
        mobileMenu.classList.add('-translate-x-full');
    });

    // Close menu when a link is clicked
    mobileMenu.querySelectorAll('a').forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });
    });
}
</script>

</body>
</html>