<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
if (!hasRole('instructor') && !hasPermission('can_create_assessments')) redirect('dashboard.php');
$db = Database::getInstance();
$assessment_id = isset($_GET['assessment_id']) ? (int)$_GET['assessment_id'] : 0;
$assessment = $db->get("SELECT * FROM assessments WHERE id = ? AND created_by = ?", [$assessment_id, getCurrentUser()['id']]);
if (!$assessment) redirect('assessments.php');

$questions = $db->getAll("SELECT * FROM assessment_questions WHERE assessment_id = ? ORDER BY sort_order ASC", [$assessment_id]);

$pageTitle = 'Questions - ' . htmlspecialchars($assessment['title']);
include __DIR__ . '/includes/header.php';
?>

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="m-0">Questions</h5>
                <a href="<?php echo APP_URL; ?>/lms/assessment_questions_edit.php?assessment_id=<?php echo (int)$assessment_id; ?>" class="btn btn-primary btn-sm">New Question</a>
            </div>
            <div class="card-body">
                <?php if (empty($questions)): ?>
                    <p class="text-muted">No questions yet.</p>
                <?php else: ?>
                    <ol>
                        <?php foreach ($questions as $q): ?>
                            <li>
                                <strong><?php echo htmlspecialchars($q['question_text']); ?></strong>
                                <div class="text-muted small">Type: <?php echo htmlspecialchars($q['question_type']); ?> &bull; Points: <?php echo htmlspecialchars($q['points']); ?></div>
                                <div class="mt-2">
                                    <a class="btn btn-sm btn-outline-secondary" href="<?php echo APP_URL; ?>/lms/assessment_questions_edit.php?id=<?php echo (int)$q['id']; ?>&assessment_id=<?php echo (int)$assessment_id; ?>">Edit</a>
                                    <a class="btn btn-sm btn-outline-danger" href="<?php echo APP_URL; ?>/lms/assessment_questions_delete.php?id=<?php echo (int)$q['id']; ?>&assessment_id=<?php echo (int)$assessment_id; ?>" onclick="return confirm('Delete this question?');">Delete</a>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ol>
                <?php endif; ?>
                <a href="<?php echo APP_URL; ?>/lms/assessments.php" class="btn btn-outline-secondary">Back</a>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php';
