<?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 questions
$stmt = $db->prepare("
    SELECT q.*, eq.points, eq.sort_order
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    WHERE eq.exam_id = ?
    ORDER BY eq.sort_order
");
$stmt->execute([$examId]);
$questions = $stmt->fetchAll();

// Get question options
foreach ($questions as &$question) {
    $stmt = $db->prepare("
        SELECT * FROM question_options
        WHERE question_id = ?
        ORDER BY sort_order
    ");
    $stmt->execute([$question['id']]);
    $question['options'] = $stmt->fetchAll();
}

$page_title = 'Preview Exam - ' . htmlspecialchars($exam['title']) . ' - ' . $lms_config['lms']['site_name'];
?>

<div class="admin-container">
    <div class="admin-sidebar">
        <div class="sidebar-header">
            <h2><i class="fas fa-graduation-cap me-2"></i><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h2>
            <p><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></p>
        </div>

        <nav class="sidebar-nav">
            <ul>
                <li><a href="../dashboard.php"><i class="fas fa-tachometer-alt me-2"></i>Dashboard</a></li>
                <li><a href="../courses/"><i class="fas fa-book me-2"></i>My Courses</a></li>
                <li><a href="../courses/new.php"><i class="fas fa-plus me-2"></i>Create Course</a></li>
                <li><a href="../questions/index.php"><i class="fas fa-question-circle me-2"></i>Question Bank</a></li>
                <li><a href="index.php" class="active"><i class="fas fa-file-alt me-2"></i>Exams</a></li>
                <li><a href="assignments.php"><i class="fas fa-user-plus me-2"></i>Exam Assignments</a></li>
                <li><a href="../resources.php"><i class="fas fa-folder me-2"></i>Resources</a></li>
                <li><a href="../students.php"><i class="fas fa-users me-2"></i>Students</a></li>
                <li><a href="../assignments.php"><i class="fas fa-tasks me-2"></i>Assignments</a></li>
                <li><a href="/lms/instructor/grading/index.php"><i class="fas fa-chart-line me-2"></i>Grades</a></li>
                <li><a href="../../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="admin-main">
        <div class="admin-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1><i class="fas fa-eye text-info me-3"></i>Preview Exam</h1>
                    <p class="text-muted mb-0"><?php echo htmlspecialchars($exam['title']); ?> - Read-only preview</p>
                </div>
                <div class="header-actions">
                    <a href="edit.php?id=<?php echo $exam['id']; ?>" class="btn btn-warning btn-lg">
                        <i class="fas fa-edit me-2"></i>Edit Exam
                    </a>
                    <a href="results.php?id=<?php echo $exam['id']; ?>" class="btn btn-success btn-lg">
                        <i class="fas fa-chart-bar me-2"></i>View Results
                    </a>
                    <a href="index.php" class="btn btn-outline-secondary btn-lg">
                        <i class="fas fa-arrow-left me-2"></i>Back to Exams
                    </a>
                </div>
            </div>
        </div>

        <div class="admin-content">
            <!-- Exam Details -->
            <div class="exam-preview-header">
                <div class="exam-info-card">
                    <h3><?php echo htmlspecialchars($exam['title']); ?></h3>
                    <?php if ($exam['description']): ?>
                        <p class="exam-description"><?php echo nl2br(htmlspecialchars($exam['description'])); ?></p>
                    <?php endif; ?>

                    <div class="exam-meta">
                        <div class="meta-item">
                            <i class="fas fa-clock"></i>
                            <span><?php echo $exam['time_limit'] ? $exam['time_limit'] . ' minutes' : 'No time limit'; ?></span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-question-circle"></i>
                            <span><?php echo count($questions); ?> questions</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-trophy"></i>
                            <span><?php echo $exam['passing_score']; ?>% passing score</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-star"></i>
                            <span><?php echo $exam['total_points']; ?> total points</span>
                        </div>
                    </div>

                    <?php if ($exam['instructions']): ?>
                        <div class="exam-instructions">
                            <h4>Instructions:</h4>
                            <p><?php echo nl2br(htmlspecialchars($exam['instructions'])); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Questions -->
            <div class="questions-preview">
                <?php if (empty($questions)): ?>
                    <div class="empty-state">
                        <div class="empty-state-icon">
                            <i class="fas fa-question-circle"></i>
                        </div>
                        <h3>No Questions</h3>
                        <p>This exam has no questions yet. Add questions to see the preview.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($questions as $index => $question): ?>
                        <div class="question-preview-card">
                            <div class="question-header">
                                <h4>Question <?php echo $index + 1; ?></h4>
                                <div class="question-meta">
                                    <span class="question-type"><?php echo ucfirst(str_replace('_', ' ', $question['question_type'])); ?></span>
                                    <span class="question-points"><?php echo $question['points']; ?> points</span>
                                </div>
                            </div>

                            <div class="question-content">
                                <div class="question-text">
                                    <?php echo nl2br(htmlspecialchars($question['content'])); ?>
                                </div>

                                <div class="question-options">
                                    <?php if (in_array($question['question_type'], ['mcq_single', 'true_false'])): ?>
                                        <?php foreach ($question['options'] as $option): ?>
                                            <div class="option-item">
                                                <div class="option-radio">
                                                    <i class="far fa-circle"></i>
                                                </div>
                                                <div class="option-text">
                                                    <?php echo htmlspecialchars($option['option_text']); ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>

                                    <?php elseif ($question['question_type'] === 'mcq_multiple'): ?>
                                        <?php foreach ($question['options'] as $option): ?>
                                            <div class="option-item">
                                                <div class="option-checkbox">
                                                    <i class="far fa-square"></i>
                                                </div>
                                                <div class="option-text">
                                                    <?php echo htmlspecialchars($option['option_text']); ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>

                                    <?php elseif (in_array($question['question_type'], ['essay', 'short_answer'])): ?>
                                        <div class="text-answer-placeholder">
                                            <textarea readonly rows="<?php echo $question['question_type'] === 'essay' ? 6 : 3; ?>"
                                                      placeholder="Student answer area"></textarea>
                                        </div>

                                    <?php elseif ($question['question_type'] === 'code'): ?>
                                        <div class="code-answer-placeholder">
                                            <textarea readonly rows="8" placeholder="Code answer area"></textarea>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
/* Custom styles for Exam Preview page */
.admin-container {
    display: flex;
    min-height: 100vh;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.admin-sidebar {
    width: 280px;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    color: white;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
    box-shadow: 4px 0 15px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.sidebar-header {
    padding: 2rem 1.5rem;
    border-bottom: 1px solid #374151;
    text-align: center;
}

.sidebar-header h2 {
    font-size: 1.5rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.sidebar-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar-nav li a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    color: #cbd5e1;
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 500;
    border-left: 3px solid transparent;
}

.sidebar-nav li a:hover,
.sidebar-nav li a.active {
    background: linear-gradient(135deg, #374151 0%, #4b5563 100%);
    color: white;
    border-left-color: #3b82f6;
    transform: translateX(5px);
}

.admin-main {
    margin-left: 280px;
    flex: 1;
    min-height: 100vh;
}

.admin-header {
    background: white;
    padding: 2rem;
    border-bottom: 1px solid #e5e7eb;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.admin-header h1 {
    font-size: 2rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.header-actions {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.admin-content {
    padding: 2rem;
}

.exam-preview-header {
    margin-bottom: 2rem;
}

.exam-info-card {
    background: white;
    border-radius: 1rem;
    padding: 2rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
}

.exam-info-card h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 1rem;
}

.exam-description {
    color: #64748b;
    font-size: 1rem;
    line-height: 1.6;
    margin-bottom: 1.5rem;
}

.exam-meta {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem;
    background: #f8fafc;
    border-radius: 0.5rem;
    border: 1px solid #e5e7eb;
}

.meta-item i {
    color: #3b82f6;
    font-size: 1.1rem;
}

.meta-item span {
    font-weight: 600;
    color: #374151;
}

.exam-instructions {
    background: #fef3c7;
    border: 1px solid #f59e0b;
    border-radius: 0.5rem;
    padding: 1rem;
}

.exam-instructions h4 {
    font-weight: 600;
    color: #92400e;
    margin-bottom: 0.5rem;
}

.exam-instructions p {
    color: #78350f;
    margin: 0;
}

.questions-preview {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.question-preview-card {
    background: white;
    border-radius: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
    overflow: hidden;
}

.question-header {
    padding: 1.5rem 2rem;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.question-header h4 {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

.question-meta {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.question-type {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 1rem;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.question-points {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 1rem;
    font-size: 0.75rem;
    font-weight: 600;
}

.question-content {
    padding: 2rem;
}

.question-text {
    margin-bottom: 1.5rem;
    font-size: 1rem;
    line-height: 1.6;
    color: #374151;
}

.question-options {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.option-item {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 0.5rem;
    border: 1px solid #e5e7eb;
}

.option-radio,
.option-checkbox {
    color: #6b7280;
    font-size: 1.1rem;
    margin-top: 0.125rem;
}

.option-text {
    flex: 1;
    color: #374151;
}

.text-answer-placeholder textarea,
.code-answer-placeholder textarea {
    width: 100%;
    padding: 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 0.5rem;
    background: #f9fafb;
    color: #6b7280;
    font-family: inherit;
    resize: vertical;
}

.code-answer-placeholder textarea {
    font-family: 'Courier New', monospace;
}

.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    background: white;
    border-radius: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.empty-state-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 2rem;
    color: white;
    font-size: 2rem;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.empty-state h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 1rem;
}

.empty-state p {
    color: #64748b;
    font-size: 1.1rem;
    margin-bottom: 2rem;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    font-weight: 600;
    text-decoration: none;
    border-radius: 0.75rem;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.875rem;
}

.btn-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
}

.btn-warning:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4);
    background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
}

.btn-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
    background: linear-gradient(135deg, #059669 0%, #047857 100%);
}

.btn-outline-secondary {
    background: transparent;
    border: 2px solid #6b7280;
    color: #6b7280;
}

.btn-outline-secondary:hover {
    background: #6b7280;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(107, 114, 128, 0.3);
}

.btn-lg {
    padding: 0.875rem 2rem;
    font-size: 1rem;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .admin-sidebar {
        transform: translateX(-100%);
        transition: transform 0.3s ease;
    }

    .admin-main {
        margin-left: 0;
    }

    .exam-meta {
        grid-template-columns: 1fr;
    }

    .question-header {
        flex-direction: column;
        align-items: stretch;
        gap: 1rem;
    }
}

@media (max-width: 768px) {
    .admin-header {
        padding: 1.5rem;
    }

    .admin-header h1 {
        font-size: 1.5rem;
    }

    .header-actions {
        flex-direction: column;
        align-items: stretch;
        gap: 0.5rem;
    }

    .admin-content {
        padding: 1rem;
    }

    .exam-info-card {
        padding: 1.5rem;
    }

    .question-content {
        padding: 1.5rem;
    }

    .empty-state {
        padding: 3rem 1rem;
    }

    .empty-state-icon {
        width: 60px;
        height: 60px;
        font-size: 1.5rem;
    }
}
</style>