<?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';
require_once '../../includes/ExamGradingService.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
$role = $_SESSION['role'] ?? 'instructor';
$stmt = $db->prepare("
    SELECT id, title
    FROM exams
    " . ($role === 'admin' ? "" : "WHERE instructor_id = ? ") . "
    ORDER BY title
");
$stmt->execute($role === 'admin' ? [] : [$userId]);
$exams = $stmt->fetchAll();

$status = $statusFilter === 'all' ? 'all' : $statusFilter;
$submissions = ExamGradingService::getGradingQueue($db, $userId, $role, $examFilter ? (int) $examFilter : null, $status);

$totalManualPoints = 0;
foreach ($submissions as $sub) {
    if (!$sub['graded_at']) {
        $totalManualPoints += floatval($sub['manual_questions'] ?? 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">${escapeHtml(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 escapeHtml(value) {
    const div = document.createElement('div');
    div.textContent = value === null || value === undefined ? '' : String(value);
    return div.innerHTML;
}

function renderStudentAnswer(question, answer) {
    if (!answer || (Array.isArray(answer) && answer.length === 0)) {
        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">${escapeHtml(option ? option.option_text : answer)}</p>`;
    } else if (question.question_type === 'mcq_multiple') {
        if (Array.isArray(answer)) {
            const selectedOptions = question.options.filter(opt => answer.map(String).includes(String(opt.id)));
            if (selectedOptions.length) {
                return '<ul class="list-disc list-inside">' + 
                    selectedOptions.map(opt => `<li class="text-gray-800">${escapeHtml(opt.option_text)}</li>`).join('') + 
                    '</ul>';
            }
        }
    } else if (question.question_type === 'essay' || question.question_type === 'short_answer') {
        return `<div class="text-gray-800 whitespace-pre-wrap">${escapeHtml(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>${escapeHtml(answer)}</code></pre>`;
    } else if (question.question_type === 'matching' || question.question_type === 'fill_blanks') {
        if (Array.isArray(answer) || (typeof answer === 'object' && answer !== null)) {
            const lines = Array.isArray(answer) ? answer : Object.entries(answer).map(([key, value]) => `${key}: ${value}`);
            return `<pre class="text-gray-800 whitespace-pre-wrap">${escapeHtml(lines.join('\n'))}</pre>`;
        }
    }

    return `<p class="text-gray-800">${escapeHtml(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>