<?php
$db = getDB();

// ---------- Determine action ----------
$action = $_GET['action'] ?? 'list';
if (!in_array($action, ['list', 'create', 'update', 'delete'])) {
    $action = 'list';
}

// ---------- Lesson filter (from query string) ----------
$lesson_id = $_GET['lesson_id'] ?? null;
if ($lesson_id !== null) $lesson_id = intval($lesson_id);

// ---------- Messages ----------
$errors = [];
$success = $_GET['success'] ?? '';

// ---------- Helper: fetch a single question ----------
function getQuestionById($db, $id): ?array {
    $stmt = $db->prepare("SELECT * FROM exam_questions WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// ---------- Handle DELETE ----------
if ($action === 'delete' && isset($_GET['id'])) {
    $stmt = $db->prepare("DELETE FROM exam_questions WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $redirect = 'index.php?page=exam_questions&success=deleted';
    if ($lesson_id) $redirect .= "&lesson_id=$lesson_id";
    header('Location: ' . $redirect);
    exit;
}

// ---------- Handle CREATE / UPDATE form submission ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['create', 'update'])) {
    $question        = trim($_POST['question'] ?? '');
    $word            = trim($_POST['word'] ?? '');
    $form_lesson_id  = intval($_POST['lesson_id'] ?? 0);
    $correct_option  = intval($_POST['correct_option'] ?? 0);

    // Collect options from text fields (up to 6, but minimum 2)
    $rawOptions = [];
    $option1 = trim($_POST['option_1'] ?? '');
    $option2 = trim($_POST['option_2'] ?? '');
    $option3 = trim($_POST['option_3'] ?? '');
    $option4 = trim($_POST['option_4'] ?? '');
    $option5 = trim($_POST['option_5'] ?? '');
    $option6 = trim($_POST['option_6'] ?? '');

    // Build an array of non-empty options, preserving index starting at 1
    $tmp = [$option1, $option2, $option3, $option4, $option5, $option6];
    foreach ($tmp as $idx => $val) {
        if ($val !== '') {
            $rawOptions[$idx + 1] = $val;  // 1-based index
        }
    }

    // Validation
    if ($question === '') {
        $errors[] = 'Question text is required.';
    }
    if ($form_lesson_id <= 0) {
        $errors[] = 'A lesson must be selected.';
    } else {
        $check = $db->prepare("SELECT id FROM lessons WHERE id = ?");
        $check->bind_param("i", $form_lesson_id);
        $check->execute();
        if ($check->get_result()->num_rows === 0) {
            $errors[] = 'The selected lesson does not exist.';
        }
    }
    if (count($rawOptions) < 2) {
        $errors[] = 'At least two options are required.';
    }
    if (!isset($rawOptions[$correct_option])) {
        $errors[] = 'The selected correct option is invalid or empty.';
    }

    if (empty($errors)) {
        // Convert options array to JSON (sequential array)
        $optionsJSON = json_encode(array_values($rawOptions));

        // Recalculate correct_option as a 0‑based index to store
        $optKeys = array_keys($rawOptions);
        $correctIndex = array_search($correct_option, $optKeys); // 0‑based position

        if ($correctIndex === false) {
            $errors[] = 'Correct option not found.';
        } else {
            if ($action === 'create') {
                $stmt = $db->prepare("INSERT INTO exam_questions (lesson_id, question, word, options, correct_option) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param("isssi", $form_lesson_id, $question, $word, $optionsJSON, $correctIndex);
                $stmt->execute();
            } elseif ($action === 'update' && isset($_GET['id'])) {
                $stmt = $db->prepare("UPDATE exam_questions SET lesson_id=?, question=?, word=?, options=?, correct_option=? WHERE id=?");
                $stmt->bind_param("isssii", $form_lesson_id, $question, $word, $optionsJSON, $correctIndex, $_GET['id']);
                $stmt->execute();
            }
            $msg = ($action === 'create') ? 'created' : 'updated';
            $redirect = 'index.php?page=exam_questions&success=' . $msg;
            if ($lesson_id) $redirect .= "&lesson_id=$lesson_id";
            header('Location: ' . $redirect);
            exit;
        }
    }
}

// ---------- Load existing question for edit ----------
$questionData = null;
if ($action === 'update' && isset($_GET['id'])) {
    $questionData = getQuestionById($db, $_GET['id']);
    if (!$questionData) {
        echo '<div class="alert alert-danger">Question not found.</div>';
        $action = 'list';
    } else {
        // Decode options for display
        $questionData['options_array'] = json_decode($questionData['options'], true) ?: [];
    }
}

// ---------- Success banners ----------
if ($success === 'created') {
    echo '<div class="alert alert-success">Exam question created successfully.</div>';
} elseif ($success === 'updated') {
    echo '<div class="alert alert-success">Exam question updated successfully.</div>';
} elseif ($success === 'deleted') {
    echo '<div class="alert alert-success">Exam question deleted.</div>';
}

// ---------- LIST view ----------
if ($action === 'list'):
    // Fetch lesson name if filtered
    $lessonName = '';
    if ($lesson_id) {
        $lstmt = $db->prepare("SELECT title FROM lessons WHERE id = ?");
        $lstmt->bind_param("i", $lesson_id);
        $lstmt->execute();
        $lres = $lstmt->get_result()->fetch_assoc();
        $lessonName = $lres['title'] ?? '';
    }
?>
    <h3>Exam Questions <?= $lesson_id ? 'for lesson: ' . htmlspecialchars($lessonName) . " (ID $lesson_id)" : '' ?></h3>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <form class="d-flex" method="get">
            <input type="hidden" name="page" value="exam_questions">
            <?php if ($lesson_id): ?>
                <input type="hidden" name="lesson_id" value="<?= $lesson_id ?>">
            <?php endif; ?>
            <input type="text" name="search" class="form-control me-2" placeholder="Search question or word"
                   value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            <button type="submit" class="btn btn-outline-secondary"><i class="fa fa-search"></i></button>
        </form>
        <a href="?page=exam_questions&action=create<?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-primary">
            <i class="fa fa-plus me-1"></i> New Question
        </a>
    </div>

    <?php
    // ---------- Pagination & search ----------
    $pageNum = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
    $limit = 50;
    $offset = ($pageNum - 1) * $limit;

    $where = [];
    $params = [];
    $types = '';

    if ($lesson_id) {
        $where[] = "q.lesson_id = ?";
        $params[] = $lesson_id;
        $types .= 'i';
    }
    if (!empty($_GET['search'])) {
        $where[] = "(q.question LIKE ? OR q.word LIKE ?)";
        $searchParam = "%" . $_GET['search'] . "%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $types .= 'ss';
    }

    $whereSQL = '';
    if (!empty($where)) {
        $whereSQL = 'WHERE ' . implode(' AND ', $where);
    }

    // Count
    $countSQL = "SELECT COUNT(*) FROM exam_questions q $whereSQL";
    $stmt = $db->prepare($countSQL);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total = $stmt->get_result()->fetch_row()[0];
    $totalPages = ceil($total / $limit);

    // Fetch questions with lesson title
    $sql = "SELECT q.*, l.title AS lesson_title 
            FROM exam_questions q 
            JOIN lessons l ON q.lesson_id = l.id 
            $whereSQL 
            ORDER BY q.lesson_id, q.id 
            LIMIT ? OFFSET ?";
    $types .= 'ii';
    $params[] = $limit;
    $params[] = $offset;
    $stmt = $db->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $questions = $stmt->get_result();
    ?>

    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Lesson</th>
                    <th>Question</th>
                    <th>Word</th>
                    <th>Correct Answer</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($questions->num_rows > 0): ?>
                <?php while($row = $questions->fetch_assoc()): 
                    $optionsArr = json_decode($row['options'], true) ?: [];
                    $correctIdx = intval($row['correct_option']);
                    $correctText = isset($optionsArr[$correctIdx]) ? htmlspecialchars($optionsArr[$correctIdx]) : '❌';
                ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['lesson_title']) ?> (<?= $row['lesson_id'] ?>)</td>
                    <td><?= htmlspecialchars($row['question']) ?></td>
                    <td><?= htmlspecialchars($row['word'] ?? '') ?></td>
                    <td><span class="badge bg-success"><?= $correctText ?></span></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="?page=exam_questions&action=update&id=<?= $row['id'] ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-outline-warning" title="Edit">
                                <i class="fa fa-edit"></i>
                            </a>
                            <a href="?page=exam_questions&action=delete&id=<?= $row['id'] ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>"
                               class="btn btn-outline-danger" title="Delete"
                               onclick="return confirm('Delete this question?')">
                                <i class="fa fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="6" class="text-center">No questions found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav>
        <ul class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $pageNum ? 'active' : '' ?>">
                    <a class="page-link" href="?page=exam_questions&p=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?><?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>">
                        <?= $i ?>
                    </a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>

<?php
// ---------- CREATE / UPDATE form ----------
else:
    // Build list of lessons for the dropdown
    $lessonList = $db->query("SELECT l.id, l.title, c.title AS course_title FROM lessons l JOIN courses c ON l.course_id = c.id ORDER BY c.sort_order, l.order");
?>
    <h3><?= $action === 'create' ? 'Create New Exam Question' : 'Edit Exam Question' ?></h3>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $err): ?>
                    <li><?= htmlspecialchars($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form method="post" class="card p-4" style="max-width: 800px;">
        <div class="mb-3">
            <label for="lesson_id" class="form-label">Lesson *</label>
            <select name="lesson_id" id="lesson_id" class="form-select" required>
                <option value="">-- Select a lesson --</option>
                <?php while($l = $lessonList->fetch_assoc()): 
                    $selected = ($questionData['lesson_id'] ?? $_POST['lesson_id'] ?? $lesson_id ?? '') == $l['id'];
                ?>
                    <option value="<?= $l['id'] ?>" <?= $selected ? 'selected' : '' ?>>
                        <?= htmlspecialchars($l['course_title']) ?> → <?= htmlspecialchars($l['title']) ?> (ID: <?= $l['id'] ?>)
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="mb-3">
            <label for="question" class="form-label">Question text *</label>
            <textarea name="question" id="question" class="form-control" rows="2" required><?= htmlspecialchars($questionData['question'] ?? $_POST['question'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label for="word" class="form-label">Word (optional)</label>
            <input type="text" name="word" id="word" class="form-control"
                   value="<?= htmlspecialchars($questionData['word'] ?? $_POST['word'] ?? '') ?>">
        </div>

        <h5>Options</h5>
        <?php
        // For edit, pre-fill options from stored JSON array (sequential, so index 0 = option 1)
        $existingOptions = [];
        if ($action === 'update' && isset($questionData['options_array'])) {
            $existingOptions = $questionData['options_array'];  // 0‑based sequential array
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Retain posted values
            for ($i=1; $i<=6; $i++) {
                $existingOptions[$i-1] = $_POST["option_$i"] ?? '';
            }
        }
        // Determine correct option index (0‑based) for radio pre-selection
        $correctIdx = -1;
        if (isset($questionData['correct_option'])) {
            $correctIdx = intval($questionData['correct_option']);
        } elseif (isset($_POST['correct_option'])) {
            // In POST we get the number (1‑based)
            $correctIdx = intval($_POST['correct_option']) - 1;
        }

        for ($i = 1; $i <= 6; $i++): 
            $optValue = $existingOptions[$i-1] ?? '';
        ?>
        <div class="row mb-2 align-items-center">
            <div class="col-md-10">
                <div class="input-group">
                    <span class="input-group-text">Option <?= $i ?></span>
                    <input type="text" name="option_<?= $i ?>" class="form-control" value="<?= htmlspecialchars($optValue) ?>">
                </div>
            </div>
            <div class="col-md-2 form-check">
                <input type="radio" name="correct_option" value="<?= $i ?>" class="form-check-input" id="correct_<?= $i ?>"
                       <?= ($correctIdx === ($i-1)) ? 'checked' : '' ?> >
                <label for="correct_<?= $i ?>" class="form-check-label">Correct</label>
            </div>
        </div>
        <?php endfor; ?>
        <small class="text-muted d-block mb-3">Fill at least two options and select the correct one.</small>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-success">
                <i class="fa fa-save me-1"></i> Save
            </button>
            <a href="?page=exam_questions<?= $lesson_id ? "&lesson_id=$lesson_id" : '' ?>" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
<?php endif; ?>