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

// 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 = '';

// Buat folder uploads jika belum ada
$upload_dir = '../uploads/soal_teori/';
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'] ?? '';
    $tinjauan1 = $_POST['tinjauan1'] ?? '';
    $tinjauan2 = $_POST['tinjauan2'] ?? '';
    $tinjauan3 = $_POST['tinjauan3'] ?? '';
    $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'] ?? '';
    
    // Debug: log data yang diterima
    error_log("Vignette received: " . substr($vignette, 0, 200));
    error_log("Pertanyaan received: " . substr($pertanyaan, 0, 200));
    
    // Validasi data
    if (empty($nomor_registrasi) || empty($tinjauan1) || empty($pertanyaan)) {
        $error = 'Nomor Registrasi, Tinjauan 1, dan Pertanyaan 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);
        
        // Debug setelah processing
        error_log("Vignette after processing: " . substr($vignette, 0, 200));
        
        // Simpan ke database
        try {
            $stmt = $pdo->prepare("INSERT INTO bank_soal_teori (
                nomor_registrasi, tinjauan1, tinjauan2, tinjauan3, 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, $vignette, $pertanyaan,
                $pilihan_a, $pilihan_b, $pilihan_c, $pilihan_d, $pilihan_e, $kunci,
                $department, $alasan_singkat, $referensi, $penulis
            ]);
            
            $success = 'Soal teori berhasil disimpan!';
            
            // Reset form jika berhasil
            $_POST = array();
            $nomor_registrasi = $tinjauan1 = $tinjauan2 = $tinjauan3 = $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;
    }
    
    // Cari semua base64 images dalam konten
    preg_match_all('/<img[^>]+src="data:image\/([^;]+);base64,([^"]+)"[^>]*>/i', $content, $matches);
    
    if (empty($matches[0])) {
        return $content;
    }
    
    error_log("Found " . count($matches[0]) . " base64 images to process");
    
    foreach ($matches[0] as $index => $imgTag) {
        $imageType = $matches[1][$index];
        $base64Data = $matches[2][$index];
        
        // Generate nama file unik
        $filename = uniqid() . '_' . time() . '.' . $imageType;
        $filepath = $upload_dir . $filename;
        
        // Decode base64 dan simpan sebagai file
        $imageData = base64_decode($base64Data);
        if (file_put_contents($filepath, $imageData)) {
            // Ganti base64 dengan path file di konten
            $newImgTag = '<img src="../uploads/soal_teori/' . $filename . '" alt="Gambar" style="max-width: 100%; height: auto;">';
            $content = str_replace($imgTag, $newImgTag, $content);
            error_log("Image saved: " . $filename);
        } else {
            error_log("Failed to save image: " . $filename);
        }
    }
    
    return $content;
}

// Ambil data soal untuk ditampilkan
$soal_teori = [];
try {
    $stmt = $pdo->query("SELECT * FROM bank_soal_teori 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 - SOCA OSCE System</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/bank_soal_teori.css">
    <!-- Tambahkan Font Awesome untuk ikon -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<style>
    .sidebar {
    width: 250px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 2px 0 10px rgba(0,0,0,0.1);
}

.sidebar-menu {
    list-style: none;
    padding: 1rem 0;

}

.sidebar-menu li {
    margin-bottom: 0.5rem;
}

.sidebar-menu a {
    display: flex;
    align-items: center;
    padding: 0.75rem 1.5rem;
    color: #080808ff;
    text-decoration: none;
    transition: all 0.3s;
}

.sidebar-menu a:hover,
.sidebar-menu a.active {
    background: #b2bdecff;
    color: white;
}

.sidebar-menu i {
    margin-right: 10px;
    width: 20px;
    text-align: center;
}

/* Styling untuk text editor yang diperbarui */
.text-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.toolbar {
    background-color: #f5f5f5;
    padding: 5px;
    border-bottom: 1px solid #ddd;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.toolbar button, .toolbar select {
    background: white;
    border: 1px solid #ccc;
    border-radius: 3px;
    padding: 5px 8px;
    cursor: pointer;
    font-size: 14px;
}

.toolbar button:hover, .toolbar select:hover {
    background-color: #e9e9e9;
}

.toolbar .font-size-selector {
    width: 70px;
}

.rich-text {
    width: 100%;
    min-height: 150px;
    padding: 10px;
    border: none;
    resize: vertical;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.5;
}

/* Modal untuk upload gambar */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 10% auto;
    padding: 20px;
    border-radius: 5px;
    width: 400px;
    max-width: 90%;
}

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

.close-modal {
    font-size: 24px;
    cursor: pointer;
}

.upload-area {
    border: 2px dashed #ccc;
    border-radius: 5px;
    padding: 20px;
    text-align: center;
    margin-bottom: 15px;
    cursor: pointer;
}

.upload-area:hover {
    border-color: #667eea;
}

.upload-area i {
    font-size: 48px;
    color: #667eea;
    margin-bottom: 10px;
}

.file-input {
    display: none;
}

.upload-preview {
    max-width: 100%;
    max-height: 200px;
    margin-top: 10px;
    display: none;
}

.upload-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 15px;
}
/* Style untuk text editor dengan upload gambar */
.text-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.toolbar {
    background-color: #f5f5f5;
    padding: 5px;
    border-bottom: 1px solid #ddd;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.toolbar button, .toolbar select {
    background: white;
    border: 1px solid #ccc;
    border-radius: 3px;
    padding: 5px 8px;
    cursor: pointer;
    font-size: 14px;
}

.toolbar button:hover, .toolbar select:hover {
    background-color: #e9e9e9;
}

.rich-text {
    width: 100%;
    min-height: 150px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    resize: vertical;
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 1.5;
    overflow-y: auto;
}

.rich-text:focus {
    border-color: #667eea;
    outline: none;
}

.rich-text img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 10px 0;
}

.char-counter {
    font-size: 12px;
    color: #666;
    text-align: right;
    margin-top: 5px;
}
</style>
<body>
    <div class="sidebar">
    <ul class="sidebar-menu">
        <li><a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
        <li><a href="bank_soal_teori.php" class="active"><i class="fas fa-book"></i> Bank Soal Teori</a></li>
        <li><a href="bank_soal_praktik.php"><i class="fas fa-clipboard-check"></i> Bank Soal Praktik</a></li>
        <li><a href="list_soal_teori.php"><i class="fas fa-list"></i> Daftar Soal Teori</a></li>
        <li><a href="list_soal_praktik.php"><i class="fas fa-list"></i> Daftar Soal Praktik</a></li>
        <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
    </ul>
</div>
            

        <div class="main-content">
            <div class="header">
                <h1>Bank Soal Teori</h1>
                <div class="user-info">
                    <span><i class="fas fa-user"></i> Halo, <?php echo $_SESSION['user_name'] ?? 'Admin'; ?></span>
                    <a href="../logout.php" class="btn btn-danger btn-sm">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>

            <div class="content">
                <?php if ($error): ?>
                    <div class="alert alert-error"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <div class="form-container">
                    <h2>Tambah Soal Teori Baru</h2>
                    <form method="POST" action="" id="soalTeoriForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="nomor_registrasi">1. Nomor Registrasi Soal *</label>
                            <input type="text" id="nomor_registrasi" name="nomor_registrasi" 
                                   value="<?php echo htmlspecialchars($_POST['nomor_registrasi'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="tinjauan1">2. Tinjauan 1: Kompetensi Utama *</label>
                            <input type="text" id="tinjauan1" name="tinjauan1" 
                                   value="<?php echo htmlspecialchars($_POST['tinjauan1'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="tinjauan2">3. Tinjauan 2: Penyakit/Kelainan</label>
                            <input type="text" id="tinjauan2" name="tinjauan2" 
                                   value="<?php echo htmlspecialchars($_POST['tinjauan2'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="tinjauan3">4. Tinjauan 3: Bidang Ilmu & Keterampilan KG</label>
                            <input type="text" id="tinjauan3" name="tinjauan3" 
                                   value="<?php echo htmlspecialchars($_POST['tinjauan3'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
    <label for="vignette">5. Vignette</label>
    <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>
            <!-- Tombol untuk upload gambar -->
            <button type="button" data-command="uploadImage" title="Upload Gambar"><i class="fas fa-image"></i></button>
            <!-- Dropdown untuk ukuran font -->
            <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>
        <!-- Contenteditable DIV untuk editor -->
        <div id="vignette_editor" class="rich-text" contenteditable="true"><?php echo $_POST['vignette'] ?? ''; ?></div>
        <!-- Hidden input untuk form submission -->
        <input type="hidden" id="vignette" name="vignette" value="<?php echo htmlspecialchars($_POST['vignette'] ?? ''); ?>">
    </div>
</div>
                        
                        <div class="form-group">
                            <label for="pertanyaan">6. Pertanyaan/Instruksi *</label>
                            <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 id="pertanyaan" name="pertanyaan" class="rich-text" required><?php echo htmlspecialchars($_POST['pertanyaan'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <!-- Sisa form tetap sama -->
                        <div class="form-group">
                            <label for="pilihan_a">7. Pilihan A</label>
                            <input type="text" id="pilihan_a" name="pilihan_a" 
                                   value="<?php echo htmlspecialchars($_POST['pilihan_a'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="pilihan_b">8. Pilihan B</label>
                            <input type="text" id="pilihan_b" name="pilihan_b" 
                                   value="<?php echo htmlspecialchars($_POST['pilihan_b'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="pilihan_c">9. Pilihan C</label>
                            <input type="text" id="pilihan_c" name="pilihan_c" 
                                   value="<?php echo htmlspecialchars($_POST['pilihan_c'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="pilihan_d">10. Pilihan D</label>
                            <input type="text" id="pilihan_d" name="pilihan_d" 
                                   value="<?php echo htmlspecialchars($_POST['pilihan_d'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="pilihan_e">11. Pilihan E</label>
                            <input type="text" id="pilihan_e" name="pilihan_e" 
                                   value="<?php echo htmlspecialchars($_POST['pilihan_e'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="kunci">12. Kunci</label>
                            <select id="kunci" name="kunci">
                                <option value="">-- Pilih Kunci Jawaban --</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>
                        
                        <div class="form-group">
                            <label for="department">13. Department</label>
                            <input type="text" id="department" name="department" 
                                   value="<?php echo htmlspecialchars($_POST['department'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="alasan_singkat">14. Alasan Singkat</label>
                            <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 id="alasan_singkat" name="alasan_singkat" class="rich-text"><?php echo htmlspecialchars($_POST['alasan_singkat'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="referensi">15. Referensi</label>
                            <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 id="referensi" name="referensi" class="rich-text"><?php echo htmlspecialchars($_POST['referensi'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="penulis">16. Penulis</label>
                            <input type="text" id="penulis" name="penulis" 
                                   value="<?php echo htmlspecialchars($_POST['penulis'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">17. Simpan</button>
                            <button type="reset" class="btn btn-secondary">Reset</button>
                        </div>
                    </form>
                </div>

                <!-- Daftar Soal Teori yang Sudah Ada -->
                <div class="soal-list">
                    <h2>Daftar Soal Teori</h2>
                    <?php if (empty($soal_teori)): ?>
                        <p>Belum ada soal teori.</p>
                    <?php else: ?>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>No. Registrasi</th>
                                    <th>Pertanyaan</th>
                                    <th>Kompetensi Utama</th>
                                    <th>Kunci</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($soal_teori as $soal): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($soal['nomor_registrasi']); ?></td>
                                        <td><?php echo strip_tags(substr($soal['pertanyaan'], 0, 100)) . '...'; ?></td>
                                        <td><?php echo htmlspecialchars($soal['tinjauan1']); ?></td>
                                        <td><?php echo htmlspecialchars($soal['kunci']); ?></td>
                                        <td>
                                            <a href="edit_soal_teori.php?id=<?php echo $soal['id']; ?>" class="btn btn-edit">Edit</a>
                                            <a href="hapus_soal_teori.php?id=<?php echo $soal['id']; ?>" class="btn btn-delete" onclick="return confirm('Yakin hapus soal?')">Hapus</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    
    <!-- Modal untuk upload gambar -->
    <div id="imageUploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>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 src="../assets/js/bank_soal_teori.js"></script>
    <script>
        // JavaScript untuk fungsi upload gambar dan ukuran font
        document.addEventListener('DOMContentLoaded', function() {
            // Variabel global
            let currentTextarea = null;
            let uploadedImageUrl = null;
            
            // Fungsi untuk eksekusi perintah pada textarea
            function execCommand(command, value = null) {
                if (currentTextarea) {
                    currentTextarea.focus();
                    document.execCommand(command, false, value);
                }
            }
            
            // Event listener untuk toolbar buttons
            document.querySelectorAll('.toolbar button[data-command]').forEach(button => {
                button.addEventListener('click', function() {
                    const command = this.getAttribute('data-command');
                    execCommand(command);
                });
            });
            
            // Event listener untuk ukuran font
            document.querySelectorAll('.font-size-selector').forEach(select => {
                select.addEventListener('change', function() {
                    if (this.value) {
                        execCommand('fontSize', this.value);
                        this.value = ''; // Reset dropdown
                    }
                });
            });
            
            // Event listener untuk fokus pada textarea
            document.querySelectorAll('.rich-text').forEach(textarea => {
                textarea.addEventListener('focus', function() {
                    currentTextarea = this;
                });
            });
            
            // Modal untuk upload gambar
            const modal = document.getElementById('imageUploadModal');
            const uploadBtn = document.getElementById('uploadImageBtn');
            const closeModal = document.querySelector('.close-modal');
            const cancelUpload = document.getElementById('cancelUpload');
            const uploadArea = document.getElementById('uploadArea');
            const imageFile = document.getElementById('imageFile');
            const uploadPreview = document.getElementById('uploadPreview');
            const insertImageBtn = document.getElementById('insertImage');
            
            // Buka modal upload gambar
            uploadBtn.addEventListener('click', function() {
                if (currentTextarea) {
                    modal.style.display = 'block';
                    uploadedImageUrl = null;
                    uploadPreview.style.display = 'none';
                    imageFile.value = '';
                } else {
                    alert('Silakan fokus pada textarea terlebih dahulu');
                }
            });
            
            // Tutup modal
            function closeImageModal() {
                modal.style.display = 'none';
            }
            
            closeModal.addEventListener('click', closeImageModal);
            cancelUpload.addEventListener('click', closeImageModal);
            
            // Event untuk area upload
            uploadArea.addEventListener('click', function() {
                imageFile.click();
            });
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.style.borderColor = '#667eea';
                this.style.backgroundColor = '#f0f0f0';
            });
            
            uploadArea.addEventListener('dragleave', function() {
                this.style.borderColor = '#ccc';
                this.style.backgroundColor = '';
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                this.style.borderColor = '#ccc';
                this.style.backgroundColor = '';
                
                if (e.dataTransfer.files.length) {
                    handleImageFile(e.dataTransfer.files[0]);
                }
            });
            
            // Event untuk input file
            imageFile.addEventListener('change', function() {
                if (this.files.length) {
                    handleImageFile(this.files[0]);
                }
            });
            
            // Fungsi untuk menangani file gambar
            function handleImageFile(file) {
                // Validasi tipe file
                if (!file.type.match('image.*')) {
                    alert('Hanya file gambar yang diizinkan');
                    return;
                }
                
                // Validasi ukuran file (maksimal 2MB)
                if (file.size > 2 * 1024 * 1024) {
                    alert('Ukuran file maksimal 2MB');
                    return;
                }
                
                // Tampilkan preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    uploadPreview.src = e.target.result;
                    uploadPreview.style.display = 'block';
                    uploadedImageUrl = e.target.result;
                };
                reader.readAsDataURL(file);
            }
            
            // Event untuk tombol sisipkan gambar
            insertImageBtn.addEventListener('click', function() {
                if (uploadedImageUrl) {
                    // Sisipkan gambar ke textarea
                    const imgHTML = `<img src="${uploadedImageUrl}" alt="Gambar" style="max-width: 100%;">`;
                    execCommand('insertHTML', imgHTML);
                    closeImageModal();
                } else {
                    alert('Silakan pilih gambar terlebih dahulu');
                }
            });
        });
    </script>
</body>
</html>