<?php
session_start();
require_once "db_connection.php"; // change to your DB connection

// ======== UPDATE HANDLER ========
if (isset($_POST['update_question'])) {
    $id = $_POST['edit_question_id'] ?? null;
    $question_text = $_POST['question_text'] ?? '';
    $question_type = $_POST['question_type'] ?? '';
    $marks = $_POST['marks'] ?? 0;
    $correct_answer = $_POST['correct_answer'] ?? '';
    $option_a = $_POST['option_a'] ?? '';
    $option_b = $_POST['option_b'] ?? '';
    $option_c = $_POST['option_c'] ?? '';
    $option_d = $_POST['option_d'] ?? '';

    // Handle image upload
    $image_sql = "";
    if (!empty($_FILES['question_image']['name'])) {
        $target_dir = "uploads/questions/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
        $image_path = $target_dir . basename($_FILES['question_image']['name']);
        move_uploaded_file($_FILES['question_image']['tmp_name'], $image_path);
        $image_sql = ", question_image = '" . $conn->real_escape_string($image_path) . "'";
    }

    $stmt = $conn->prepare("
        UPDATE questions SET 
            question_text = ?, 
            question_type = ?, 
            marks = ?, 
            option_a = ?, 
            option_b = ?, 
            option_c = ?, 
            option_d = ?, 
            correct_answer = ? 
            $image_sql
        WHERE id = ?
    ");

    $stmt->bind_param(
        "ssdsssssi",
        $question_text,
        $question_type,
        $marks,
        $option_a,
        $option_b,
        $option_c,
        $option_d,
        $correct_answer,
        $id
    );

    if ($stmt->execute()) {
        $_SESSION['msg'] = "Question updated successfully!";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Error updating question: " . $stmt->error;
        $_SESSION['type'] = "error";
    }

    $stmt->close();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ======== FETCH QUESTIONS ========
$questions = $conn->query("SELECT * FROM questions ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Questions</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<div class="container mt-5">
    <h2>Questions List</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Question</th>
                <th>Type</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($q = $questions->fetch_assoc()): ?>
                <tr>
                    <td><?= $q['id'] ?></td>
                    <td><?= htmlspecialchars($q['question_text']) ?></td>
                    <td><?= strtoupper($q['question_type']) ?></td>
                    <td>
                        <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editModal<?= $q['id'] ?>">Edit</button>
                    </td>
                </tr>

                <!-- ======== EDIT MODAL ======== -->
                <div class="modal fade" id="editModal<?= $q['id'] ?>" tabindex="-1" aria-hidden="true">
                  <div class="modal-dialog modal-lg">
                    <form method="post" enctype="multipart/form-data">
                      <input type="hidden" name="edit_question_id" value="<?= $q['id'] ?>">
                      <div class="modal-content">
                        <div class="modal-header bg-warning">
                          <h5 class="modal-title">Edit Question</h5>
                          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label>Question</label>
                                <textarea name="question_text" class="form-control" required><?= htmlspecialchars($q['question_text']) ?></textarea>
                            </div>

                            <div class="mb-3">
                                <label>Question Type</label>
                                <select name="question_type" class="form-control question-type-selector" id="question-type-<?= $q['id'] ?>" onchange="toggleEditOptions(<?= $q['id'] ?>)">
                                    <option value="mcq" <?= $q['question_type']=='mcq'?'selected':'' ?>>MCQ</option>
                                    <option value="theory" <?= $q['question_type']=='theory'?'selected':'' ?>>Theory</option>
                                </select>
                            </div>

                            <div class="mcq-options" id="mcq-options-<?= $q['id'] ?>" <?= $q['question_type'] != 'mcq' ? 'style="display:none;"' : '' ?>>
                                <div class="row">
                                    <?php foreach(['a','b','c','d'] as $opt): ?>
                                    <div class="col-md-6 mb-2">
                                        <label>Option <?= strtoupper($opt) ?></label>
                                        <input type="text" name="option_<?= $opt ?>" class="form-control" value="<?= htmlspecialchars($q["option_$opt"]) ?>">
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="mb-3" id="edit-correct-answer-<?= $q['id'] ?>" <?= $q['question_type'] != 'mcq' ? 'style="display:none;"' : '' ?>>
                                <label>Correct Answer</label>
                                <input type="text" name="correct_answer" class="form-control" value="<?= htmlspecialchars($q['correct_answer']) ?>">
                            </div>

                            <div class="mb-3">
                                <label>Marks</label>
                                <input type="number" step="0.01" name="marks" class="form-control" value="<?= $q['marks'] ?>" required>
                            </div>

                            <div class="mb-3">
                                <label>Current Image</label><br>
                                <?php if(!empty($q['question_image'])): ?>
                                    <img src="<?= htmlspecialchars($q['question_image']) ?>" width="100"><br>
                                <?php else: ?>
                                    No image<br>
                                <?php endif; ?>
                                <label>Change Image</label>
                                <input type="file" name="question_image" class="form-control">
                            </div>
                        </div>

                        <div class="modal-footer">
                            <button type="submit" name="update_question" class="btn btn-success">Save Changes</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
function toggleEditOptions(id) {
    const type = document.getElementById('question-type-' + id).value;
    const mcqBlock = document.getElementById('mcq-options-' + id);
    const answerBlock = document.getElementById('edit-correct-answer-' + id);
    if(type === 'mcq'){
        mcqBlock.style.display = 'block';
        answerBlock.style.display = 'block';
    } else {
        mcqBlock.style.display = 'none';
        answerBlock.style.display = 'none';
    }
}

// ===== SweetAlert for update =====
<?php if(!empty($_SESSION['msg'])): ?>
Swal.fire({
    text: <?= json_encode($_SESSION['msg']) ?>,
    icon: <?= json_encode($_SESSION['type']) ?>,
    confirmButtonText: 'OK'
});
<?php 
unset($_SESSION['msg'], $_SESSION['type']);
endif; 
?>
</script>
</body>
</html>
