<?php
session_start();
$projectRoot = dirname(__DIR__);
require_once $projectRoot . '/config/database.php';

// Security: Admin/Sub-admin only
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

$q_id = $_GET['id'] ?? null;
$exam_id = $_GET['exam_id'] ?? null;

if (!$q_id) die("Invalid Question ID");

// 1. Fetch Question Data
$stmt = $pdo->prepare("SELECT * FROM questions WHERE id = ?");
$stmt->execute([$q_id]);
$q = $stmt->fetch();

if (!$q) die("Question not found.");

// 2. Handle the Update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $text = $_POST['question_text'];
    $oa = $_POST['option_a'];
    $ob = $_POST['option_b'];
    $oc = $_POST['option_c'];
    $od = $_POST['option_d'];
    $correct = $_POST['correct_option'];
    $image_path = $q['image_path']; // Keep old image by default

    // Handle Image Upload if provided
    if (!empty($_FILES['q_image']['name'])) {
        $targetDir = "../assets/img/cbt/";
        $fileName = time() . '_' . basename($_FILES['q_image']['name']);
        $targetFilePath = $targetDir . $fileName;

        if (move_uploaded_file($_FILES['q_image']['tmp_name'], $targetFilePath)) {
            $image_path = $fileName;
        }
    }

    $update = $pdo->prepare("UPDATE questions SET 
        question_text = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_option = ?, image_path = ? 
        WHERE id = ?");
    
    if ($update->execute([$text, $oa, $ob, $oc, $od, $correct, $image_path, $q_id])) {
        header("Location: review_questions.php?id=" . ($exam_id ?? $q['exam_id']) . "&msg=Updated");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Question | Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Inter', sans-serif; background: #f4f7f6; padding: 40px; }
        .edit-container { max-width: 600px; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin: 0 auto; }
        .form-group { margin-bottom: 15px; }
        label { display: block; font-weight: bold; margin-bottom: 5px; font-size: 14px; }
        input, textarea, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; }
        .btn-save { background: #27ae60; color: white; border: none; padding: 12px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 10px; }
        .preview-img { max-width: 150px; margin-top: 10px; border-radius: 5px; border: 1px solid #eee; }
    </style>
</head>
<body>

<div class="edit-container">
    <h3 style="margin-top:0;"><i class="fa fa-edit"></i> Edit Question</h3>
    <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label>Question Text</label>
            <textarea name="question_text" rows="3" required><?= htmlspecialchars($q['question_text']) ?></textarea>
        </div>

        <?php if($q['image_path']): ?>
            <div class="form-group">
                <label>Current Image</label>
                <img src="../assets/img/cbt/<?= $q['image_path'] ?>" class="preview-img">
            </div>
        <?php endif; ?>

        <div class="form-group">
            <label>Change Image (Optional)</label>
            <input type="file" name="q_image" accept="image/*">
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <div class="form-group"><label>Option A</label><input type="text" name="option_a" value="<?= htmlspecialchars($q['option_a']) ?>" required></div>
            <div class="form-group"><label>Option B</label><input type="text" name="option_b" value="<?= htmlspecialchars($q['option_b']) ?>" required></div>
            <div class="form-group"><label>Option C</label><input type="text" name="option_c" value="<?= htmlspecialchars($q['option_c']) ?>" required></div>
            <div class="form-group"><label>Option D</label><input type="text" name="option_d" value="<?= htmlspecialchars($q['option_d']) ?>" required></div>
        </div>

        <div class="form-group">
            <label>Correct Option</label>
            <select name="correct_option">
                <option value="A" <?= $q['correct_option'] == 'A' ? 'selected' : '' ?>>Option A</option>
                <option value="B" <?= $q['correct_option'] == 'B' ? 'selected' : '' ?>>Option B</option>
                <option value="C" <?= $q['correct_option'] == 'C' ? 'selected' : '' ?>>Option C</option>
                <option value="D" <?= $q['correct_option'] == 'D' ? 'selected' : '' ?>>Option D</option>
            </select>
        </div>

        <button type="submit" class="btn-save">Update Question</button>
        <a href="review_questions.php?id=<?= $exam_id ?>" style="display:block; text-align:center; margin-top:15px; color:#666; text-decoration:none; font-size:14px;">Cancel & Go Back</a>
    </form>
</div>

</body>
</html>