<?php
require_once __DIR__ . "/auth.php";
require_role(['super','admin']);
require_once __DIR__ . "/../includes/db.php";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset('utf8mb4');

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

/* ----------------------
   Check exam_id
---------------------- */
if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
    $_SESSION['error'] = "Please select an exam before adding questions.";
    header("Location: add_question_select.php?mode=single");
    exit;
}
$exam_id = (int)$_GET['exam_id'];

/* ----------------------
   Fetch exam details
---------------------- */
$stmt = $conn->prepare("SELECT id, title, course_name, unit_exam FROM exams WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error'] = "Exam not found.";
    header("Location: add_question_select.php?mode=single");
    exit;
}
$exam = $result->fetch_assoc();
$stmt->close();

$message = "";

/* ----------------------
   Upload helper
---------------------- */
function uploadFile(array $file, array &$errors = [], string $fieldLabel = 'File'): ?string {
    if (!isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
        return null;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors[] = $fieldLabel . " upload failed.";
        return null;
    }

    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp3', 'wav', 'ogg', 'm4a'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExt, true)) {
        $errors[] = $fieldLabel . " must be an image or audio file.";
        return null;
    }

    if (($file['size'] ?? 0) > 10 * 1024 * 1024) {
        $errors[] = $fieldLabel . " must be smaller than 10MB.";
        return null;
    }

    $targetDir = __DIR__ . "/../uploads/";
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $safeName = preg_replace('/[^A-Za-z0-9_\.-]/', '_', basename($file['name']));
    $filename = time() . "_" . bin2hex(random_bytes(4)) . "_" . $safeName;
    $targetFilePath = $targetDir . $filename;

    if (move_uploaded_file($file["tmp_name"], $targetFilePath)) {
        return $filename;
    }

    $errors[] = $fieldLabel . " could not be saved.";
    return null;
}

/* ----------------------
   Save question
---------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $question_text   = trim($_POST['question_text'] ?? '');
    $option_1        = trim($_POST['option_1'] ?? '');
    $option_2        = trim($_POST['option_2'] ?? '');
    $option_3        = trim($_POST['option_3'] ?? '');
    $option_4        = trim($_POST['option_4'] ?? '');
    $correct_option  = (int)($_POST['correct_option'] ?? 0);

    $errors = [];

    if ($question_text === '' && empty($_FILES['question_file']['name'])) {
        $errors[] = "Please enter question text or upload a question file.";
    }

    if ($correct_option < 1 || $correct_option > 4) {
        $errors[] = "Correct option must be between 1 and 4.";
    }

    $options = [$option_1, $option_2, $option_3, $option_4];
    $optionFiles = [
        !empty($_FILES['option_1_file']['name']),
        !empty($_FILES['option_2_file']['name']),
        !empty($_FILES['option_3_file']['name']),
        !empty($_FILES['option_4_file']['name']),
    ];

    for ($i = 0; $i < 4; $i++) {
        if ($options[$i] === '' && !$optionFiles[$i]) {
            $errors[] = "Option " . ($i + 1) . " must have text or file.";
        }
    }

    $question_file = uploadFile($_FILES['question_file'] ?? [], $errors, 'Question file');
    $option_1_file = uploadFile($_FILES['option_1_file'] ?? [], $errors, 'Option 1 file');
    $option_2_file = uploadFile($_FILES['option_2_file'] ?? [], $errors, 'Option 2 file');
    $option_3_file = uploadFile($_FILES['option_3_file'] ?? [], $errors, 'Option 3 file');
    $option_4_file = uploadFile($_FILES['option_4_file'] ?? [], $errors, 'Option 4 file');

    if (empty($errors)) {
        $stmt = $conn->prepare("
            INSERT INTO questions
            (
                exam_id,
                question_text,
                question_file,
                option_1,
                option_1_file,
                option_2,
                option_2_file,
                option_3,
                option_3_file,
                option_4,
                option_4_file,
                correct_option
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->bind_param(
            "issssssssssi",
            $exam_id,
            $question_text,
            $question_file,
            $option_1,
            $option_1_file,
            $option_2,
            $option_2_file,
            $option_3,
            $option_3_file,
            $option_4,
            $option_4_file,
            $correct_option
        );

        if ($stmt->execute()) {
            $message = "<div class='alert alert-success alert-modern'>Question added successfully!</div>";

            $_POST = [];
        } else {
            $message = "<div class='alert alert-danger alert-modern'>Error while saving question.</div>";
        }
        $stmt->close();
    } else {
        $message = "<div class='alert alert-danger alert-modern'><ul class='mb-0 ps-3'><li>" . implode("</li><li>", array_map('h', $errors)) . "</li></ul></div>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Add Question</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root{
            --ec-blue:#0b2c61;
            --ec-blue-dark:#071f49;
            --ec-red:#e42424;
            --ec-bg:#f5f7fb;
        }



        .page-wrap{
            max-width: 1280px;
        }

        .page-head{
            margin-top: 22px;
            margin-bottom: 18px;
        }

        .head-box{
            width: 100%;
            background: linear-gradient(135deg,var(--ec-blue),var(--ec-blue-dark));
            color: #fff;
            border-radius: 18px;
            padding: 18px 22px;
            box-shadow: 0 12px 26px rgba(11,44,97,.14);
        }

        .card-neo{
            border: 0;
            border-radius: 18px;
            box-shadow: 0 14px 36px rgba(15,23,42,.10);
        }

        .section-title{
            font-size: 1.9rem;
            font-weight: 800;
            color: #FFFFFF;
            margin: 0 0 6px 0;
        }

        .section-sub{
            color: #FFFFFF;
            margin: 0;
            font-size: .98rem;
        }

        .form-label{
            font-weight: 700;
            color: #24304a;
        }

        .form-control{
            min-height: 48px;
            border-radius: 12px;
        }

        textarea.form-control{
            min-height: 120px;
        }

        .btn-theme{
            background: var(--ec-red);
            border-color: var(--ec-red);
            color: #fff;
            border-radius: 12px;
            padding: 10px 18px;
            font-weight: 700;
        }

        .btn-theme:hover{
            background: #c71f1f;
            border-color: #c71f1f;
            color:#fff;
        }

        .btn-soft{
            border-radius: 12px;
            padding: 10px 18px;
            font-weight: 700;
        }

        .alert-modern{
            border-radius: 14px;
        }

        .option-box{
            border: 1px solid #edf1f7;
            border-radius: 16px;
            padding: 16px;
            background: #fafcff;
            height: 100%;
        }
    </style>
</head>
<body class="py-4">

<?php
$__topbar_candidates = [
    __DIR__ . '/../includes/topbar.php',
    __DIR__ . '/includes/topbar.php',
    __DIR__ . '/../admin/includes/topbar.php',
];

$__topbar_loaded = false;
foreach ($__topbar_candidates as $__p) {
    if (is_file($__p)) {
        require_once $__p;
        $__topbar_loaded = true;
        break;
    }
}

if (!$__topbar_loaded) {
    echo "<!-- topbar.php not found in expected paths -->";
}
?>

<div class="container-fluid px-3 px-lg-4 page-wrap">

    <div class="page-head">
        <div class="head-box">
            <div class="section-title">Add Question</div>
            <p class="section-sub">
                <?= h($exam['title']) ?> — <?= h($exam['course_name']) ?> — <?= h($exam['unit_exam']) ?>
            </p>
        </div>
    </div>

    <?= $message ?>

    <div class="card card-neo">
        <div class="card-body p-4 p-lg-4">
            <form method="post" enctype="multipart/form-data">
                <div class="mb-3">
                    <label class="form-label">Question Text</label>
                    <textarea name="question_text" class="form-control" rows="4"><?= h($_POST['question_text'] ?? '') ?></textarea>
                </div>

                <div class="mb-4">
                    <label class="form-label">Question File (Image/Audio)</label>
                    <input type="file" name="question_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp,.mp3,.wav,.ogg,.m4a">
                </div>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="option-box">
                            <label class="form-label">Option 1</label>
                            <input type="text" name="option_1" class="form-control mb-2" value="<?= h($_POST['option_1'] ?? '') ?>">
                            <input type="file" name="option_1_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp,.mp3,.wav,.ogg,.m4a">
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="option-box">
                            <label class="form-label">Option 2</label>
                            <input type="text" name="option_2" class="form-control mb-2" value="<?= h($_POST['option_2'] ?? '') ?>">
                            <input type="file" name="option_2_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp,.mp3,.wav,.ogg,.m4a">
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="option-box">
                            <label class="form-label">Option 3</label>
                            <input type="text" name="option_3" class="form-control mb-2" value="<?= h($_POST['option_3'] ?? '') ?>">
                            <input type="file" name="option_3_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp,.mp3,.wav,.ogg,.m4a">
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="option-box">
                            <label class="form-label">Option 4</label>
                            <input type="text" name="option_4" class="form-control mb-2" value="<?= h($_POST['option_4'] ?? '') ?>">
                            <input type="file" name="option_4_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp,.mp3,.wav,.ogg,.m4a">
                        </div>
                    </div>
                </div>

                <div class="mt-4 mb-4">
                    <label class="form-label">Correct Option (1-4)</label>
                    <input type="number" name="correct_option" class="form-control" min="1" max="4" required value="<?= h($_POST['correct_option'] ?? '') ?>">
                </div>

                <div class="d-flex gap-2 flex-wrap">
                    <button type="submit" class="btn btn-theme">Add Question</button>
                    <a href="add_question_select.php?mode=single" class="btn btn-secondary btn-soft">Back</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('.dropdown-toggle').forEach(function (el) {
    new bootstrap.Dropdown(el);
  });
});
</script>
</body>
</html>