<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
if (!hasRole('instructor') && !hasPermission('can_create_assessments')) redirect('dashboard.php');
$db = Database::getInstance();
$user = getCurrentUser();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$assessment_id = isset($_GET['assessment_id']) ? (int)$_GET['assessment_id'] : 0;
$question = null;
if ($id) {
    $question = $db->get("SELECT * FROM assessment_questions WHERE id = ? AND assessment_id IN (SELECT id FROM assessments WHERE created_by = ?)", [$id, $user['id']]);
    if (!$question) redirect('assessments.php');
    $assessment_id = $question['assessment_id'];
}

$assessment = $db->get("SELECT * FROM assessments WHERE id = ? AND created_by = ?", [$assessment_id, $user['id']]);
if (!$assessment) redirect('assessments.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $question_text = trim($_POST['question_text'] ?? '');
    $question_type = $_POST['question_type'] ?? 'multiple_choice';
    $options = [];
    if ($question_type === 'multiple_choice') {
        $rawOpts = explode("\n", trim($_POST['options'] ?? ''));
        foreach ($rawOpts as $r) if (trim($r) !== '') $options[] = trim($r);
    }
    $correct_answer = trim($_POST['correct_answer'] ?? '');
    $points = (float)($_POST['points'] ?? 1);

    if ($id) {
        $db->query("UPDATE assessment_questions SET question_text = ?, question_type = ?, options = ?, correct_answer = ?, points = ? WHERE id = ?", [$question_text, $question_type, !empty($options) ? json_encode($options) : null, $correct_answer, $points, $id]);
        header('Location: ' . APP_URL . '/lms/assessment_questions.php?assessment_id=' . $assessment_id);
        exit;
    } else {
        $db->query("INSERT INTO assessment_questions (assessment_id, question_text, question_type, options, correct_answer, points) VALUES (?, ?, ?, ?, ?, ?)", [$assessment_id, $question_text, $question_type, !empty($options) ? json_encode($options) : null, $correct_answer, $points]);
        header('Location: ' . APP_URL . '/lms/assessment_questions.php?assessment_id=' . $assessment_id);
        exit;
    }
}

$pageTitle = $id ? 'Edit Question' : 'New Question';
include __DIR__ . '/includes/header.php';
?>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header"><h5 class="m-0"><?php echo htmlspecialchars($pageTitle); ?></h5></div>
            <div class="card-body">
                <form method="post">
                    <div class="mb-3">
                        <label class="form-label">Question Text</label>
                        <textarea class="form-control" name="question_text" required><?php echo htmlspecialchars($question['question_text'] ?? ''); ?></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Type</label>
                            <select name="question_type" id="question_type" class="form-select">
                                <option value="multiple_choice" <?php echo (isset($question['question_type']) && $question['question_type'] === 'multiple_choice') ? 'selected' : ''; ?>>Multiple Choice</option>
                                <option value="true_false" <?php echo (isset($question['question_type']) && $question['question_type'] === 'true_false') ? 'selected' : ''; ?>>True / False</option>
                                <option value="short_answer" <?php echo (isset($question['question_type']) && $question['question_type'] === 'short_answer') ? 'selected' : ''; ?>>Short Answer</option>
                                <option value="essay" <?php echo (isset($question['question_type']) && $question['question_type'] === 'essay') ? 'selected' : ''; ?>>Essay</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Points</label>
                            <input type="number" step="0.5" class="form-control" name="points" value="<?php echo htmlspecialchars($question['points'] ?? 1); ?>" />
                        </div>
                    </div>

                    <div class="mb-3" id="options_block" style="display: <?php echo (isset($question['question_type']) && $question['question_type'] === 'multiple_choice') ? 'block' : 'none'; ?>">
                        <label class="form-label">Options (one per line)</label>
                        <textarea class="form-control" name="options"><?php echo isset($question['options']) ? implode("\n", json_decode($question['options'], true) ?: []) : ''; ?></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Correct Answer</label>
                        <input class="form-control" name="correct_answer" value="<?php echo htmlspecialchars($question['correct_answer'] ?? ''); ?>" />
                        <small class="form-text text-muted">For multiple choice, enter the option text exactly as listed above. For true/false use 'true' or 'false'.</small>
                    </div>

                    <div>
                        <button class="btn btn-success">Save</button>
                        <a class="btn btn-outline-secondary ms-2" href="<?php echo APP_URL; ?>/lms/assessment_questions.php?assessment_id=<?php echo (int)$assessment_id; ?>">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('question_type').addEventListener('change', function(){
    var v = this.value;
    document.getElementById('options_block').style.display = v === 'multiple_choice' ? 'block' : 'none';
});
</script>

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