<?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 exam ID from URL
$examId = $_GET['id'] ?? null;
if (!$examId) {
    header('Location: index.php');
    exit;
}

// Get exam details
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    WHERE e.id = ? AND e.instructor_id = ?
");
$stmt->execute([$examId, $userId]);
$exam = $stmt->fetch();

if (!$exam) {
    $_SESSION['error_message'] = 'Exam not found or access denied';
    header('Location: index.php');
    exit;
}

// Get exam attempts with student info
$stmt = $db->prepare("
    SELECT ea.*, u.username, u.email, up.first_name, up.last_name,
           TIMESTAMPDIFF(MINUTE, ea.started_at, ea.completed_at) as time_taken
    FROM exam_attempts ea
    JOIN users u ON ea.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE ea.exam_id = ?
    ORDER BY ea.completed_at DESC, ea.started_at DESC
");
$stmt->execute([$examId]);
$attempts = $stmt->fetchAll();

// Calculate statistics
$totalAttempts = count($attempts);
$completedAttempts = count(array_filter($attempts, fn($a) => $a['status'] === 'completed'));
$passedAttempts = count(array_filter($attempts, fn($a) => $a['is_passed'] == 1));
$averageScore = $completedAttempts > 0 ? array_sum(array_column(array_filter($attempts, fn($a) => $a['status'] === 'completed'), 'percentage')) / $completedAttempts : 0;

$page_title = 'Exam Results - ' . htmlspecialchars($exam['title']) . ' - ' . $lms_config['lms']['site_name'];
$active_link = 'exams';
?>
<!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="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle mb-6">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800 mb-2 flex items-center">
                        <i class="fas fa-chart-bar text-green-500 mr-3"></i>Exam Results
                    </h1>
                    <p class="text-gray-600"><?php echo htmlspecialchars($exam['title']); ?> - Student Performance</p>
                </div>
                <div class="flex gap-3">
                    <a href="edit.php?id=<?php echo $exam['id']; ?>" class="px-4 py-2 bg-yellow-500 text-white rounded-lg shadow hover:bg-yellow-600 transition duration-150 font-medium">
                        <i class="fas fa-edit mr-2"></i>Edit Exam
                    </a>
                    <a href="preview.php?id=<?php echo $exam['id']; ?>" class="px-4 py-2 bg-blue-500 text-white rounded-lg shadow hover:bg-blue-600 transition duration-150 font-medium">
                        <i class="fas fa-eye mr-2"></i>Preview Exam
                    </a>
                    <a href="index.php" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg shadow hover:bg-gray-300 transition duration-150 font-medium">
                        <i class="fas fa-arrow-left mr-2"></i>Back to Exams
                    </a>
                </div>
            </div>
        </div>

        <!-- Exam Overview -->
        <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle mb-6">
            <h2 class="text-2xl font-bold text-gray-800 mb-4"><?php echo htmlspecialchars($exam['title']); ?></h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="flex items-center p-4 bg-blue-50 rounded-lg border border-blue-200">
                    <i class="fas fa-users text-2xl text-blue-500 mr-3"></i>
                    <div>
                        <div class="text-2xl font-bold text-blue-600"><?php echo $totalAttempts; ?></div>
                        <div class="text-sm text-blue-600">Total Attempts</div>
                    </div>
                </div>
                <div class="flex items-center p-4 bg-green-50 rounded-lg border border-green-200">
                    <i class="fas fa-check-circle text-2xl text-green-500 mr-3"></i>
                    <div>
                        <div class="text-2xl font-bold text-green-600"><?php echo $completedAttempts; ?></div>
                        <div class="text-sm text-green-600">Completed</div>
                    </div>
                </div>
                <div class="flex items-center p-4 bg-purple-50 rounded-lg border border-purple-200">
                    <i class="fas fa-trophy text-2xl text-purple-500 mr-3"></i>
                    <div>
                        <div class="text-2xl font-bold text-purple-600"><?php echo $passedAttempts; ?> (<?php echo $completedAttempts > 0 ? round(($passedAttempts / $completedAttempts) * 100, 1) : 0; ?>%)</div>
                        <div class="text-sm text-purple-600">Passed</div>
                    </div>
                </div>
                <div class="flex items-center p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                    <i class="fas fa-chart-line text-2xl text-yellow-500 mr-3"></i>
                    <div>
                        <div class="text-2xl font-bold text-yellow-600"><?php echo round($averageScore, 1); ?>%</div>
                        <div class="text-sm text-yellow-600">Average Score</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Results Table -->
        <div class="bg-white rounded-xl shadow-lg border border-accent-subtle overflow-hidden">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800 flex items-center">
                    <i class="fas fa-list mr-2"></i>Student Attempts
                </h3>
            </div>

            <?php if (empty($attempts)): ?>
                <div class="text-center py-12">
                    <div class="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-chart-bar text-4xl text-blue-500"></i>
                    </div>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">No Attempts Yet</h3>
                    <p class="text-gray-600">Students haven't taken this exam yet. Results will appear here once they do.</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">Attempt</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">Score</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Percentage</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Result</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Time Taken</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Completed</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 ($attempts as $attempt): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div>
                                            <div class="text-sm font-medium text-gray-900">
                                                <?php echo htmlspecialchars($attempt['first_name'] . ' ' . $attempt['last_name']); ?>
                                            </div>
                                            <div class="text-sm text-gray-500">
                                                <?php echo htmlspecialchars($attempt['email']); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php echo $attempt['attempt_number']; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                            <?php
                                            echo $attempt['status'] === 'completed' ? 'bg-green-100 text-green-800' :
                                                 ($attempt['status'] === 'in_progress' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800');
                                            ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $attempt['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php if ($attempt['status'] === 'completed'): ?>
                                            <?php echo $attempt['score']; ?>/<?php echo $attempt['max_score']; ?>
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium
                                        <?php if ($attempt['status'] === 'completed'): ?>
                                            <?php echo $attempt['percentage'] >= $exam['passing_score'] ? 'text-green-600' : 'text-red-600'; ?>
                                        <?php endif; ?>">
                                        <?php if ($attempt['status'] === 'completed'): ?>
                                            <?php echo round($attempt['percentage'], 1); ?>%
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($attempt['status'] === 'completed'): ?>
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                                <?php echo $attempt['is_passed'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                                <?php echo $attempt['is_passed'] ? 'PASSED' : 'FAILED'; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php if ($attempt['status'] === 'completed' && $attempt['time_taken']): ?>
                                            <?php echo $attempt['time_taken']; ?> min
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php if ($attempt['completed_at']): ?>
                                            <?php echo date('M j, Y g:i A', strtotime($attempt['completed_at'])); ?>
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <?php if ($attempt['status'] === 'completed'): ?>
                                            <button class="text-blue-600 hover:text-blue-900 px-2 py-1 rounded border border-blue-300 hover:bg-blue-50 transition" onclick="viewAttemptDetails(<?php echo $attempt['id']; ?>)">
                                                <i class="fas fa-eye mr-1"></i> View
                                            </button>
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<!-- Attempt Details Modal -->
<div id="attemptModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold text-gray-900" id="modalTitle">Attempt Details</h3>
            <button class="text-gray-400 hover:text-gray-600" onclick="closeModal()">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div id="modalBody" class="text-center p-4">
            <!-- Attempt details will be loaded here -->
            <i class="fas fa-info-circle text-4xl text-blue-500 mb-4"></i>
            <p>Detailed attempt view would be implemented here.</p>
        </div>
    </div>
</div>

<script>
// 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');
        });
    });
}

function viewAttemptDetails(attemptId) {
    // This would typically load attempt details via AJAX
    // For now, we'll show a placeholder
    document.getElementById('modalTitle').textContent = 'Attempt Details';
    document.getElementById('modalBody').innerHTML = `
        <div class="text-center p-4">
            <i class="fas fa-info-circle text-4xl text-blue-500 mb-4"></i>
            <p>Detailed attempt view would be implemented here.</p>
            <p>Attempt ID: ${attemptId}</p>
        </div>
    `;
    document.getElementById('attemptModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('attemptModal').classList.add('hidden');
}

// Close modal when clicking outside
document.getElementById('attemptModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});
</script>
</body>
</html>
