<?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 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'
];

// Fungsi untuk generate nomor registrasi otomatis
function generateNomorRegistrasi($pdo) {
    try {
        $stmt = $pdo->query("SELECT nomor_registrasi FROM bank_soal_praktik ORDER BY id DESC LIMIT 1");
        $last_soal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $next_number = 1;
        
        if ($last_soal && preg_match('/^(\d+)\/FKG-UMS\/U\.P\//', $last_soal['nomor_registrasi'], $matches)) {
            $next_number = intval($matches[1]) + 1;
        }
        
        $current_month = date('m');
        $current_year = date('Y');
        
        return sprintf('%02d', $next_number) . "/FKG-UMS/U.P/" . $current_month . "/" . $current_year;
    } catch (PDOException $e) {
        error_log("Error in generateNomorRegistrasi: " . $e->getMessage());
        return '01/FKG-UMS/U.P/' . date('m') . '/' . date('Y');
    }
}

// Fungsi untuk upload gambar
function uploadGambar($file) {
    $target_dir = "../uploads/gambar_soal/";
    
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $max_size = 5 * 1024 * 1024;
    
    $filename = basename($file["name"]);
    $target_file = $target_dir . uniqid() . '_' . preg_replace("/[^a-zA-Z0-9\.]/", "_", $filename);
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    
    if (!in_array($imageFileType, $allowed_types)) {
        throw new Exception("Hanya file JPG, JPEG, PNG, GIF, dan WebP yang diizinkan.");
    }
    
    if ($file["size"] > $max_size) {
        throw new Exception("Ukuran file terlalu besar. Maksimal 5MB.");
    }
    
    $check = getimagesize($file["tmp_name"]);
    if ($check === false) {
        throw new Exception("File bukan gambar yang valid.");
    }
    
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        return str_replace('../', '', $target_file);
    } else {
        throw new Exception("Terjadi kesalahan saat mengupload gambar.");
    }
}

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

// Proses form jika ada data yang dikirim
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nomor_registrasi = $_POST['nomor_registrasi'] ?? '';
    $tinjauan1 = $_POST['tinjauan1'] ?? '';
    $tinjauan2 = $_POST['tinjauan2'] ?? '';
    $sub_tinjauan2 = $_POST['sub_tinjauan2'] ?? '';
    $tinjauan3 = $_POST['tinjauan3'] ?? '';
    $tinjauan4 = $_POST['tinjauan4'] ?? '';
    $tujuan = $_POST['tujuan'] ?? '';
    $skenario_klinik = $_POST['skenario_klinik'] ?? '';
    $tugas_kandidat = $_POST['tugas_kandidat'] ?? '';
    $tugas_penguji = $_POST['tugas_penguji'] ?? '';
    $instruksi_pasien = $_POST['instruksi_pasien'] ?? '';
    $peralatan = $_POST['peralatan'] ?? '';
    $gambar_soal = $_POST['gambar_soal'] ?? '';
    $department = $_POST['department'] ?? '';
    $referensi = $_POST['referensi'] ?? '';
    $penulis = $_POST['penulis'] ?? '';
    
    $gambar_path = '';
    
    if (empty($nomor_registrasi) || empty($tinjauan1) || empty($skenario_klinik)) {
        $error = 'Nomor Registrasi, Tinjauan 1, dan Skenario Klinik harus diisi!';
    } else {
        try {
            if (isset($_FILES['gambar_upload']) && $_FILES['gambar_upload']['error'] != UPLOAD_ERR_NO_FILE) {
                if ($_FILES['gambar_upload']['error'] == UPLOAD_ERR_OK) {
                    $gambar_path = uploadGambar($_FILES['gambar_upload']);
                } else {
                    throw new Exception("Error upload gambar: " . $_FILES['gambar_upload']['error']);
                }
            }
            
            if (empty($gambar_path) && !empty($gambar_soal)) {
                $gambar_path = $gambar_soal;
            }
            
            $stmt = $pdo->prepare("INSERT INTO bank_soal_praktik (
                nomor_registrasi, tinjauan1, tinjauan2, sub_tinjauan2, tinjauan3, tinjauan4,
                tujuan, skenario_klinik, tugas_kandidat, tugas_penguji, instruksi_pasien,
                peralatan, gambar_soal, department, referensi, penulis
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $nomor_registrasi, $tinjauan1, $tinjauan2, $sub_tinjauan2, $tinjauan3, $tinjauan4,
                $tujuan, $skenario_klinik, $tugas_kandidat, $tugas_penguji, $instruksi_pasien,
                $peralatan, $gambar_path, $department, $referensi, $penulis
            ]);
            
            $success = 'Soal praktik berhasil disimpan!';
            $auto_nomor_registrasi = generateNomorRegistrasi($pdo);
            $_POST = array();
            
        } catch (Exception $e) {
            $error = 'Terjadi kesalahan: ' . $e->getMessage();
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan database: ' . $e->getMessage();
        }
    }
}

// Ambil data soal praktik untuk ditampilkan
$soal_praktik = [];
try {
    $stmt = $pdo->query("SELECT * FROM bank_soal_praktik ORDER BY created_at DESC");
    $soal_praktik = $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 Praktik - 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: #fff;
            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, #4669f7);
            -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, #3b47ef);
            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: #fff;
            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-section {
            margin-bottom: 28px;
            padding-bottom: 24px;
            border-bottom: 1px solid #f1f5f9;
        }

        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .form-section .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #1a2332;
            margin-bottom: 18px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

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

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

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

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

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

        .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: #fff;
        }

        .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: #f1f5f9;
            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: #475569;
            transition: all 0.2s ease;
            font-weight: 600;
        }

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

        .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;
        }

        /* ===== UPLOAD AREA ===== */
        .upload-container {
            border: 2px dashed #e2e8f0;
            border-radius: 12px;
            padding: 30px 20px;
            text-align: center;
            transition: all 0.3s ease;
            background: #f8fafc;
            cursor: pointer;
        }

        .upload-container:hover {
            border-color: #60a5fa;
            background: #eff6ff;
        }

        .upload-container.dragover {
            border-color: #2563eb;
            background: #dbeafe;
        }

        .upload-container i {
            font-size: 40px;
            color: #60a5fa;
            margin-bottom: 10px;
        }

        .upload-container .upload-info {
            font-size: 13px;
            color: #6b7a8f;
            margin-top: 8px;
        }

        .file-input-wrapper {
            position: relative;
            display: inline-block;
            margin: 12px 0;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-input-label {
            display: inline-block;
            padding: 8px 20px;
            background: linear-gradient(135deg, #2563eb, #303ded);
            color: #fff;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            font-size: 14px;
        }

        .file-input-label:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(37,99,235,0.3);
        }

        .upload-preview {
            max-width: 200px;
            max-height: 150px;
            margin: 12px auto;
            border-radius: 8px;
            display: none;
            border: 2px solid #e2e8f0;
        }

        /* ===== 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, #2f3ff5);
            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;
            text-decoration: none;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

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

        .btn-delete {
            background: #fee2e2;
            color: #dc2626;
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 12px;
            text-decoration: none;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

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

        .btn-sm {
            padding: 2px 10px;
            font-size: 12px;
            border-radius: 4px;
            background: #f1f5f9;
            color: #475569;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

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

        /* ===== 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-department {
            display: inline-block;
            padding: 2px 10px;
            border-radius: 50px;
            font-size: 11px;
            font-weight: 600;
            background: #dbeafe;
            color: #2563eb;
        }

        .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;
        }

        .empty-state h3 {
            font-size: 18px;
            color: #1a2332;
            margin-bottom: 6px;
        }

        /* ===== 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;
        }

        .scroll-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #2563eb;
            color: #fff;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: none;
            cursor: pointer;
            font-size: 18px;
            box-shadow: 0 4px 16px rgba(37,99,235,0.3);
            transition: all 0.3s ease;
            opacity: 0;
            visibility: hidden;
            z-index: 50;
        }

        .scroll-top.visible {
            opacity: 1;
            visibility: visible;
        }

        .scroll-top:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 24px rgba(37,99,235,0.4);
        }
    </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"><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" class="active"><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="preview_aspek_penilaian.php"><i class="fas fa-eye"></i> Preview Aspek</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 Praktik</h1>
                <div class="subtitle">Kelola soal ujian praktik untuk program studi 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>
                <strong>Tambah Soal Praktik Baru</strong>
            </div>

            <form method="POST" action="" id="soalPraktikForm" enctype="multipart/form-data">
                <!-- Bagian 1: Informasi Dasar -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-info-circle"></i> Informasi Dasar Soal
                    </div>

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

                    <div class="form-row">
                        <div class="form-group">
                            <label><strong>Sub Tinjauan 2: Penyakit/Kelainan</label></strong>
                            <input type="text" name="sub_tinjauan2" class="form-control" 
                                   value="<?php echo htmlspecialchars($_POST['sub_tinjauan2'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label><strong>Tinjauan 3: Ranah Keterampilan Klinis</label></strong>
                            <input type="text" name="tinjauan3" class="form-control" 
                                   value="<?php echo htmlspecialchars($_POST['tinjauan3'] ?? ''); ?>">
                        </div>
                    </div>

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

                <!-- Bagian 2: Konten Soal -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-file-alt"></i> <strong>Konten Soal Praktik</strong>
                    </div>

                    <div class="form-group">
                        <label><strong>Tujuan</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="tujuan" class="rich-text"><?php echo htmlspecialchars($_POST['tujuan'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><strong>Skenario Klinik <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="skenario_klinik" class="rich-text" required><?php echo htmlspecialchars($_POST['skenario_klinik'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><strong>Tugas untuk Kandidat</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="tugas_kandidat" class="rich-text"><?php echo htmlspecialchars($_POST['tugas_kandidat'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Bagian 3: Instruksi dan Perlengkapan -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-clipboard-list"></i> <strong>Instruksi dan Perlengkapan</strong>
                    </div>

                    <div class="form-group">
                        <label><strong>Tugas untuk Penguji</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="tugas_penguji" class="rich-text"><?php echo htmlspecialchars($_POST['tugas_penguji'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><strong>Instruksi Untuk Pasien Simulasi</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="instruksi_pasien" class="rich-text"><?php echo htmlspecialchars($_POST['instruksi_pasien'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><strong>Peralatan yang dibutuhkan</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="peralatan" class="rich-text"><?php echo htmlspecialchars($_POST['peralatan'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Bagian 4: Informasi Tambahan -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-image"></i> <strong>Gambar Soal</strong>
                    </div>

                    <div class="form-group">
                        <div class="upload-container" id="uploadContainer">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p style="font-weight:500; color:#1a2332;">Drag & drop file gambar di sini atau klik untuk memilih</p>
                            <div class="file-input-wrapper">
                                <input type="file" id="gambar_upload" name="gambar_upload" accept="image/*">
                                <span class="file-input-label">
                                    <i class="fas fa-folder-open"></i> Pilih File
                                </span>
                            </div>
                            <div class="upload-info">
                                <i class="fas fa-info-circle"></i>
                                Format: JPG, JPEG, PNG, GIF, WebP (Maks. 5MB)
                            </div>
                            <img id="uploadPreview" class="upload-preview" src="" alt="Preview">
                        </div>
                        <input type="hidden" name="gambar_soal" id="gambar_soal" value="">
                    </div>

                    <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 (isset($_POST['department']) && $_POST['department'] == $dept) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($dept); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <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>

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

                <!-- Actions -->
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan Soal Praktik
                    </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 Praktik
                    <span class="total-badge"><?php echo count($soal_praktik); ?> soal</span>
                </div>
            </div>

            <?php if (empty($soal_praktik)): ?>
                <div class="empty-state">
                    <i class="fas fa-stethoscope"></i>
                    <h3>Belum ada soal praktik</h3>
                    <p>Mulai dengan menambahkan soal praktik baru di atas.</p>
                </div>
            <?php else: ?>
                <div class="table-wrapper">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>No. Registrasi</th>
                                <th>Skenario Klinik</th>
                                <th>Kompetensi Utama</th>
                                <th>Department</th>
                                <th>Gambar</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($soal_praktik as $soal): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($soal['nomor_registrasi']); ?></strong></td>
                                    <td><?php echo strip_tags(substr($soal['skenario_klinik'], 0, 80)) . (strlen($soal['skenario_klinik']) > 80 ? '...' : ''); ?></td>
                                    <td><?php echo htmlspecialchars($soal['tinjauan1']); ?></td>
                                    <td><span class="badge-department"><?php echo htmlspecialchars($soal['department'] ?? '-'); ?></span></td>
                                    <td>
                                        <?php if (!empty($soal['gambar_soal'])): ?>
                                            <?php if (filter_var($soal['gambar_soal'], FILTER_VALIDATE_URL)): ?>
                                                <a href="<?php echo htmlspecialchars($soal['gambar_soal']); ?>" target="_blank" class="btn-sm">
                                                    <i class="fas fa-external-link-alt"></i> Lihat
                                                </a>
                                            <?php else: ?>
                                                <a href="../<?php echo htmlspecialchars($soal['gambar_soal']); ?>" target="_blank" class="btn-sm">
                                                    <i class="fas fa-image"></i> Lihat
                                                </a>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span style="color:#94a3b8;font-size:12px;">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="actions">
                                            <a href="edit_soal_praktik.php?id=<?php echo $soal['id']; ?>" class="btn-edit">
                                                <i class="fas fa-edit"></i> Edit
                                            </a>
                                            <a href="hapus_soal_praktik.php?id=<?php echo $soal['id']; ?>" 
                                               class="btn-delete" 
                                               onclick="return confirm('Yakin hapus soal praktik ini?')">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div> -->

    <!-- Scroll to Top -->
    <button class="scroll-top" id="scrollTopBtn" title="Kembali ke atas">
        <i class="fas fa-arrow-up"></i>
    </button>

    <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);

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

        // ===== SCROLL TO TOP =====
        const scrollBtn = document.getElementById('scrollTopBtn');
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                scrollBtn.classList.add('visible');
            } else {
                scrollBtn.classList.remove('visible');
            }
        });

        scrollBtn.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });

        // ===== TEXT EDITOR =====
        document.addEventListener('DOMContentLoaded', function() {
            const textEditors = document.querySelectorAll('.text-editor');
            textEditors.forEach(function(editor) {
                const toolbar = editor.querySelector('.toolbar');
                const textarea = editor.querySelector('textarea');
                
                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;
                        
                        document.execCommand(command, false, null);
                        textarea.focus();
                    }
                });
            });

            // ===== UPLOAD GAMBAR =====
            const uploadContainer = document.getElementById('uploadContainer');
            const fileInput = document.getElementById('gambar_upload');
            const preview = document.getElementById('uploadPreview');
            
            uploadContainer.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadContainer.classList.add('dragover');
            });
            
            uploadContainer.addEventListener('dragleave', function() {
                uploadContainer.classList.remove('dragover');
            });
            
            uploadContainer.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadContainer.classList.remove('dragover');
                
                if (e.dataTransfer.files.length) {
                    fileInput.files = e.dataTransfer.files;
                    handleFileSelect(e.dataTransfer.files[0]);
                }
            });
            
            fileInput.addEventListener('change', function(e) {
                if (this.files.length) {
                    handleFileSelect(this.files[0]);
                }
            });
            
            uploadContainer.addEventListener('click', function(e) {
                if (e.target.tagName !== 'BUTTON' && e.target.tagName !== 'SPAN') {
                    fileInput.click();
                }
            });

            function handleFileSelect(file) {
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                if (!allowedTypes.includes(file.type)) {
                    alert('Hanya file gambar (JPG, PNG, GIF, WebP) yang diizinkan.');
                    fileInput.value = '';
                    return;
                }
                
                if (file.size > 5 * 1024 * 1024) {
                    alert('Ukuran file terlalu besar. Maksimal 5MB.');
                    fileInput.value = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }

            // Reset preview saat form direset
            document.querySelector('form').addEventListener('reset', function() {
                preview.style.display = 'none';
                preview.src = '';
                fileInput.value = '';
            });
        });
    </script>
</body>
</html>