<?php
declare(strict_types=1);
session_start();

require_once __DIR__ . '/config/database.php';

/*
 * HALAMAN PEMBUATAN SOAL PILIHAN GANDA
 * Tahap awal: autentikasi guru belum diterapkan.
 * Akses paket menggunakan paket_id dari URL.
 */

if (empty($_SESSION['csrf_buat_soal'])) {
    $_SESSION['csrf_buat_soal'] = bin2hex(random_bytes(32));
}

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

function redirectSoal(int $paketId, ?int $soalId = null): never {
    $url = 'buat_soal.php?paket_id=' . $paketId;
    if ($soalId !== null && $soalId > 0) {
        $url .= '&soal_id=' . $soalId;
    }
    header('Location: ' . $url);
    exit;
}

function simpanGambar(string $field, ?string $gambarLama, string $folderUpload): ?string {
    if (!isset($_FILES[$field]) || $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) {
        return $gambarLama;
    }

    $file = $_FILES[$field];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Gagal mengunggah gambar pada ' . $field . '.');
    }
    if ($file['size'] > 4 * 1024 * 1024) {
        throw new RuntimeException('Ukuran setiap gambar maksimal 4 MB.');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
    ];
    if (!isset($allowed[$mime])) {
        throw new RuntimeException('Format gambar harus JPG, PNG, atau WEBP.');
    }

    if (!is_dir($folderUpload) && !mkdir($folderUpload, 0755, true) && !is_dir($folderUpload)) {
        throw new RuntimeException('Folder upload gambar tidak dapat dibuat.');
    }

    $namaFile = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
    $tujuan = $folderUpload . DIRECTORY_SEPARATOR . $namaFile;

    if (!move_uploaded_file($file['tmp_name'], $tujuan)) {
        throw new RuntimeException('Gambar gagal disimpan ke server.');
    }

    // Hapus file lama hanya jika berada di folder upload aplikasi ini.
    if ($gambarLama) {
        $lamaNama = basename($gambarLama);
        $lamaPath = $folderUpload . DIRECTORY_SEPARATOR . $lamaNama;
        if (is_file($lamaPath)) {
            @unlink($lamaPath);
        }
    }

    return 'uploads/soal/' . $namaFile;
}

/**
 * Membersihkan HTML editor agar hanya format teks dan gambar yang diperlukan tersimpan.
 * URL gambar dibatasi ke folder upload aplikasi.
 */
function bersihkanHtmlEditor(string $html): string {
    $html = trim($html);
    if ($html === '') return '';

    // Hapus blok berbahaya beserta isinya.
    $html = preg_replace('~<(script|style|iframe|object|embed|form)[^>]*>.*?</\\1>~is', '', $html) ?? '';
    $html = strip_tags($html, '<p><br><div><span><strong><b><em><i><u><s><sub><sup><ul><ol><li><blockquote><h1><h2><h3><h4><table><thead><tbody><tr><td><th><img>');
    // Hilangkan seluruh atribut event dan atribut style/class yang tidak diperlukan.
    $html = preg_replace("/\\s+on[a-z]+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)/i", '', $html) ?? $html;
    $html = preg_replace("/\\s+(style|class|id|contenteditable)\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)/i", '', $html) ?? $html;

    // Untuk gambar, hanya izinkan file lokal di uploads/soal.
    $html = preg_replace_callback('~<img\\b([^>]*)>~i', function ($m) {
        $attrs = $m[1];
        if (!preg_match("/\\bsrc\\s*=\\s*([\"'])(.*?)\\1/i", $attrs, $srcMatch)) return '';
        $src = html_entity_decode($srcMatch[2], ENT_QUOTES, 'UTF-8');
        if (!preg_match('~^uploads/soal/[a-zA-Z0-9._-]+$~', $src)) return '';
        $alt = '';
        if (preg_match("/\\balt\\s*=\\s*([\"'])(.*?)\\1/i", $attrs, $altMatch)) {
            $alt = ' alt="' . htmlspecialchars($altMatch[2], ENT_QUOTES, 'UTF-8') . '"';
        }
        return '<img src="' . htmlspecialchars($src, ENT_QUOTES, 'UTF-8') . '"' . $alt . '>';
    }, $html) ?? $html;

    return $html;
}

$paketId = filter_input(INPUT_GET, 'paket_id', FILTER_VALIDATE_INT);
if (!$paketId || $paketId < 1) {
    http_response_code(400);
    exit('Paket soal tidak valid. Buka halaman dari daftar identitas soal.');
}

$stmtPaket = $pdo->prepare("SELECT * FROM cbt_paket_soal WHERE id = :id LIMIT 1");
$stmtPaket->execute([':id' => $paketId]);
$paket = $stmtPaket->fetch(PDO::FETCH_ASSOC);

if (!$paket) {
    http_response_code(404);
    exit('Paket soal tidak ditemukan.');
}

$stmtKelas = $pdo->prepare(
    "SELECT nama_kelas FROM cbt_paket_kelas WHERE paket_id = :paket_id ORDER BY nama_kelas"
);
$stmtKelas->execute([':paket_id' => $paketId]);
$kelasUji = $stmtKelas->fetchAll(PDO::FETCH_COLUMN);

// KONFIGURASI PENYIMPANAN GAMBAR PASTE DAN UPLOAD MANUAL
// Folder fisik: [folder aplikasi]/uploads/soal/
// Path yang disimpan di database: uploads/soal/[nama-file-acak].[jpg|png|webp]
$folderUploadRelatif = 'uploads/soal';
$folderUpload = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'soal';

// Buat folder secara otomatis saat halaman dibuka, bukan menunggu upload pertama.
if (!is_dir($folderUpload)) {
    if (!mkdir($folderUpload, 0755, true) && !is_dir($folderUpload)) {
        throw new RuntimeException('Folder uploads/soal gagal dibuat. Periksa izin tulis (permission) folder aplikasi.');
    }
}
if (!is_writable($folderUpload)) {
    throw new RuntimeException('Folder uploads/soal tidak memiliki izin tulis. Atur permission folder agar PHP dapat menyimpan gambar.');
}

$pesan = '';
$jenisPesan = 'success';

// Endpoint unggah gambar dari clipboard (Ctrl+V) tanpa tombol upload manual.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'upload_paste') {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $token = (string)($_POST['csrf_token'] ?? '');
        if (!hash_equals($_SESSION['csrf_buat_soal'], $token)) {
            throw new RuntimeException('Sesi tidak valid. Muat ulang halaman.');
        }
        if (!isset($_FILES['gambar_clipboard'])) {
            throw new RuntimeException('Tidak ada gambar pada clipboard.');
        }
        $path = simpanGambar('gambar_clipboard', null, $folderUpload);
        echo json_encode(['success' => true, 'path' => $path], JSON_UNESCAPED_SLASHES);
    } catch (Throwable $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

// Simpan soal baru atau perubahan soal yang sudah ada.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $token = (string)($_POST['csrf_token'] ?? '');
        if (!hash_equals($_SESSION['csrf_buat_soal'], $token)) {
            throw new RuntimeException('Sesi formulir tidak valid. Muat ulang halaman.');
        }

        $soalIdPost = filter_var($_POST['soal_id'] ?? '', FILTER_VALIDATE_INT);
        $nomorSoal = filter_var($_POST['nomor_soal'] ?? '', FILTER_VALIDATE_INT);
        $materi = trim((string)($_POST['pokok_materi'] ?? ''));
        $level = (string)($_POST['level_soal'] ?? '');
        $teksSoal = bersihkanHtmlEditor((string)($_POST['soal'] ?? ''));

        $opsi = [];
        foreach (['a','b','c','d'] as $huruf) {
            $opsi[$huruf] = bersihkanHtmlEditor((string)($_POST['opsi_' . $huruf] ?? ''));
        }

        $kunci = strtoupper((string)($_POST['kunci_jawaban'] ?? ''));

        if (!$nomorSoal || $nomorSoal < 1) {
            throw new RuntimeException('Nomor soal tidak valid.');
        }
        if ($materi === '') {
            throw new RuntimeException('Pokok materi wajib diisi.');
        }
        if (!in_array($level, ['C1', 'C2'], true)) {
            throw new RuntimeException('Level soal harus C1 atau C2.');
        }
        if (trim(strip_tags($teksSoal)) === '' && !str_contains($teksSoal, '<img') && empty($_FILES['gambar_soal']['name'])) {
            throw new RuntimeException('Pertanyaan harus diisi teks atau gambar.');
        }
        foreach (['a','b','c','d'] as $huruf) {
            if (trim(strip_tags($opsi[$huruf])) === '' && !str_contains($opsi[$huruf], '<img') && empty($_FILES['gambar_opsi_' . $huruf]['name'])) {
                throw new RuntimeException('Pilihan ' . strtoupper($huruf) . ' harus diisi teks atau gambar.');
            }
        }
        if (!in_array($kunci, ['A','B','C','D'], true)) {
            throw new RuntimeException('Pilih kunci jawaban A, B, C, atau D.');
        }

        $dataLama = null;
        if ($soalIdPost) {
            $stmtLama = $pdo->prepare(
                "SELECT * FROM cbt_soal_pilihan_ganda WHERE id = :id AND paket_id = :paket_id LIMIT 1"
            );
            $stmtLama->execute([':id' => $soalIdPost, ':paket_id' => $paketId]);
            $dataLama = $stmtLama->fetch(PDO::FETCH_ASSOC);
            if (!$dataLama) {
                throw new RuntimeException('Soal yang akan diedit tidak ditemukan pada paket ini.');
            }
        }

        // Cegah nomor soal ganda pada paket yang sama.
        $stmtCek = $pdo->prepare(
            "SELECT id FROM cbt_soal_pilihan_ganda
             WHERE paket_id = :paket_id AND nomor_soal = :nomor
             AND (:soal_id_null IS NULL OR id <> :soal_id_compare)
             LIMIT 1"
        );
        $stmtCek->execute([
            ':paket_id' => $paketId,
            ':nomor' => $nomorSoal,
            ':soal_id_null' => $soalIdPost ?: null,
            ':soal_id_compare' => $soalIdPost ?: null,
        ]);
        if ($stmtCek->fetchColumn()) {
            throw new RuntimeException('Nomor soal tersebut sudah digunakan dalam paket ini.');
        }

        $gambarSoal = simpanGambar(
            'gambar_soal',
            $dataLama['gambar_soal'] ?? null,
            $folderUpload
        );

        $gambarOpsi = [];
        foreach (['a','b','c','d'] as $huruf) {
            $kolom = 'gambar_opsi_' . $huruf;
            $gambarOpsi[$huruf] = simpanGambar(
                $kolom,
                $dataLama[$kolom] ?? null,
                $folderUpload
            );
        }

        // Gambar hasil paste sudah tersimpan sebagai file fisik di uploads/soal/.
        // Alamat relatifnya berada di dalam HTML kolom soal/opsi (LONGTEXT).
        // Kolom gambar_soal/gambar_opsi_* tetap untuk mekanisme upload manual lama.
        $parameter = [
            ':paket_id' => $paketId,
            ':nomor_soal' => $nomorSoal,
            ':pokok_materi' => $materi,
            ':level_soal' => $level,
            ':soal' => $teksSoal,
            ':gambar_soal' => $gambarSoal,
            ':opsi_a' => $opsi['a'],
            ':gambar_opsi_a' => $gambarOpsi['a'],
            ':opsi_b' => $opsi['b'],
            ':gambar_opsi_b' => $gambarOpsi['b'],
            ':opsi_c' => $opsi['c'],
            ':gambar_opsi_c' => $gambarOpsi['c'],
            ':opsi_d' => $opsi['d'],
            ':gambar_opsi_d' => $gambarOpsi['d'],
            ':kunci_jawaban' => $kunci,
        ];

        if ($soalIdPost) {
            $parameter[':id'] = $soalIdPost;
            $sql = "UPDATE cbt_soal_pilihan_ganda SET
                        nomor_soal = :nomor_soal,
                        pokok_materi = :pokok_materi,
                        level_soal = :level_soal,
                        soal = :soal,
                        gambar_soal = :gambar_soal,
                        opsi_a = :opsi_a,
                        gambar_opsi_a = :gambar_opsi_a,
                        opsi_b = :opsi_b,
                        gambar_opsi_b = :gambar_opsi_b,
                        opsi_c = :opsi_c,
                        gambar_opsi_c = :gambar_opsi_c,
                        opsi_d = :opsi_d,
                        gambar_opsi_d = :gambar_opsi_d,
                        kunci_jawaban = :kunci_jawaban
                    WHERE id = :id AND paket_id = :paket_id";
            $stmtSave = $pdo->prepare($sql);
            $stmtSave->execute($parameter);
            $idTersimpan = $soalIdPost;
        } else {
            $sql = "INSERT INTO cbt_soal_pilihan_ganda (
                        paket_id, nomor_soal, pokok_materi, level_soal,
                        soal, gambar_soal,
                        opsi_a, gambar_opsi_a,
                        opsi_b, gambar_opsi_b,
                        opsi_c, gambar_opsi_c,
                        opsi_d, gambar_opsi_d,
                        kunci_jawaban
                    ) VALUES (
                        :paket_id, :nomor_soal, :pokok_materi, :level_soal,
                        :soal, :gambar_soal,
                        :opsi_a, :gambar_opsi_a,
                        :opsi_b, :gambar_opsi_b,
                        :opsi_c, :gambar_opsi_c,
                        :opsi_d, :gambar_opsi_d,
                        :kunci_jawaban
                    )";
            $stmtSave = $pdo->prepare($sql);
            $stmtSave->execute($parameter);
            $idTersimpan = (int)$pdo->lastInsertId();
        }

        redirectSoal((int)$paketId, $idTersimpan);
    } catch (Throwable $e) {
        $pesan = $e instanceof PDOException
            ? 'Gagal menyimpan soal. Periksa struktur tabel dan koneksi database.'
            : $e->getMessage();
        $jenisPesan = 'danger';
    }
}

// Ambil seluruh soal dalam paket untuk navigasi dan daftar ringkas.
$stmtDaftar = $pdo->prepare(
    "SELECT id, nomor_soal, pokok_materi, level_soal
     FROM cbt_soal_pilihan_ganda
     WHERE paket_id = :paket_id
     ORDER BY nomor_soal ASC"
);
$stmtDaftar->execute([':paket_id' => $paketId]);
$daftarSoal = $stmtDaftar->fetchAll(PDO::FETCH_ASSOC);

$soalId = filter_input(INPUT_GET, 'soal_id', FILTER_VALIDATE_INT);
$modeBaru = (($_GET['mode'] ?? '') === 'baru');
$record = null;

if ($soalId) {
    $stmtRecord = $pdo->prepare(
        "SELECT * FROM cbt_soal_pilihan_ganda WHERE id = :id AND paket_id = :paket_id LIMIT 1"
    );
    $stmtRecord->execute([':id' => $soalId, ':paket_id' => $paketId]);
    $record = $stmtRecord->fetch(PDO::FETCH_ASSOC) ?: null;
}

// Mode baru harus tetap menampilkan formulir kosong, bukan kembali ke soal pertama.
if (!$record && !$modeBaru && !$soalId && count($daftarSoal) > 0) {
    $stmtRecord = $pdo->prepare(
        "SELECT * FROM cbt_soal_pilihan_ganda
         WHERE id = :id AND paket_id = :paket_id LIMIT 1"
    );
    $stmtRecord->execute([
        ':id' => (int)$daftarSoal[0]['id'],
        ':paket_id' => $paketId
    ]);
    $record = $stmtRecord->fetch(PDO::FETCH_ASSOC) ?: null;
}

$nomorMaksimum = $daftarSoal
    ? (int)max(array_column($daftarSoal, 'nomor_soal'))
    : 0;

$nilai = [
    'id' => $record['id'] ?? '',
    'nomor_soal' => $record['nomor_soal'] ?? ($nomorMaksimum + 1),
    'pokok_materi' => $record['pokok_materi'] ?? '',
    'level_soal' => $record['level_soal'] ?? 'C1',
    'soal' => $record['soal'] ?? '',
    'gambar_soal' => $record['gambar_soal'] ?? '',
    'opsi_a' => $record['opsi_a'] ?? '',
    'gambar_opsi_a' => $record['gambar_opsi_a'] ?? '',
    'opsi_b' => $record['opsi_b'] ?? '',
    'gambar_opsi_b' => $record['gambar_opsi_b'] ?? '',
    'opsi_c' => $record['opsi_c'] ?? '',
    'gambar_opsi_c' => $record['gambar_opsi_c'] ?? '',
    'opsi_d' => $record['opsi_d'] ?? '',
    'gambar_opsi_d' => $record['gambar_opsi_d'] ?? '',
    'kunci_jawaban' => $record['kunci_jawaban'] ?? '',
];

// Navigasi berdasarkan nomor_soal, bukan posisi ID atau urutan input.
$nomorAktif = (int)$nilai['nomor_soal'];
$stmtSebelumnya = $pdo->prepare(
    "SELECT id FROM cbt_soal_pilihan_ganda
     WHERE paket_id = :paket_id AND nomor_soal < :nomor_aktif
     ORDER BY nomor_soal DESC LIMIT 1"
);
$stmtSebelumnya->execute([':paket_id' => $paketId, ':nomor_aktif' => $nomorAktif]);
$idSebelumnya = $stmtSebelumnya->fetchColumn();
$idSebelumnya = $idSebelumnya ? (int)$idSebelumnya : null;

$stmtSelanjutnya = $pdo->prepare(
    "SELECT id FROM cbt_soal_pilihan_ganda
     WHERE paket_id = :paket_id AND nomor_soal > :nomor_aktif
     ORDER BY nomor_soal ASC LIMIT 1"
);
$stmtSelanjutnya->execute([':paket_id' => $paketId, ':nomor_aktif' => $nomorAktif]);
$idSelanjutnya = $stmtSelanjutnya->fetchColumn();
$idSelanjutnya = $idSelanjutnya ? (int)$idSelanjutnya : null;

$sudahTersimpan = !empty($nilai['id']);

$jumlahSoal = count($daftarSoal);
$nomorTampilan = (int)$nilai['nomor_soal'];
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pembuatan Soal Pilihan Ganda</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root { --hijau:#006c45; --hijau-tua:#004d36; --emas:#c9a227; }
        body { background:#f4f7f5; color:#24332c; }
        .navbar { background:var(--hijau-tua); }
        .card { border:0; border-radius:14px; box-shadow:0 4px 18px rgba(0,0,0,.055); }
        .btn-primary { background:var(--hijau); border-color:var(--hijau); }
        .btn-primary:hover { background:var(--hijau-tua); border-color:var(--hijau-tua); }
        .section-title { color:var(--hijau-tua); font-weight:700; }
        .form-label { font-weight:600; }
        .option-letter { width:38px; height:38px; display:grid; place-items:center; flex:0 0 38px;
            border-radius:9px; background:#eaf3ed; color:var(--hijau-tua); font-weight:700; }
        .image-preview { max-width:220px; max-height:150px; display:block; object-fit:contain;
            border:1px solid #dce5df; border-radius:9px; padding:5px; background:#fff; margin-top:8px; }
        .question-number { color:var(--hijau); font-size:1.2rem; font-weight:800; }
        .sticky-actions { position:sticky; bottom:0; background:rgba(244,247,245,.96);
            padding:12px 0; z-index:5; backdrop-filter:blur(8px); }
        .rich-editor { min-height:130px; border:1px solid #ced4da; border-radius:.375rem;
            padding:.75rem; background:#fff; overflow-wrap:anywhere; }
        .rich-editor:focus { outline:0; border-color:#86b7fe; box-shadow:0 0 0 .25rem rgba(13,110,253,.15); }
        .rich-editor:empty:before { content:attr(data-placeholder); color:#6c757d; pointer-events:none; }
        .rich-editor img { max-width:100%; height:auto; max-height:360px; object-fit:contain; display:block; margin:8px 0; }
        .paste-help { font-size:.8rem; color:#64736b; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark mb-4">
    <div class="container d-flex justify-content-between">
        <span class="navbar-brand fw-semibold">CBT  Pembuatan Soal</span>
        <a href="identitas_soal.php" class="btn btn-outline-light btn-sm">Kembali ke Identitas</a>
    </div>
</nav>

<main class="container pb-4">
    <div class="mb-3">
        <h3 class="section-title mb-1">Pembuatan Soal Pilihan Ganda</h3>
        <div class="text-secondary">
            <?= h($paket['mata_pelajaran']) ?>  Kelas <?= h($paket['tingkat_kelas']) ?>
             Kelas ujian: <?= h(implode(', ', $kelasUji)) ?>
        </div>
    </div>

    <?php if ($pesan !== ''): ?>
        <div class="alert alert-<?= h($jenisPesan) ?> alert-dismissible fade show" role="alert">
            <?= h($pesan) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Tutup"></button>
        </div>
    <?php endif; ?>

    <div class="row g-3">
        <div class="col-lg-8">
            <section class="card">
                <div class="card-body p-3 p-md-4">
                    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
                        <div>
                            <h5 class="section-title mb-1">Form Soal</h5>
                            <span class="text-secondary small">Lengkapi pertanyaan, pilihan jawaban, dan kunci.</span>
                        </div>
                        <div class="text-end">
                            <div class="small text-secondary">Nomor soal</div>
                            <div class="question-number">#<?= $nomorTampilan ?></div>
                        </div>
                    </div>

                    <form method="post" enctype="multipart/form-data" id="formSoal">
                        <input type="hidden" name="csrf_token" value="<?= h($_SESSION['csrf_buat_soal']) ?>">
                        <input type="hidden" name="soal_id" value="<?= h($nilai['id']) ?>">
                        <input type="hidden" name="nomor_soal" value="<?= h($nilai['nomor_soal']) ?>">

                        <div class="row g-3 mb-3">
                            <div class="col-md-8">
                                <label for="pokok_materi" class="form-label">Pokok Materi</label>
                                <input type="text" class="form-control" id="pokok_materi" name="pokok_materi"
                                       maxlength="255" value="<?= h($nilai['pokok_materi']) ?>"
                                       placeholder="Contoh: Struktur Data Tree" required>
                            </div>
                            <div class="col-md-4">
                                <label for="level_soal" class="form-label">Level Soal</label>
                                <select class="form-select" id="level_soal" name="level_soal" required>
                                    <option value="C1" <?= $nilai['level_soal'] === 'C1' ? 'selected' : '' ?>>C1 - Mengingat</option>
                                    <option value="C2" <?= $nilai['level_soal'] === 'C2' ? 'selected' : '' ?>>C2 - Memahami</option>
                                </select>
                            </div>
                        </div>

                        <hr>
                        <div class="mb-4">
                            <label for="soal" class="form-label">Pertanyaan / Soal</label>
                            <div class="rich-editor editor-soal" id="editor_soal" contenteditable="true"
                                 data-placeholder="Tuliskan soal atau tekan Ctrl+V untuk menempelkan teks/gambar..."><?= bersihkanHtmlEditor((string)$nilai['soal']) ?></div>
                            <textarea class="d-none" id="soal" name="soal"></textarea>
                            <div class="paste-help mt-1">Tips: tempel teks atau gambar langsung dengan Ctrl+V. Gambar clipboard otomatis disimpan ke folder uploads/soal/ dan alamatnya ikut disimpan di database.</div>
                            <label for="gambar_soal" class="form-label mt-3">Gambar Soal (opsional)</label>
                            <input class="form-control image-input" type="file" id="gambar_soal"
                                   name="gambar_soal" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp">
                            <div class="form-text">Format JPG, PNG, WEBP. Maksimal 4 MB.</div>
                            <?php if ($nilai['gambar_soal']): ?>
                                <div class="small text-secondary mt-2">Gambar tersimpan:</div>
                                <img class="image-preview" src="<?= h($nilai['gambar_soal']) ?>" alt="Gambar soal">
                            <?php endif; ?>
                            <div class="preview-container"></div>
                        </div>

                        <hr>
                        <h6 class="section-title mb-3">Opsi Jawaban</h6>

                        <?php foreach (['a'=>'A','b'=>'B','c'=>'C','d'=>'D'] as $huruf => $label): ?>
                            <div class="mb-4">
                                <div class="d-flex gap-2 align-items-start">
                                    <div class="option-letter"><?= $label ?></div>
                                    <div class="flex-grow-1">
                                        <label for="opsi_<?= $huruf ?>" class="form-label">Pilihan <?= $label ?></label>
                                        <div class="rich-editor editor-opsi" id="editor_opsi_<?= $huruf ?>" contenteditable="true"
                                             data-placeholder="Tuliskan pilihan <?= $label ?> atau Ctrl+V teks/gambar..."><?= bersihkanHtmlEditor((string)$nilai['opsi_' . $huruf]) ?></div>
                                        <textarea class="d-none" id="opsi_<?= $huruf ?>" name="opsi_<?= $huruf ?>"></textarea>
                                        <div class="paste-help mt-1">Ctrl+V untuk menempelkan teks/gambar.</div>
                                        <label for="gambar_opsi_<?= $huruf ?>" class="form-label mt-2">
                                            Gambar pilihan <?= $label ?> (opsional)
                                        </label>
                                        <input class="form-control image-input" type="file"
                                               id="gambar_opsi_<?= $huruf ?>" name="gambar_opsi_<?= $huruf ?>"
                                               accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp">
                                        <?php if ($nilai['gambar_opsi_' . $huruf]): ?>
                                            <div class="small text-secondary mt-2">Gambar tersimpan:</div>
                                            <img class="image-preview" src="<?= h($nilai['gambar_opsi_' . $huruf]) ?>"
                                                 alt="Gambar pilihan <?= $label ?>">
                                        <?php endif; ?>
                                        <div class="preview-container"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>

                        <hr>
                        <div class="mb-2">
                            <label class="form-label d-block">Kunci Jawaban</label>
                            <div class="d-flex flex-wrap gap-4">
                                <?php foreach (['A','B','C','D'] as $huruf): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="kunci_jawaban"
                                               id="kunci<?= $huruf ?>" value="<?= $huruf ?>"
                                               <?= $nilai['kunci_jawaban'] === $huruf ? 'checked' : '' ?> required>
                                        <label class="form-check-label fw-semibold" for="kunci<?= $huruf ?>">
                                            <?= $huruf ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="sticky-actions mt-4">
                            <div class="row g-2 align-items-center">
                                <div class="col-4 text-start">
                                    <?php if ($idSebelumnya): ?>
                                        <a class="btn btn-success w-100"
                                           href="buat_soal.php?paket_id=<?= (int)$paketId ?>&soal_id=<?= $idSebelumnya ?>">
                                            &larr; Sebelumnya
                                        </a>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-outline-secondary w-100" disabled>
                                            &larr; Sebelumnya
                                        </button>
                                    <?php endif; ?>
                                </div>

                                <div class="col-4 text-center">
                                    <button type="submit" class="btn <?= $sudahTersimpan ? 'btn-warning' : 'btn-success' ?> w-100 px-2">
                                        <?= $sudahTersimpan ? 'Update' : 'Simpan' ?>
                                    </button>
                                </div>

                                <div class="col-4 text-end">
                                    <?php if ($idSelanjutnya): ?>
                                        <a class="btn btn-warning w-100"
                                           href="buat_soal.php?paket_id=<?= (int)$paketId ?>&soal_id=<?= $idSelanjutnya ?>">
                                            Selanjutnya &rarr;
                                        </a>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-success w-100" id="btnSoalBaru">
                                            Buat Soal Berikutnya &rarr;
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="form-text text-center mt-2">
                                Simpan perubahan sebelum berpindah ke soal lain.
                            </div>
                        </div>
                    </form>
                </div>
            </section>
        </div>

        <div class="col-lg-4">
            <section class="card">
                <div class="card-body p-3">
                    <h6 class="section-title">Daftar Nomor Soal</h6>
                    <div class="text-secondary small mb-3"><?= $jumlahSoal ?> soal tersimpan</div>
                    <?php if (!$daftarSoal): ?>
                        <div class="text-secondary small">Belum ada soal yang disimpan.</div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($daftarSoal as $item): ?>
                                <a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center
                                    <?= (int)$item['id'] === (int)($nilai['id'] ?: 0) ? 'active' : '' ?>"
                                   href="buat_soal.php?paket_id=<?= (int)$paketId ?>&soal_id=<?= (int)$item['id'] ?>">
                                    <span>
                                        <strong>No. <?= (int)$item['nomor_soal'] ?></strong>
                                        <small class="d-block"><?= h($item['pokok_materi']) ?></small>
                                    </span>
                                    <span class="badge <?= (int)$item['id'] === (int)($nilai['id'] ?: 0) ? 'text-bg-light' : 'text-bg-success' ?>">
                                        <?= h($item['level_soal']) ?>
                                    </span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <hr>
                    <div class="small text-secondary">
                        Nomor soal baru dibuat otomatis berdasarkan nomor terbesar yang sudah tersimpan.
                    </div>
                </div>
            </section>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Sinkronkan editor visual ke textarea tersembunyi sebelum formulir dikirim.
const formSoal = document.getElementById('formSoal');
const csrfToken = document.querySelector('[name="csrf_token"]').value;
const pasanganEditor = [
    ['editor_soal', 'soal'],
    ['editor_opsi_a', 'opsi_a'],
    ['editor_opsi_b', 'opsi_b'],
    ['editor_opsi_c', 'opsi_c'],
    ['editor_opsi_d', 'opsi_d']
];
function sinkronEditor() {
    pasanganEditor.forEach(([editorId, fieldName]) => {
        document.getElementById(fieldName).value = document.getElementById(editorId).innerHTML.trim();
    });
}
formSoal.addEventListener('submit', sinkronEditor);

// Tangani clipboard dari Word/browser: teks HTML dipertahankan dan gambar diunggah ke server.
async function unggahBlobClipboard(blob, index) {
    const formData = new FormData();
    formData.append('aksi', 'upload_paste');
    formData.append('csrf_token', csrfToken);
    const mime = blob.type || 'image/png';
    const ext = mime.includes('jpeg') ? 'jpg' : (mime.includes('webp') ? 'webp' : 'png');
    formData.append('gambar_clipboard', blob, `clipboard-${index}.${ext}`);
    const response = await fetch(window.location.href, { method: 'POST', body: formData });
    const result = await response.json();
    if (!response.ok || !result.success) {
        throw new Error(result.message || 'Gagal mengunggah gambar dari clipboard.');
    }
    return result.path;
}

document.querySelectorAll('.rich-editor').forEach(editor => {
    editor.addEventListener('paste', async event => {
        const clipboard = event.clipboardData;
        if (!clipboard) return;

        const htmlAsli = clipboard.getData('text/html');
        const teksBiasa = clipboard.getData('text/plain');
        const imageBlobs = Array.from(clipboard.items || [])
            .filter(item => item.type && item.type.startsWith('image/'))
            .map(item => item.getAsFile())
            .filter(Boolean);

        // Tidak ada HTML bergambar maupun file gambar: biarkan browser menempelkan teks biasa.
        const adaImgHtml = htmlAsli && /<img\b/i.test(htmlAsli);
        if (!adaImgHtml && imageBlobs.length === 0) return;

        event.preventDefault();

        const selection = window.getSelection();
        let range = null;
        if (selection && selection.rangeCount && editor.contains(selection.anchorNode)) {
            range = selection.getRangeAt(0).cloneRange();
        } else {
            range = document.createRange();
            range.selectNodeContents(editor);
            range.collapse(false);
        }

        try {
            let fragmen;
            if (htmlAsli) {
                const doc = new DOMParser().parseFromString(htmlAsli, 'text/html');
                const gambarHtml = Array.from(doc.querySelectorAll('img'));
                let indexBlob = 0;

                for (const img of gambarHtml) {
                    let blob = null;
                    const src = img.getAttribute('src') || '';

                    // Word/Office dan beberapa browser menaruh gambar sebagai data URI.
                    if (/^data:image\//i.test(src)) {
                        const hasil = await fetch(src);
                        blob = await hasil.blob();
                    } else if (/^blob:/i.test(src)) {
                        try {
                            const hasil = await fetch(src);
                            blob = await hasil.blob();
                        } catch (_) {}
                    }

                    // Jika HTML hanya membawa referensi file lokal/URL sementara,
                    // ambil berkas gambar yang ikut disediakan clipboard browser.
                    if ((!blob || !blob.type.startsWith('image/')) && imageBlobs[indexBlob]) {
                        blob = imageBlobs[indexBlob++];
                    }

                    if (blob && blob.size > 0) {
                        if (blob.size > 4 * 1024 * 1024) {
                            throw new Error('Ukuran setiap gambar maksimal 4 MB.');
                        }
                        img.setAttribute('src', await unggahBlobClipboard(blob, indexBlob));
                        img.removeAttribute('width');
                        img.removeAttribute('height');
                        img.removeAttribute('style');
                        img.removeAttribute('class');
                    } else {
                        // Jangan tampilkan gambar rusak/tautan file lokal dari komputer pengguna.
                        img.remove();
                    }
                }

                // Ambil isi body HTML dari clipboard, bukan wrapper dokumen Word.
                fragmen = document.createDocumentFragment();
                while (doc.body.firstChild) fragmen.appendChild(doc.body.firstChild);
            } else {
                // Clipboard berisi gambar bitmap tanpa representasi HTML.
                fragmen = document.createDocumentFragment();
                for (let i = 0; i < imageBlobs.length; i++) {
                    const blob = imageBlobs[i];
                    if (blob.size > 4 * 1024 * 1024) {
                        throw new Error('Ukuran setiap gambar maksimal 4 MB.');
                    }
                    const img = document.createElement('img');
                    img.src = await unggahBlobClipboard(blob, i);
                    img.alt = 'Gambar soal';
                    fragmen.appendChild(img);
                }
            }

            editor.focus();
            range.deleteContents();
            range.insertNode(fragmen);
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
        } catch (error) {
            alert(error.message || 'Gagal memproses isi clipboard.');
            // Bila gambar gagal diproses, teks biasa tetap dapat ditempel sebagai alternatif.
            if (teksBiasa) {
                editor.focus();
                document.execCommand('insertText', false, teksBiasa);
            }
        }
    });
});

// Pratinjau gambar sebelum diunggah.
document.querySelectorAll('.image-input').forEach(input => {
    input.addEventListener('change', function () {
        const container = this.parentElement.querySelector('.preview-container');
        container.innerHTML = '';
        const file = this.files && this.files[0];
        if (!file) return;

        if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
            alert('Format gambar harus JPG, PNG, atau WEBP.');
            this.value = '';
            return;
        }
        if (file.size > 4 * 1024 * 1024) {
            alert('Ukuran gambar maksimal 4 MB.');
            this.value = '';
            return;
        }

        const img = document.createElement('img');
        img.className = 'image-preview';
        img.alt = 'Pratinjau gambar baru';
        img.src = URL.createObjectURL(file);
        container.appendChild(img);
    });
});

// Tombol soal berikutnya: simpan terlebih dahulu agar perubahan tidak hilang.
const tombolBaru = document.getElementById('btnSoalBaru');
if (tombolBaru) {
    tombolBaru.addEventListener('click', function () {
        const form = document.getElementById('formSoal');
        if (form.querySelector('[name="soal_id"]').value === '') {
            alert('Isi dan simpan soal ini terlebih dahulu.');
            return;
        }
        const url = new URL(window.location.href);
        url.searchParams.delete('soal_id');
        url.searchParams.set('mode', 'baru');
        window.location.href = url.toString();
    });
}
</script>
</body>
</html>
