<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Cek apakah user sudah login dan memiliki akses admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin_soal') {
    header('Location: ../login.php');
    exit;
}

$error = '';
$success = '';

// Daftar 10 department kedokteran gigi
$departments = [
    'Odontologi Forensik',
    'Konservasi Gigi',
    'Bedah Mulut',
    'Periodonsia', 
    'Orthodonti',
    'Prostodonsia',
    'Ilmu Kesehatan Gigi Masyarakat',
    'Ilmu Kedokteran Gigi Anak',
    'Radiologi Kedokteran Gigi',
    'Penyakit Mulut'
];

// Data blok berdasarkan semester
$blok_options = [
    'Gasal' => [
        'Blok 1', 'Blok 2', 'Blok 3', 'Blok 7', 'Blok 8', 'Blok 9', 
        'Blok 13', 'Blok 14', 'Blok 15', 'Blok 16', 'Blok 17', 
        'Blok 21', 'Blok 22', 'Blok 23'
    ],
    'Genap' => [
        'Blok 4', 'Blok 5', 'Blok 6', 'Blok 10', 'Blok 11', 'Blok 12',
        'Blok 18', 'Blok 19', 'Blok 20'
    ]
];

// Data CPMK berdasarkan blok
$cpmk_options = [
    'Blok 1' => ['CPMK Blok 1.1', 'CPMK Blok 1.2', 'CPMK Blok 1.3'],
    'Blok 2' => ['CPMK Blok 2.1', 'CPMK Blok 2.2', 'CPMK Blok 2.3'],
    'Blok 3' => ['CPMK Blok 3.1', 'CPMK Blok 3.2', 'CPMK Blok 3.3'],
    'Blok 4' => ['CPMK Blok 4.1', 'CPMK Blok 4.2', 'CPMK Blok 4.3'],
    'Blok 5' => ['CPMK Blok 5.1', 'CPMK Blok 5.2', 'CPMK Blok 5.3'],
    'Blok 6' => ['CPMK Blok 6.1', 'CPMK Blok 6.2', 'CPMK Blok 6.3'],
    'Blok 7' => ['CPMK Blok 7.1', 'CPMK Blok 7.2', 'CPMK Blok 7.3'],
    'Blok 8' => ['CPMK Blok 8.1', 'CPMK Blok 8.2', 'CPMK Blok 8.3'],
    'Blok 9' => ['CPMK Blok 9.1', 'CPMK Blok 9.2', 'CPMK Blok 9.3'],
    'Blok 10' => ['CPMK Blok 10.1', 'CPMK Blok 10.2', 'CPMK Blok 10.3'],
    'Blok 11' => ['CPMK Blok 11.1', 'CPMK Blok 11.2', 'CPMK Blok 11.3'],
    'Blok 12' => ['CPMK Blok 12.1', 'CPMK Blok 12.2', 'CPMK Blok 12.3'],
    'Blok 13' => ['CPMK Blok 13.1', 'CPMK Blok 13.2', 'CPMK Blok 13.3'],
    'Blok 14' => ['CPMK Blok 14.1', 'CPMK Blok 14.2', 'CPMK Blok 14.3'],
    'Blok 15' => ['CPMK Blok 15.1', 'CPMK Blok 15.2', 'CPMK Blok 15.3'],
    'Blok 16' => ['CPMK Blok 16.1', 'CPMK Blok 16.2', 'CPMK Blok 16.3'],
    'Blok 17' => ['CPMK Blok 17.1', 'CPMK Blok 17.2', 'CPMK Blok 17.3'],
    'Blok 18' => ['CPMK Blok 18.1', 'CPMK Blok 18.2', 'CPMK Blok 18.3'],
    'Blok 19' => ['CPMK Blok 19.1', 'CPMK Blok 19.2', 'CPMK Blok 19.3'],
    'Blok 20' => ['CPMK Blok 20.1', 'CPMK Blok 20.2', 'CPMK Blok 20.3'],
    'Blok 21' => ['CPMK Blok 21.1', 'CPMK Blok 21.2', 'CPMK Blok 21.3'],
    'Blok 22' => ['CPMK Blok 22.1', 'CPMK Blok 22.2', 'CPMK Blok 22.3'],
    'Blok 23' => ['CPMK Blok 23.1', 'CPMK Blok 23.2', 'CPMK Blok 23.3']
];

// Inisialisasi variabel untuk form fields
$nomor_registrasi = $tinjauan1 = $tinjauan2 = $tinjauan3 = $vignette = $pertanyaan = '';
$pilihan_a = $pilihan_b = $pilihan_c = $pilihan_d = $pilihan_e = $kunci = '';
$department = $alasan_singkat = $referensi = $penulis = '';
$semester = $blok = $cpmk = '';

// Fungsi untuk generate nomor registrasi otomatis
function generateNomorRegistrasi($pdo) {
    try {
        // Cek apakah tabel ada
        $stmt = $pdo->query("SHOW TABLES LIKE 'bank_soal_teori_s1'");
        $tableExists = $stmt->fetch();
        
        if (!$tableExists) {
            $new_number = '01';
        } else {
            // Ambil nomor urut terakhir
            $stmt = $pdo->query("SELECT nomor_registrasi FROM bank_soal_teori_s1 ORDER BY id DESC LIMIT 1");
            $last_soal = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($last_soal && !empty($last_soal['nomor_registrasi'])) {
                $parts = explode('/', $last_soal['nomor_registrasi']);
                
                if (count($parts) === 4) {
                    $last_number = intval($parts[0]);
                    $new_number = str_pad($last_number + 1, 2, '0', STR_PAD_LEFT);
                } else {
                    $stmt = $pdo->query("SELECT MAX(CAST(SUBSTRING_INDEX(nomor_registrasi, '/', 1) AS UNSIGNED)) as max_number FROM bank_soal_teori_s1");
                    $max_result = $stmt->fetch(PDO::FETCH_ASSOC);
                    $max_number = $max_result['max_number'] ?: 0;
                    $new_number = str_pad($max_number + 1, 2, '0', STR_PAD_LEFT);
                }
            } else {
                $new_number = '01';
            }
        }
    } catch (PDOException $e) {
        error_log("Error in generateNomorRegistrasi: " . $e->getMessage());
        $new_number = '01';
    }
    
    $current_year = date('Y');
    $current_month = date('m');
    
    return $new_number . '/FKG-UMS/' . $current_month . '/' . $current_year;
}

// Generate nomor registrasi otomatis
$auto_nomor_registrasi = generateNomorRegistrasi($pdo);

// Buat folder uploads jika belum ada
$upload_dir = '../uploads/soal_teori_s1/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Proses form jika ada data yang dikirim
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $nomor_registrasi = $_POST['nomor_registrasi'] ?? $auto_nomor_registrasi;
    $tinjauan1 = $_POST['tinjauan1'] ?? '';
    $tinjauan2 = $_POST['tinjauan2'] ?? '';
    $tinjauan3 = $_POST['tinjauan3'] ?? '';
    $semester = $_POST['semester'] ?? '';
    $blok = $_POST['blok'] ?? '';
    $cpmk = $_POST['cpmk'] ?? '';
    $vignette = $_POST['vignette'] ?? '';
    $pertanyaan = $_POST['pertanyaan'] ?? '';
    $pilihan_a = $_POST['pilihan_a'] ?? '';
    $pilihan_b = $_POST['pilihan_b'] ?? '';
    $pilihan_c = $_POST['pilihan_c'] ?? '';
    $pilihan_d = $_POST['pilihan_d'] ?? '';
    $pilihan_e = $_POST['pilihan_e'] ?? '';
    $kunci = $_POST['kunci'] ?? '';
    $department = $_POST['department'] ?? '';
    $alasan_singkat = $_POST['alasan_singkat'] ?? '';
    $referensi = $_POST['referensi'] ?? '';
    $penulis = $_POST['penulis'] ?? '';
    
    // Validasi data
    if (empty($tinjauan1) || empty($pertanyaan) || empty($semester) || empty($blok) || empty($cpmk)) {
        $error = 'Kompetensi Utama, Pertanyaan, Semester, Blok, dan CPMK harus diisi!';
    } else {
        // Proses upload gambar dari base64
        $vignette = processImagesFromHTML($vignette, $upload_dir);
        $pertanyaan = processImagesFromHTML($pertanyaan, $upload_dir);
        $alasan_singkat = processImagesFromHTML($alasan_singkat, $upload_dir);
        $referensi = processImagesFromHTML($referensi, $upload_dir);
        
        // Simpan ke database
        try {
            $stmt = $pdo->prepare("INSERT INTO bank_soal_teori_s1 (
                nomor_registrasi, tinjauan1, tinjauan2, tinjauan3, semester, blok, cpmk,
                vignette, pertanyaan, pilihan_a, pilihan_b, pilihan_c, pilihan_d, pilihan_e, 
                kunci, department, alasan_singkat, referensi, penulis
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $nomor_registrasi, $tinjauan1, $tinjauan2, $tinjauan3, $semester, $blok, $cpmk,
                $vignette, $pertanyaan, $pilihan_a, $pilihan_b, $pilihan_c, $pilihan_d, $pilihan_e, 
                $kunci, $department, $alasan_singkat, $referensi, $penulis
            ]);
            
            $success = 'Soal teori S1 berhasil disimpan!';
            
            // Generate nomor registrasi baru untuk form selanjutnya
            $auto_nomor_registrasi = generateNomorRegistrasi($pdo);
            
            // Reset form jika berhasil
            $_POST = array();
            $tinjauan1 = $tinjauan2 = $tinjauan3 = $semester = $blok = $cpmk = $vignette = $pertanyaan = '';
            $pilihan_a = $pilihan_b = $pilihan_c = $pilihan_d = $pilihan_e = $kunci = '';
            $department = $alasan_singkat = $referensi = $penulis = '';
            
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan: ' . $e->getMessage();
            error_log("Database error: " . $e->getMessage());
        }
    }
}

// Fungsi untuk memproses base64 images dan menyimpannya sebagai file
function processImagesFromHTML($content, $upload_dir) {
    if (empty($content)) {
        return $content;
    }
    
    preg_match_all('/<img[^>]+src="data:image\/([^;]+);base64,([^"]+)"[^>]*>/i', $content, $matches);
    
    if (empty($matches[0])) {
        return $content;
    }
    
    foreach ($matches[0] as $index => $imgTag) {
        $imageType = $matches[1][$index];
        $base64Data = $matches[2][$index];
        
        $filename = uniqid() . '_' . time() . '.' . $imageType;
        $filepath = $upload_dir . $filename;
        
        $imageData = base64_decode($base64Data);
        if (file_put_contents($filepath, $imageData)) {
            $newImgTag = '<img src="../uploads/soal_teori_s1/' . $filename . '" alt="Gambar" style="max-width: 100%; height: auto; border-radius: 8px;">';
            $content = str_replace($imgTag, $newImgTag, $content);
        }
    }
    
    return $content;
}

// Ambil data soal untuk ditampilkan
$soal_teori = [];
try {
    $stmt = $pdo->query("SELECT * FROM bank_soal_teori_s1 ORDER BY created_at DESC");
    $soal_teori = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = 'Gagal mengambil data soal: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bank Soal Teori S1 - SOCA OSCE System</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ===== RESET & BASE ===== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #d4d8dc;
            display: flex;
            min-height: 100vh;
        }

        /* ===== SIDEBAR ===== */
        .sidebar {
            width: 260px;
            background: linear-gradient(180deg, #1a2332 0%, #0f1724 100%);
            color: #ffffff;
            padding: 0;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 100;
            transition: all 0.3s ease;
            box-shadow: 4px 0 20px rgba(0,0,0,0.1);
        }

        .sidebar::-webkit-scrollbar {
            width: 4px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
        }

        .sidebar-header {
            padding: 25px 20px 20px;
            border-bottom: 1px solid rgba(255,255,255,0.08);
            text-align: center;
        }

        .sidebar-header h2 {
            font-size: 20px;
            font-weight: 700;
            letter-spacing: 1px;
            background: linear-gradient(135deg, #60a5fa, #8b9ffa);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .sidebar-header p {
            font-size: 12px;
            color: rgba(255,255,255,0.5);
            margin-top: 4px;
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        .sidebar-menu {
            list-style: none;
            padding: 15px 0;
        }

        .sidebar-menu li {
            margin: 2px 12px;
        }

        .sidebar-menu li a {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 12px 16px;
            color: rgba(255, 255, 255, 0.6);
            text-decoration: none;
            border-radius: 12px;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .sidebar-menu li a i {
            width: 20px;
            font-size: 16px;
            text-align: center;
        }

        .sidebar-menu li a:hover {
            background: rgba(255,255,255,0.08);
            color: #fff;
            transform: translateX(4px);
        }

        .sidebar-menu li a.active {
            background: linear-gradient(135deg, rgba(96,165,250,0.2), rgba(167,139,250,0.2));
            color: #60a5fa;
            box-shadow: inset 3px 0 0 #60a5fa;
        }

        .sidebar-menu .menu-divider {
            height: 1px;
            background: rgba(255,255,255,0.06);
            margin: 12px 20px;
        }

        .sidebar-menu .menu-label {
            padding: 10px 20px 6px;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            color: rgba(255,255,255,0.25);
            font-weight: 600;
        }

        /* ===== MAIN CONTENT ===== */
        .main-content {
            margin-left: 260px;
            flex: 1;
            padding: 30px 35px 40px;
            min-height: 100vh;
        }

        /* ===== HEADER ===== */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header-left h1 {
            font-size: 28px;
            font-weight: 700;
            color: #1a2332;
            letter-spacing: -0.5px;
        }

        .header-left .subtitle {
            font-size: 14px;
            color: #6b7a8f;
            margin-top: 4px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header-right .user-badge {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #fff;
            padding: 8px 16px 8px 12px;
            border-radius: 50px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
        }

        .header-right .user-badge .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: linear-gradient(135deg, #60a5fa, #3e6de3);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-weight: 600;
            font-size: 16px;
        }

        .header-right .user-badge .user-name {
            font-weight: 600;
            font-size: 14px;
            color: #1a2332;
        }

        .header-right .user-badge .user-role {
            font-size: 12px;
            color: #6b7a8f;
        }

        .btn-logout {
            background: #fee2e2;
            color: #dc2626;
            border: none;
            padding: 8px 16px;
            border-radius: 50px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-logout:hover {
            background: #fecaca;
            transform: scale(1.02);
        }

        /* ===== ALERT ===== */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }

        .alert i {
            font-size: 18px;
        }

        /* ===== FORM CONTAINER ===== */
        .form-container {
            background: #ffffff;
            border-radius: 16px;
            padding: 30px 32px;
            margin-bottom: 30px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.05);
            border: 1px solid rgba(0,0,0,0.04);
        }

        .form-container .form-title {
            font-size: 20px;
            font-weight: 700;
            color: #1a2332;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .form-container .form-title i {
            color: #60a5fa;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            font-size: 14px;
            color: #1a2332;
            margin-bottom: 6px;
        }

        .form-group label .required {
            color: #dc2626;
        }

        .form-group label .label-hint {
            font-weight: 400;
            font-size: 12px;
            color: #6b7a8f;
        }

        .form-control {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: #f0f4f7;
            color: #1a2332;
            font-family: inherit;
        }

        .form-control:focus {
            outline: none;
            border-color: #60a5fa;
            box-shadow: 0 0 0 4px rgba(96,165,250,0.15);
            background: #e5edf9;
        }

        .form-control:read-only {
            background: #f0f4f7;
            cursor: not-allowed;
        }

        select.form-control {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7a8f' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 40px;
        }

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

        /* ===== NOMOR REGISTRASI ===== */
        .nomor-registrasi-wrapper {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }

        .nomor-registrasi-wrapper .form-control {
            flex: 1;
            min-width: 200px;
            font-weight: 600;
            color: #2563eb;
            background: #eff6ff;
            border-color: #bfdbfe;
        }

        .info-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            background: #f1f5f9;
            border-radius: 50px;
            font-size: 12px;
            color: #475569;
            cursor: help;
        }

        .info-badge i {
            color: #60a5fa;
        }

        /* ===== TEXT EDITOR ===== */
        .text-editor {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            overflow: hidden;
            transition: all 0.3s ease;
            background: #f8fafc;
        }

        .text-editor:focus-within {
            border-color: #60a5fa;
            box-shadow: 0 0 0 4px rgba(96,165,250,0.15);
        }

        .text-editor .toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            padding: 8px 12px;
            background: #f0f4f7;
            border-bottom: 1px solid #e2e8f0;
        }

        .text-editor .toolbar button {
            padding: 6px 12px;
            border: none;
            background: transparent;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            color: #080808;
            transition: all 0.2s ease;
            font-weight: 600;
        }

        .text-editor .toolbar button:hover {
            background: #e2e8f0;
            color: #1a2332;
        }

        .text-editor .toolbar select {
            padding: 4px 8px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            background: #fff;
            font-size: 12px;
            color: #475569;
        }

        .text-editor .rich-text {
            padding: 12px 16px;
            min-height: 120px;
            background: #fff;
            font-size: 14px;
            line-height: 1.6;
            color: #1a2332;
        }

        .text-editor .rich-text:focus {
            outline: none;
        }

        .text-editor textarea {
            width: 100%;
            padding: 12px 16px;
            border: none;
            min-height: 120px;
            font-size: 14px;
            line-height: 1.6;
            font-family: inherit;
            resize: vertical;
            background: #fff;
            color: #1a2332;
        }

        .text-editor textarea:focus {
            outline: none;
        }

        /* ===== FORM ACTIONS ===== */
        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 10px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 10px 28px;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2563eb, #4072f0);
            color: #fff;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(37,99,235,0.3);
        }

        .btn-secondary {
            background: #f1f5f9;
            color: #475569;
        }

        .btn-secondary:hover {
            background: #e2e8f0;
        }

        .btn-edit {
            background: #eff6ff;
            color: #2563eb;
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 12px;
        }

        .btn-edit:hover {
            background: #dbeafe;
        }

        .btn-delete {
            background: #fee2e2;
            color: #dc2626;
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 12px;
        }

        .btn-delete:hover {
            background: #fecaca;
        }

        /* ===== SOAL LIST ===== */
        .soal-list {
            background: #fff;
            border-radius: 16px;
            padding: 24px 28px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.05);
            border: 1px solid rgba(0,0,0,0.04);
        }

        .soal-list .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 18px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .soal-list .list-title {
            font-size: 18px;
            font-weight: 700;
            color: #1a2332;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .soal-list .list-title i {
            color: #60a5fa;
        }

        .soal-list .total-badge {
            padding: 4px 14px;
            background: #f1f5f9;
            border-radius: 50px;
            font-size: 13px;
            color: #475569;
        }

        /* ===== TABLE ===== */
        .table-wrapper {
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .data-table thead {
            background: #f8fafc;
        }

        .data-table th {
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            color: #475569;
            border-bottom: 2px solid #e2e8f0;
            white-space: nowrap;
        }

        .data-table td {
            padding: 12px 16px;
            border-bottom: 1px solid #f1f5f9;
            color: #1a2332;
            vertical-align: middle;
        }

        .data-table tbody tr {
            transition: all 0.2s ease;
        }

        .data-table tbody tr:hover {
            background: #f8fafc;
        }

        .data-table .badge-semester {
            display: inline-block;
            padding: 2px 12px;
            border-radius: 50px;
            font-size: 12px;
            font-weight: 600;
        }

        .data-table .badge-semester.gasal {
            background: #dbeafe;
            color: #2563eb;
        }

        .data-table .badge-semester.genap {
            background: #fef3c7;
            color: #d97706;
        }

        .data-table .badge-kunci {
            display: inline-block;
            width: 28px;
            height: 28px;
            line-height: 28px;
            text-align: center;
            background: #f1f5f9;
            border-radius: 50%;
            font-weight: 700;
            font-size: 13px;
            color: #475569;
        }

        .data-table .actions {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .empty-state {
            text-align: center;
            padding: 50px 20px;
            color: #6b7a8f;
        }

        .empty-state i {
            font-size: 48px;
            color: #d1d5db;
            margin-bottom: 12px;
            display: block;
        }

        /* ===== MODAL ===== */
        .modal {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: #fff;
            border-radius: 16px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-header h3 {
            font-size: 18px;
            color: #1a2332;
        }

        .modal-header .close-modal {
            font-size: 28px;
            cursor: pointer;
            color: #6b7a8f;
            transition: all 0.3s ease;
        }

        .modal-header .close-modal:hover {
            color: #dc2626;
        }

        .upload-area {
            border: 2px dashed #e2e8f0;
            border-radius: 12px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .upload-area:hover {
            border-color: #60a5fa;
            background: #f8fafc;
        }

        .upload-area.drag-over {
            border-color: #2563eb;
            background: #eff6ff;
        }

        .upload-area i {
            font-size: 48px;
            color: #60a5fa;
            margin-bottom: 12px;
        }

        .upload-area p {
            color: #6b7a8f;
            font-size: 14px;
        }

        .upload-area .file-input {
            display: none;
        }

        .upload-preview {
            max-width: 100%;
            max-height: 200px;
            margin-top: 12px;
            border-radius: 8px;
            display: none;
        }

        .upload-buttons {
            display: flex;
            gap: 12px;
            margin-top: 20px;
            justify-content: flex-end;
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 992px) {
            .sidebar {
                width: 220px;
            }
            .main-content {
                margin-left: 220px;
                padding: 20px;
            }
            .form-row {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 0;
                transform: translateX(-100%);
            }
            .sidebar.open {
                width: 280px;
                transform: translateX(0);
            }
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            .header {
                flex-direction: column;
                align-items: flex-start;
            }
            .form-container {
                padding: 20px;
            }
            .soal-list {
                padding: 16px;
            }
            .data-table {
                font-size: 13px;
            }
            .data-table th,
            .data-table td {
                padding: 8px 10px;
            }
            .nomor-registrasi-wrapper {
                flex-direction: column;
                align-items: stretch;
            }
        }

        @media (max-width: 480px) {
            .header-left h1 {
                font-size: 22px;
            }
            .form-actions {
                flex-direction: column;
            }
            .form-actions .btn {
                width: 100%;
                justify-content: center;
            }
        }

        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            color: #1a2332;
            cursor: pointer;
            padding: 8px;
            margin-bottom: 10px;
        }

        @media (max-width: 768px) {
            .hamburger {
                display: block;
            }
        }

        .sidebar-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.4);
            z-index: 99;
        }

        .sidebar-overlay.active {
            display: block;
        }
    </style>
</head>
<body>
    <!-- Overlay untuk mobile -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h2>SOCA/OSCE</h2>
            <p>Admin Panel</p>
        </div>
        <ul class="sidebar-menu">
            <li class="menu-label">Main Menu</li>
            <li><a href="dashboard.php"><i class="fas fa-th-large"></i> Dashboard</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Teori S1</li>
            <li><a href="bank_soal_teori_s1.php" class="active"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_teori_s1.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Teori</li>
            <li><a href="bank_soal_teori.php"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_teori.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Praktik</li>
            <li><a href="bank_soal_praktik.php"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_praktik.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Lainnya</li>
            <li><a href="aspek_penilaian.php"><i class="fas fa-clipboard-check"></i> Aspek Penilaian</a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> Kelola Users</a></li>
            <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <button class="hamburger" id="hamburgerBtn">
                    <i class="fas fa-bars"></i>
                </button>
                <h1>Bank Soal Teori PDG</h1>
                <div class="subtitle">Kelola soal teori untuk program studi Pendidikan Kedokteran Gigi</div>
            </div>
            <div class="header-right">
                <div class="user-badge">
                    <div class="avatar">
                        <?php echo strtoupper(substr($_SESSION['user_name'] ?? 'A', 0, 1)); ?>
                    </div>
                    <div>
                        <div class="user-name"><?php echo $_SESSION['user_name'] ?? 'Admin'; ?></div>
                        <div class="user-role">Admin Soal</div>
                    </div>
                </div>
                <a href="../logout.php" class="btn-logout">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>

        <!-- Alert -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <!-- Form -->
        <div class="form-container">
            <div class="form-title">
                <i class="fas fa-plus-circle"></i>
                Tambah Soal Teori PDG Baru
            </div>

            <form method="POST" action="" id="soalTeoriForm" enctype="multipart/form-data">
                <!-- Nomor Registrasi -->
                <div class="form-group">
                    <label><strong>Nomor Registrasi Soal <span class="required">*</span></label></strong>
                    <div class="nomor-registrasi-wrapper">
                        <input type="text" name="nomor_registrasi" 
                               value="<?php echo htmlspecialchars($auto_nomor_registrasi); ?>" 
                               readonly class="form-control">
                        <span class="info-badge">
                            <i class="fas fa-info-circle"></i>
                            Auto-generated
                        </span>
                    </div>
                </div>

                <div class="form-row">
                    <!-- Tinjauan 1 -->
                    <div class="form-group">
                        <label><strong>Tinjauan 1: Kompetensi Utama <span class="required">*</span></label></strong>
                        <input type="text" name="tinjauan1" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['tinjauan1'] ?? ''); ?>" required>
                    </div>

                    <!-- Tinjauan 2 -->
                    <div class="form-group">
                        <label><strong>Tinjauan 2: Penyakit/Kelainan</label></strong>
                        <input type="text" name="tinjauan2" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['tinjauan2'] ?? ''); ?>">
                    </div>
                </div>

                <!-- Tinjauan 3 -->
                <div class="form-group">
                    <label><strong>Tinjauan 3: Bidang Ilmu & Keterampilan KG</label></strong>
                    <input type="text" name="tinjauan3" class="form-control" 
                           value="<?php echo htmlspecialchars($_POST['tinjauan3'] ?? ''); ?>">
                </div>

                <div class="form-row">
                    <!-- Semester -->
                    <div class="form-group">
                        <label><strong>Semester <span class="required">*</span></label></strong>
                        <select name="semester" class="form-control" id="semester" required>
                            <option value="">-- Pilih Semester --</option>
                            <option value="Gasal" <?php echo ($_POST['semester'] ?? '') == 'Gasal' ? 'selected' : ''; ?>>Gasal</option>
                            <option value="Genap" <?php echo ($_POST['semester'] ?? '') == 'Genap' ? 'selected' : ''; ?>>Genap</option>
                        </select>
                    </div>

                    <!-- Blok -->
                    <div class="form-group">
                        <label><strong>Blok <span class="required">*</span></label></strong>
                        <select name="blok" class="form-control" id="blok" required>
                            <option value="">-- Pilih Blok --</option>
                            <?php 
                            if (isset($_POST['semester']) && !empty($_POST['semester'])) {
                                $selected_semester = $_POST['semester'];
                                if (isset($blok_options[$selected_semester])) {
                                    foreach ($blok_options[$selected_semester] as $blok_opt) {
                                        $selected = ($_POST['blok'] ?? '') == $blok_opt ? 'selected' : '';
                                        echo "<option value=\"$blok_opt\" $selected>$blok_opt</option>";
                                    }
                                }
                            }
                            ?>
                        </select>
                    </div>
                </div>

                <!-- CPMK -->
                <div class="form-group">
                    <label><strong>CPMK <span class="required">*</span></label></strong>
                    <select name="cpmk" class="form-control" id="cpmk" required>
                        <option value="">-- Pilih CPMK --</option>
                        <?php 
                        if (isset($_POST['blok']) && !empty($_POST['blok'])) {
                            $selected_blok = $_POST['blok'];
                            if (isset($cpmk_options[$selected_blok])) {
                                foreach ($cpmk_options[$selected_blok] as $cpmk_opt) {
                                    $selected = ($_POST['cpmk'] ?? '') == $cpmk_opt ? 'selected' : '';
                                    echo "<option value=\"$cpmk_opt\" $selected>$cpmk_opt</option>";
                                }
                            }
                        }
                        ?>
                    </select>
                </div>

                <!-- Vignette -->
                <div class="form-group">
                    <label><strong>Vignette</label></strong>
                    <div class="text-editor" id="vignette_editor_container">
                        <div class="toolbar">
                            <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                            <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                            <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                            <button type="button" data-command="insertUnorderedList" title="Bullet List">• List</button>
                            <button type="button" data-command="insertOrderedList" title="Numbered List">1. List</button>
                            <button type="button" data-command="uploadImage" title="Upload Gambar"><i class="fas fa-image"></i></button>
                            <select class="font-size-selector" title="Ukuran Font">
                                <option value="">Ukuran Font</option>
                                <option value="1">Sangat Kecil</option>
                                <option value="2">Kecil</option>
                                <option value="3">Normal</option>
                                <option value="4">Sedang</option>
                                <option value="5">Besar</option>
                                <option value="6">Sangat Besar</option>
                                <option value="7">Terbesar</option>
                            </select>
                        </div>
                        <div id="vignette_editor" class="rich-text" contenteditable="true"><?php echo $_POST['vignette'] ?? ''; ?></div>
                        <input type="hidden" id="vignette" name="vignette" value="<?php echo htmlspecialchars($_POST['vignette'] ?? ''); ?>">
                    </div>
                </div>

                <!-- Pertanyaan -->
                <div class="form-group">
                    <label><strong>Pertanyaan/Instruksi <span class="required">*</span></label></strong>
                    <div class="text-editor">
                        <div class="toolbar">
                            <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                            <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                            <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                            <button type="button" data-command="insertUnorderedList" title="Bullet List">• List</button>
                            <button type="button" data-command="insertOrderedList" title="Numbered List">1. List</button>
                        </div>
                        <textarea name="pertanyaan" class="rich-text" required><?php echo htmlspecialchars($_POST['pertanyaan'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <!-- Pilihan A -->
                    <div class="form-group">
                        <label><strong>Pilihan A</label></strong>
                        <input type="text" name="pilihan_a" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['pilihan_a'] ?? ''); ?>">
                    </div>

                    <!-- Pilihan B -->
                    <div class="form-group">
                        <label><strong>Pilihan B</label></strong>
                        <input type="text" name="pilihan_b" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['pilihan_b'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-row">
                    <!-- Pilihan C -->
                    <div class="form-group">
                        <label><strong>Pilihan C</label></strong>
                        <input type="text" name="pilihan_c" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['pilihan_c'] ?? ''); ?>">
                    </div>

                    <!-- Pilihan D -->
                    <div class="form-group">
                        <label><strong>Pilihan D</label></strong>
                        <input type="text" name="pilihan_d" class="form-control" 
                               value="<?php echo htmlspecialchars($_POST['pilihan_d'] ?? ''); ?>">
                    </div>
                </div>

                <!-- Pilihan E -->
                <div class="form-group">
                    <label><strong>Pilihan E</label></strong>
                    <input type="text" name="pilihan_e" class="form-control" 
                           value="<?php echo htmlspecialchars($_POST['pilihan_e'] ?? ''); ?>">
                </div>

                <div class="form-row">
                    <!-- Kunci -->
                    <div class="form-group">
                        <label><strong>Kunci Jawaban</label></strong>
                        <select name="kunci" class="form-control">
                            <option value="">-- Pilih Kunci --</option>
                            <option value="A" <?php echo ($_POST['kunci'] ?? '') == 'A' ? 'selected' : ''; ?>>A</option>
                            <option value="B" <?php echo ($_POST['kunci'] ?? '') == 'B' ? 'selected' : ''; ?>>B</option>
                            <option value="C" <?php echo ($_POST['kunci'] ?? '') == 'C' ? 'selected' : ''; ?>>C</option>
                            <option value="D" <?php echo ($_POST['kunci'] ?? '') == 'D' ? 'selected' : ''; ?>>D</option>
                            <option value="E" <?php echo ($_POST['kunci'] ?? '') == 'E' ? 'selected' : ''; ?>>E</option>
                        </select>
                    </div>

                    <!-- Department -->
                    <div class="form-group">
                        <label><strong>Department <span class="required">*</span></label></strong>
                        <select name="department" class="form-control" required>
                            <option value="">-- Pilih Department --</option>
                            <?php foreach ($departments as $dept): ?>
                                <option value="<?php echo htmlspecialchars($dept); ?>" 
                                        <?php echo ($department == $dept) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($dept); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Alasan Singkat -->
                <div class="form-group">
                    <label><strong>Alasan Singkat</label></strong>
                    <div class="text-editor">
                        <div class="toolbar">
                            <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                            <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                            <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                        </div>
                        <textarea name="alasan_singkat" class="rich-text"><?php echo htmlspecialchars($_POST['alasan_singkat'] ?? ''); ?></textarea>
                    </div>
                </div>

                <!-- Referensi -->
                <div class="form-group">
                    <label><strong>Referensi</label></strong>
                    <div class="text-editor">
                        <div class="toolbar">
                            <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                            <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                            <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                        </div>
                        <textarea name="referensi" class="rich-text"><?php echo htmlspecialchars($_POST['referensi'] ?? ''); ?></textarea>
                    </div>
                </div>

                <!-- Penulis -->
                <div class="form-group">
                    <label><strong>Penulis</label></strong>
                    <input type="text" name="penulis" class="form-control" 
                           value="<?php echo htmlspecialchars($_POST['penulis'] ?? ''); ?>">
                </div>

                <!-- Actions -->
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan Soal
                    </button>
                    <button type="reset" class="btn btn-secondary">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                </div>
            </form>
        </div>

        <!-- Daftar Soal 
        <div class="soal-list">
            <div class="list-header">
                <div class="list-title">
                    <i class="fas fa-list"></i>
                    Daftar Soal Teori S1
                    <span class="total-badge"><?php echo count($soal_teori); ?> soal</span>
                </div>
            </div>

            <?php if (empty($soal_teori)): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>Belum ada soal teori S1 yang tersimpan.</p>
                    <p style="font-size:13px; color:#94a3b8; margin-top:4px;">Mulai dengan menambahkan soal baru di atas.</p>
                </div>
            <?php else: ?>
                <div class="table-wrapper">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>No. Registrasi</th>
                                <th>Pertanyaan</th>
                                <th>Semester</th>
                                <th>Blok</th>
                                <th>CPMK</th>
                                <th>Kunci</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($soal_teori as $soal): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($soal['nomor_registrasi']); ?></strong></td>
                                    <td><?php echo strip_tags(substr($soal['pertanyaan'], 0, 80)) . (strlen($soal['pertanyaan']) > 80 ? '...' : ''); ?></td>
                                    <td>
                                        <span class="badge-semester <?php echo strtolower($soal['semester']); ?>">
                                            <?php echo htmlspecialchars($soal['semester']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo htmlspecialchars($soal['blok']); ?></td>
                                    <td><?php echo htmlspecialchars($soal['cpmk']); ?></td>
                                    <td>
                                        <?php if ($soal['kunci']): ?>
                                            <span class="badge-kunci"><?php echo htmlspecialchars($soal['kunci']); ?></span>
                                        <?php else: ?>
                                            <span style="color:#94a3b8; font-size:12px;">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="actions">
                                            <a href="edit_soal_teori_s1.php?id=<?php echo $soal['id']; ?>" class="btn-edit">
                                                <i class="fas fa-edit"></i> Edit
                                            </a>
                                            <a href="hapus_soal_teori_s1.php?id=<?php echo $soal['id']; ?>" class="btn-delete" onclick="return confirm('Yakin hapus soal ini?')">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?> 
        </div>
    </div> -->

    <!-- Modal Upload Gambar -->
    <div id="imageUploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-image" style="color:#60a5fa;"></i> Upload Gambar</h3>
                <span class="close-modal">&times;</span>
            </div>
            <div class="upload-area" id="uploadArea">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>Klik atau seret gambar ke sini</p>
                <input type="file" id="imageFile" class="file-input" accept="image/*">
                <img id="uploadPreview" class="upload-preview" src="" alt="Preview">
            </div>
            <div class="upload-buttons">
                <button id="cancelUpload" class="btn btn-secondary">Batal</button>
                <button id="insertImage" class="btn btn-primary">Sisipkan</button>
            </div>
        </div>
    </div>

    <script>
        // ===== SIDEBAR TOGGLE =====
        const hamburger = document.getElementById('hamburgerBtn');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');

        function toggleSidebar() {
            sidebar.classList.toggle('open');
            overlay.classList.toggle('active');
        }

        hamburger.addEventListener('click', toggleSidebar);
        overlay.addEventListener('click', toggleSidebar);

        // ===== DROPDOWN TERKAIT =====
        document.addEventListener('DOMContentLoaded', function() {
            const semesterSelect = document.getElementById('semester');
            const blokSelect = document.getElementById('blok');
            const cpmkSelect = document.getElementById('cpmk');
            
            const blokOptions = {
                'Gasal': ['Blok 1', 'Blok 2', 'Blok 3', 'Blok 7', 'Blok 8', 'Blok 9', 'Blok 13', 'Blok 14', 'Blok 15', 'Blok 16', 'Blok 17', 'Blok 21', 'Blok 22', 'Blok 23'],
                'Genap': ['Blok 4', 'Blok 5', 'Blok 6', 'Blok 10', 'Blok 11', 'Blok 12', 'Blok 18', 'Blok 19', 'Blok 20']
            };
            
            const cpmkOptions = {
                'Blok 1': ['CPMK Blok 1.1', 'CPMK Blok 1.2', 'CPMK Blok 1.3'],
                'Blok 2': ['CPMK Blok 2.1', 'CPMK Blok 2.2', 'CPMK Blok 2.3'],
                'Blok 3': ['CPMK Blok 3.1', 'CPMK Blok 3.2', 'CPMK Blok 3.3'],
                'Blok 4': ['CPMK Blok 4.1', 'CPMK Blok 4.2', 'CPMK Blok 4.3'],
                'Blok 5': ['CPMK Blok 5.1', 'CPMK Blok 5.2', 'CPMK Blok 5.3'],
                'Blok 6': ['CPMK Blok 6.1', 'CPMK Blok 6.2', 'CPMK Blok 6.3'],
                'Blok 7': ['CPMK Blok 7.1', 'CPMK Blok 7.2', 'CPMK Blok 7.3'],
                'Blok 8': ['CPMK Blok 8.1', 'CPMK Blok 8.2', 'CPMK Blok 8.3'],
                'Blok 9': ['CPMK Blok 9.1', 'CPMK Blok 9.2', 'CPMK Blok 9.3'],
                'Blok 10': ['CPMK Blok 10.1', 'CPMK Blok 10.2', 'CPMK Blok 10.3'],
                'Blok 11': ['CPMK Blok 11.1', 'CPMK Blok 11.2', 'CPMK Blok 11.3'],
                'Blok 12': ['CPMK Blok 12.1', 'CPMK Blok 12.2', 'CPMK Blok 12.3'],
                'Blok 13': ['CPMK Blok 13.1', 'CPMK Blok 13.2', 'CPMK Blok 13.3'],
                'Blok 14': ['CPMK Blok 14.1', 'CPMK Blok 14.2', 'CPMK Blok 14.3'],
                'Blok 15': ['CPMK Blok 15.1', 'CPMK Blok 15.2', 'CPMK Blok 15.3'],
                'Blok 16': ['CPMK Blok 16.1', 'CPMK Blok 16.2', 'CPMK Blok 16.3'],
                'Blok 17': ['CPMK Blok 17.1', 'CPMK Blok 17.2', 'CPMK Blok 17.3'],
                'Blok 18': ['CPMK Blok 18.1', 'CPMK Blok 18.2', 'CPMK Blok 18.3'],
                'Blok 19': ['CPMK Blok 19.1', 'CPMK Blok 19.2', 'CPMK Blok 19.3'],
                'Blok 20': ['CPMK Blok 20.1', 'CPMK Blok 20.2', 'CPMK Blok 20.3'],
                'Blok 21': ['CPMK Blok 21.1', 'CPMK Blok 21.2', 'CPMK Blok 21.3'],
                'Blok 22': ['CPMK Blok 22.1', 'CPMK Blok 22.2', 'CPMK Blok 22.3'],
                'Blok 23': ['CPMK Blok 23.1', 'CPMK Blok 23.2', 'CPMK Blok 23.3']
            };
            
            semesterSelect.addEventListener('change', function() {
                const selectedSemester = this.value;
                blokSelect.innerHTML = '<option value="">-- Pilih Blok --</option>';
                cpmkSelect.innerHTML = '<option value="">-- Pilih CPMK --</option>';
                
                if (selectedSemester && blokOptions[selectedSemester]) {
                    blokOptions[selectedSemester].forEach(function(blok) {
                        const option = document.createElement('option');
                        option.value = blok;
                        option.textContent = blok;
                        blokSelect.appendChild(option);
                    });
                }
            });
            
            blokSelect.addEventListener('change', function() {
                const selectedBlok = this.value;
                cpmkSelect.innerHTML = '<option value="">-- Pilih CPMK --</option>';
                
                if (selectedBlok && cpmkOptions[selectedBlok]) {
                    cpmkOptions[selectedBlok].forEach(function(cpmk) {
                        const option = document.createElement('option');
                        option.value = cpmk;
                        option.textContent = cpmk;
                        cpmkSelect.appendChild(option);
                    });
                }
            });

            // ===== TEXT EDITOR =====
            const textEditors = document.querySelectorAll('.text-editor');
            textEditors.forEach(function(editor) {
                const toolbar = editor.querySelector('.toolbar');
                const textarea = editor.querySelector('textarea');
                const contentEditable = editor.querySelector('[contenteditable="true"]');
                const targetElement = textarea || contentEditable;
                
                toolbar.addEventListener('click', function(e) {
                    if (e.target.tagName === 'BUTTON' || e.target.parentElement.tagName === 'BUTTON') {
                        const button = e.target.tagName === 'BUTTON' ? e.target : e.target.parentElement;
                        const command = button.dataset.command;
                        
                        if (command === 'uploadImage') {
                            openImageUploadModal(targetElement);
                            return;
                        }
                        
                        document.execCommand(command, false, null);
                        if (textarea) textarea.focus();
                    }
                });
                
                const fontSizeSelector = toolbar.querySelector('.font-size-selector');
                if (fontSizeSelector) {
                    fontSizeSelector.addEventListener('change', function() {
                        const size = this.value;
                        if (size) {
                            document.execCommand('fontSize', false, size);
                            if (textarea) textarea.focus();
                        }
                    });
                }
                
                if (contentEditable) {
                    contentEditable.addEventListener('input', function() {
                        const hiddenInput = editor.querySelector('input[type="hidden"]');
                        if (hiddenInput) {
                            hiddenInput.value = this.innerHTML;
                        }
                    });
                }
            });

            // ===== IMAGE UPLOAD MODAL =====
            const modal = document.getElementById('imageUploadModal');
            const uploadArea = document.getElementById('uploadArea');
            const imageFile = document.getElementById('imageFile');
            const uploadPreview = document.getElementById('uploadPreview');
            const cancelUpload = document.getElementById('cancelUpload');
            const insertImage = document.getElementById('insertImage');
            const closeModal = document.querySelector('.close-modal');
            
            let currentEditor = null;
            let uploadedImageData = null;
            
            function openImageUploadModal(editor) {
                currentEditor = editor;
                modal.classList.add('active');
                uploadPreview.style.display = 'none';
                uploadArea.querySelector('p').textContent = 'Klik atau seret gambar ke sini';
                uploadedImageData = null;
            }
            
            function closeImageUploadModal() {
                modal.classList.remove('active');
                currentEditor = null;
                uploadedImageData = null;
            }
            
            closeModal.addEventListener('click', closeImageUploadModal);
            cancelUpload.addEventListener('click', closeImageUploadModal);
            modal.addEventListener('click', function(e) {
                if (e.target === modal) closeImageUploadModal();
            });
            
            imageFile.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file && file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        uploadedImageData = e.target.result;
                        uploadPreview.src = uploadedImageData;
                        uploadPreview.style.display = 'block';
                        uploadArea.querySelector('p').textContent = 'Gambar siap diupload';
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('drag-over');
            });
            
            uploadArea.addEventListener('dragleave', function() {
                uploadArea.classList.remove('drag-over');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('drag-over');
                
                const file = e.dataTransfer.files[0];
                if (file && file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        uploadedImageData = e.target.result;
                        uploadPreview.src = uploadedImageData;
                        uploadPreview.style.display = 'block';
                        uploadArea.querySelector('p').textContent = 'Gambar siap diupload';
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            insertImage.addEventListener('click', function() {
                if (uploadedImageData && currentEditor) {
                    const img = document.createElement('img');
                    img.src = uploadedImageData;
                    img.style.maxWidth = '100%';
                    img.style.height = 'auto';
                    img.style.borderRadius = '8px';
                    
                    if (currentEditor.tagName === 'TEXTAREA') {
                        const cursorPos = currentEditor.selectionStart;
                        const textBefore = currentEditor.value.substring(0, cursorPos);
                        const textAfter = currentEditor.value.substring(cursorPos);
                        currentEditor.value = textBefore + '\n[Gambar:' + uploadedImageData + ']\n' + textAfter;
                    } else {
                        const selection = window.getSelection();
                        if (selection.rangeCount > 0) {
                            const range = selection.getRangeAt(0);
                            range.insertNode(img);
                        } else {
                            currentEditor.appendChild(img);
                        }
                        
                        const hiddenInput = currentEditor.closest('.text-editor').querySelector('input[type="hidden"]');
                        if (hiddenInput) {
                            hiddenInput.value = currentEditor.innerHTML;
                        }
                    }
                    
                    closeImageUploadModal();
                }
            });
            
            uploadArea.addEventListener('click', function() {
                imageFile.click();
            });
        });

        // ===== CLOSE SIDEBAR ON RESIZE =====
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                sidebar.classList.remove('open');
                overlay.classList.remove('active');
            }
        });
    </script>
</body>
</html>