<?php
require_once '../includes/auth.php';

if (!isAdmin()) {
    redirect('../login.php');
}

$station_id = $_GET['id'] ?? null;

if (!$station_id) {
    redirect('soal.php');
}

// Ambil data station
$stmt = $pdo->prepare("SELECT * FROM stations WHERE id = ?");
$stmt->execute([$station_id]);
$station = $stmt->fetch();

if (!$station) {
    redirect('soal.php');
}

// Ambil aspek penilaian
$stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ? ORDER BY nomor_urut");
$stmt->execute([$station_id]);
$aspeks = $stmt->fetchAll();

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

// Update station
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_station'])) {
    $nama_station = sanitize($_POST['nama_station']);
    $deskripsi = $_POST['deskripsi'];
    $instruksi_peserta = $_POST['instruksi_peserta'];
    $instruksi_penguji = $_POST['instruksi_penguji'];
    
    // Hitung total maksimal dari skor yang dipilih
    $total_maksimal = 0;
    if (isset($_POST['aspek_nama']) && is_array($_POST['aspek_nama'])) {
        foreach ($_POST['aspek_nama'] as $index => $aspek_nama) {
            if (!empty($aspek_nama)) {
                $skor_2 = isset($_POST['skor_2'][$index]) ? 1 : 0;
                $skor_1 = isset($_POST['skor_1'][$index]) ? 1 : 0;
                
                if ($skor_2) $total_maksimal += 2;
                else if ($skor_1) $total_maksimal += 1;
            }
        }
    }
    
    $stmt = $pdo->prepare("UPDATE stations SET nama_station = ?, deskripsi = ?, instruksi_peserta = ?, instruksi_penguji = ?, total_maksimal = ? WHERE id = ?");
    
    if ($stmt->execute([$nama_station, $deskripsi, $instruksi_peserta, $instruksi_penguji, $total_maksimal, $station_id])) {
        $success = "Station berhasil diupdate!";
        
        // Hapus aspek lama
        $stmt = $pdo->prepare("DELETE FROM aspek_penilaian WHERE station_id = ?");
        $stmt->execute([$station_id]);
        
        // Tambah aspek penilaian baru jika ada
        if (isset($_POST['aspek_nama']) && is_array($_POST['aspek_nama'])) {
            foreach ($_POST['aspek_nama'] as $index => $aspek_nama) {
                if (!empty($aspek_nama)) {
                    $nomor_urut = intval($_POST['nomor_urut'][$index]);
                    $skor_0 = isset($_POST['skor_0'][$index]) ? 1 : 0;
                    $skor_1 = isset($_POST['skor_1'][$index]) ? 1 : 0;
                    $skor_2 = isset($_POST['skor_2'][$index]) ? 1 : 0;
                    $deskripsi_0 = $_POST['deskripsi_0'][$index] ?? '';
                    $deskripsi_1 = $_POST['deskripsi_1'][$index] ?? '';
                    $deskripsi_2 = $_POST['deskripsi_2'][$index] ?? '';
                    $item_verifikasi = $_POST['item_verifikasi'][$index] ?? '';
                    
                    $stmt = $pdo->prepare("INSERT INTO aspek_penilaian (station_id, nomor_urut, nama_aspek, skor_0, skor_1, skor_2, deskripsi_0, deskripsi_1, deskripsi_2, item_verifikasi) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$station_id, $nomor_urut, $aspek_nama, $skor_0, $skor_1, $skor_2, $deskripsi_0, $deskripsi_1, $deskripsi_2, $item_verifikasi]);
                }
            }
        }
        
        // Redirect to prevent resubmission
        redirect("edit_station.php?id=$station_id&success=1");
    } else {
        $error = "Gagal mengupdate station!";
    }
}

if (isset($_GET['success'])) {
    $success = "Station berhasil diupdate!";
    // Refresh data aspek
    $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ? ORDER BY nomor_urut");
    $stmt->execute([$station_id]);
    $aspeks = $stmt->fetchAll();
}
?>

<?php include 'header.php'; ?>

<div class="content">
    <h2>Edit Station: <?php echo htmlspecialchars($station['nama_station']); ?></h2>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="card">
        <form method="POST" id="stationForm">
            <div class="form-group">
                <label for="nama_station">Nama Station:</label>
                <input type="text" id="nama_station" name="nama_station" value="<?php echo htmlspecialchars($station['nama_station']); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="deskripsi">Deskripsi/Skenario:</label>
                <div id="deskripsiEditor" class="rich-text-editor" data-target="deskripsi"><?php echo $station['deskripsi']; ?></div>
                <textarea id="deskripsi" name="deskripsi" style="display: none;"><?php echo htmlspecialchars($station['deskripsi']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="instruksi_peserta">Instruksi untuk Peserta:</label>
                <div id="instruksiPesertaEditor" class="rich-text-editor" data-target="instruksi_peserta"><?php echo $station['instruksi_peserta']; ?></div>
                <textarea id="instruksi_peserta" name="instruksi_peserta" style="display: none;"><?php echo htmlspecialchars($station['instruksi_peserta']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="instruksi_penguji">Instruksi untuk Penguji:</label>
                <div id="instruksiPengujiEditor" class="rich-text-editor" data-target="instruksi_penguji"><?php echo $station['instruksi_penguji']; ?></div>
                <textarea id="instruksi_penguji" name="instruksi_penguji" style="display: none;"><?php echo htmlspecialchars($station['instruksi_penguji']); ?></textarea>
            </div>
            
            <!-- Aspek Penilaian -->
            <div class="aspek-penilaian-section">
                <div class="section-header">
                    <h4>Aspek yang Dinilai</h4>
                    <div class="aspek-counter">
                        <span id="aspekCountDisplay"><?php echo count($aspeks); ?></span>/<span id="maxAspekDisplay">40</span> Aspek
                    </div>
                </div>
                <div id="aspekContainer">
                    <?php foreach ($aspeks as $index => $aspek): ?>
                        <div class="aspek-item" data-aspek-id="<?php echo $aspek['id']; ?>">
                            <div class="aspek-header">
                                <h5>Aspek Penilaian <span class="aspek-number"><?php echo $index + 1; ?></span></h5>
                                <button type="button" class="btn btn-danger btn-sm hapus-aspek" title="Hapus aspek ini">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            </div>
                            
                            <div class="form-group">
                                <label>Nomor Urut:</label>
                                <input type="number" name="nomor_urut[]" class="nomor-urut" min="1" value="<?php echo $aspek['nomor_urut']; ?>" required>
                                <small class="form-hint">Urutan penampilan aspek penilaian</small>
                            </div>

                            <div class="form-group">
                                <label>Nama Aspek:</label>
                                <div class="mini-editor nama-aspek-editor" data-target="aspek_nama[]"><?php echo htmlspecialchars($aspek['nama_aspek']); ?></div>
                                <textarea name="aspek_nama[]" style="display: none;"><?php echo htmlspecialchars($aspek['nama_aspek']); ?></textarea>
                            </div>
                            
                            <!-- Item Verifikasi -->
                            <div class="item-verifikasi-section" style="margin-top: 20px;">
                                <label style="font-weight: 600; margin-bottom: 10px; display: block;">
                                    <i class="fas fa-list-check"></i> Item Verifikasi (Optional)
                                    <small style="font-weight: normal; color: #6c757d;">
                                        - Daftar item untuk diverifikasi oleh penguji
                                    </small>
                                </label>
                                <div class="item-verifikasi-input">
                                    <textarea 
                                        name="item_verifikasi[]" 
                                        class="item-verifikasi-textarea" 
                                        placeholder="Masukkan item-item untuk diverifikasi (satu item per baris):
Contoh:
1. Alat diagnostik
2. Occlusal biterim
3. Sliding caliper
4. Spidol
...
*Item ini hanya sebagai alat bantu verifikasi, tidak mempengaruhi nilai"
                                        rows="4"
                                        style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;"><?php echo htmlspecialchars($aspek['item_verifikasi'] ?? ''); ?></textarea>
                                    <small style="color: #6c757d; display: block; margin-top: 5px;">
                                        <i class="fas fa-info-circle"></i> Item akan muncul sebagai checkbox di halaman penilaian penguji
                                    </small>
                                </div>
                            </div>
                            
                            <div class="skor-options">
                                <label><strong>Skor Penilaian:</strong></label>
                                <div class="checkbox-group">
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_0[]" value="1" <?php echo $aspek['skor_0'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-0-badge">Skor 0</span>
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_1[]" value="1" <?php echo $aspek['skor_1'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-1-badge">Skor 1</span>
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_2[]" value="1" <?php echo $aspek['skor_2'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-2-badge">Skor 2</span>
                                    </label>
                                </div>
                                <small class="form-hint">Pilih skor yang akan digunakan untuk aspek ini</small>
                            </div>
                            
                            <div class="skor-description">
                                <div class="skor-item skor-0" style="<?php echo !$aspek['skor_0'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-0-badge">Deskripsi Skor 0</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_0[]"><?php echo htmlspecialchars($aspek['deskripsi_0']); ?></div>
                                    <textarea name="deskripsi_0[]" style="display: none;"><?php echo htmlspecialchars($aspek['deskripsi_0']); ?></textarea>
                                </div>
                                
                                <div class="skor-item skor-1" style="<?php echo !$aspek['skor_1'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-1-badge">Deskripsi Skor 1</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_1[]"><?php echo htmlspecialchars($aspek['deskripsi_1']); ?></div>
                                    <textarea name="deskripsi_1[]" style="display: none;"><?php echo htmlspecialchars($aspek['deskripsi_1']); ?></textarea>
                                </div>
                                
                                <div class="skor-item skor-2" style="<?php echo !$aspek['skor_2'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-2-badge">Deskripsi Skor 2</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_2[]"><?php echo htmlspecialchars($aspek['deskripsi_2']); ?></div>
                                    <textarea name="deskripsi_2[]" style="display: none;"><?php echo htmlspecialchars($aspek['deskripsi_2']); ?></textarea>
                                </div>
                            </div>
                            
                            <div class="aspek-actions">
                                <button type="button" class="btn btn-secondary btn-sm duplicate-aspek" title="Duplikat aspek ini">
                                    <i class="fas fa-copy"></i> Duplikat
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" id="tambahAspek" class="btn btn-secondary">
                    <i class="fas fa-plus"></i> Tambah Aspek
                </button>
            </div>
            
            <div style="margin-top: 20px;">
                <button type="submit" name="update_station" class="btn btn-primary">Update Station</button>
                <a href="soal.php" class="btn btn-secondary">Kembali</a>
            </div>
        </form>
    </div>
</div>

<!-- Template untuk Aspek Penilaian -->
<script type="text/template" id="aspekTemplate">
    <div class="aspek-item">
        <div class="aspek-header">
            <h5>Aspek Penilaian <span class="aspek-number">1</span></h5>
            <button type="button" class="btn btn-danger btn-sm hapus-aspek" title="Hapus aspek ini">
                <i class="fas fa-trash"></i> Hapus
            </button>
        </div>
        
        <div class="form-group">
            <label>Nomor Urut:</label>
            <input type="number" name="nomor_urut[]" class="nomor-urut" min="1" value="1" required>
            <small class="form-hint">Urutan penampilan aspek penilaian</small>
        </div>

        <div class="form-group">
            <label>Nama Aspek:</label>
            <div class="mini-editor nama-aspek-editor" data-target="aspek_nama[]"></div>
            <textarea name="aspek_nama[]" style="display: none;"></textarea>
        </div>
        
        <!-- Item Verifikasi -->
        <div class="item-verifikasi-section" style="margin-top: 20px;">
            <label style="font-weight: 600; margin-bottom: 10px; display: block;">
                <i class="fas fa-list-check"></i> Item Verifikasi (Optional)
                <small style="font-weight: normal; color: #6c757d;">
                    - Daftar item untuk diverifikasi oleh penguji
                </small>
            </label>
            <div class="item-verifikasi-input">
                <textarea 
                    name="item_verifikasi[]" 
                    class="item-verifikasi-textarea" 
                    placeholder="Masukkan item-item untuk diverifikasi (satu item per baris):
Contoh:
1. Alat diagnostik
2. Occlusal biterim
3. Sliding caliper
4. Spidol
...
*Item ini hanya sebagai alat bantu verifikasi, tidak mempengaruhi nilai"
                    rows="4"
                    style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;"></textarea>
                <small style="color: #6c757d; display: block; margin-top: 5px;">
                    <i class="fas fa-info-circle"></i> Item akan muncul sebagai checkbox di halaman penilaian penguji
                </small>
            </div>
        </div>
        
        <div class="skor-options">
            <label><strong>Skor Penilaian:</strong></label>
            <div class="checkbox-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_0[]" value="1" checked> 
                    <span class="skor-badge skor-0-badge">Skor 0</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_1[]" value="1" checked> 
                    <span class="skor-badge skor-1-badge">Skor 1</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_2[]" value="1" checked> 
                    <span class="skor-badge skor-2-badge">Skor 2</span>
                </label>
            </div>
            <small class="form-hint">Pilih skor yang akan digunakan untuk aspek ini</small>
        </div>
        
        <div class="skor-description">
            <div class="skor-item skor-0">
                <label>
                    <span class="skor-badge skor-0-badge">Deskripsi Skor 0</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_0[]"></div>
                <textarea name="deskripsi_0[]" style="display: none;"></textarea>
            </div>
            
            <div class="skor-item skor-1">
                <label>
                    <span class="skor-badge skor-1-badge">Deskripsi Skor 1</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_1[]"></div>
                <textarea name="deskripsi_1[]" style="display: none;"></textarea>
            </div>
            
            <div class="skor-item skor-2">
                <label>
                    <span class="skor-badge skor-2-badge">Deskripsi Skor 2</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_2[]"></div>
                <textarea name="deskripsi_2[]" style="display: none;"></textarea>
            </div>
        </div>
        
        <div class="aspek-actions">
            <button type="button" class="btn btn-secondary btn-sm duplicate-aspek" title="Duplikat aspek ini">
                <i class="fas fa-copy"></i> Duplikat
            </button>
        </div>
    </div>
</script>

<style>
/* Style untuk aspek item */
.aspek-item {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: #f9f9f9;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.aspek-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #e9ecef;
}

.aspek-header h5 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.2rem;
}

.aspek-number {
    background: #3498db;
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
}

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

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #495057;
}

.form-hint {
    display: block;
    margin-top: 5px;
    font-size: 0.85rem;
    color: #6c757d;
}

.checkbox-group {
    display: flex;
    gap: 15px;
    margin: 10px 0;
    flex-wrap: wrap;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.skor-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    font-weight: 600;
    font-size: 0.85rem;
}

.skor-0-badge { background: #dc3545; color: white; }
.skor-1-badge { background: #ffc107; color: #000; }
.skor-2-badge { background: #28a745; color: white; }

.skor-item {
    margin-bottom: 15px;
    padding: 15px;
    background: white;
    border-radius: 6px;
    border-left: 4px solid #ddd;
}

.skor-0 { border-left-color: #dc3545; }
.skor-1 { border-left-color: #ffc107; }
.skor-2 { border-left-color: #28a745; }

.aspek-actions {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #e9ecef;
    text-align: right;
}

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

.aspek-counter {
    background: #6c757d;
    color: white;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 0.9rem;
    font-weight: 600;
}

/* Style untuk mini editor */
.mini-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
    background: white;
}

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

.mini-toolbar .toolbar-btn {
    padding: 4px 8px;
    border: none;
    background: white;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
}

.mini-toolbar .toolbar-btn:hover {
    background: #e9e9e9;
    transform: translateY(-1px);
}

.mini-editor-content {
    min-height: 60px;
    padding: 10px;
    max-height: 150px;
    overflow-y: auto;
    line-height: 1.5;
}

.mini-editor-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 5px 0;
}

/* Style untuk rich text editor */
.rich-text-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
}

.editor-toolbar {
    background: #f5f5f5;
    padding: 8px;
    border-bottom: 1px solid #ddd;
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    align-items: center;
}

.editor-toolbar .toolbar-btn {
    padding: 6px 10px;
    border: none;
    background: white;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
    border: 1px solid #ddd;
}

.editor-toolbar .toolbar-btn:hover {
    background: #e9e9e9;
    transform: translateY(-1px);
}

.editor-content {
    min-height: 200px;
    padding: 15px;
    max-height: 400px;
    overflow-y: auto;
    line-height: 1.6;
}

.editor-content img {
    max-width: 100%;
    height: auto;
    border-radius: 6px;
    margin: 10px 0;
}

.aspek-penilaian-section {
    max-height: 600px;
    overflow-y: auto;
    padding-right: 10px;
}

.aspek-penilaian-section::-webkit-scrollbar {
    width: 8px;
}

.aspek-penilaian-section::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.aspek-penilaian-section::-webkit-scrollbar-thumb {
    background: #667eea;
    border-radius: 4px;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1.2rem;
    border: none;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.3s;
}

.btn-sm {
    padding: 0.3rem 0.8rem;
    font-size: 0.8rem;
}

.btn-primary {
    background: #3498db;
    color: white;
}

.btn-primary:hover {
    background: #2980b9;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-danger {
    background: #e74c3c;
    color: white;
}

.btn-danger:hover {
    background: #c0392b;
}

.alert {
    padding: 1rem;
    border-radius: 6px;
    margin-bottom: 1rem;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
    .aspek-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }
    
    .checkbox-group {
        flex-direction: column;
        gap: 8px;
    }
    
    .aspek-item {
        padding: 15px;
    }
    
    .section-header {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>

<script src="../assets/js/soal.js"></script>
<script>
// Inisialisasi untuk edit station
document.addEventListener('DOMContentLoaded', function() {
    console.log('Edit Station initialized');
    
    // Function to initialize all mini editors in an aspek element
    function initMiniEditorsInAspek(aspekElement) {
        console.log('Initializing mini editors in aspek');
        
        // Initialize Nama Aspek editor
        const namaAspekEditor = aspekElement.querySelector('.mini-editor.nama-aspek-editor');
        if (namaAspekEditor && !namaAspekEditor.hasAttribute('data-initialized')) {
            try {
                // Check if editor already has content
                const contentDiv = namaAspekEditor.querySelector('.editor-content');
                const textarea = aspekElement.querySelector('textarea[name="aspek_nama[]"]');
                
                if (!contentDiv && textarea && textarea.value) {
                    // Create content div if not exists
                    const newContent = document.createElement('div');
                    newContent.className = 'editor-content mini-editor-content';
                    newContent.contentEditable = true;
                    newContent.innerHTML = textarea.value;
                    namaAspekEditor.appendChild(newContent);
                }
                
                new MiniRichTextEditor(namaAspekEditor);
                namaAspekEditor.setAttribute('data-initialized', 'true');
                console.log('Initialized nama aspek editor');
            } catch(e) {
                console.error('Error initializing nama aspek editor:', e);
            }
        }
        
        // Initialize Deskripsi Skor editors
        const skorEditors = aspekElement.querySelectorAll('.mini-editor:not(.nama-aspek-editor)');
        skorEditors.forEach((editor, idx) => {
            if (!editor.hasAttribute('data-initialized')) {
                try {
                    // Check if editor already has content
                    const contentDiv = editor.querySelector('.editor-content');
                    const targetName = editor.getAttribute('data-target');
                    const textarea = aspekElement.querySelector(`textarea[name="${targetName}"]`);
                    
                    if (!contentDiv && textarea && textarea.value) {
                        // Create content div if not exists
                        const newContent = document.createElement('div');
                        newContent.className = 'editor-content mini-editor-content';
                        newContent.contentEditable = true;
                        newContent.innerHTML = textarea.value;
                        editor.appendChild(newContent);
                    }
                    
                    new MiniRichTextEditor(editor);
                    editor.setAttribute('data-initialized', 'true');
                    console.log(`Initialized skor editor ${idx + 1}`);
                } catch(e) {
                    console.error(`Error initializing skor editor ${idx + 1}:`, e);
                }
            }
        });
    }
    
    // Initialize all existing aspek items
    function initAllExistingAspek() {
        const aspekItems = document.querySelectorAll('.aspek-item');
        console.log('Found existing aspek items:', aspekItems.length);
        
        aspekItems.forEach((aspek, index) => {
            console.log(`Initializing aspek ${index + 1}`);
            initMiniEditorsInAspek(aspek);
            setupSkorCheckboxesForAspek(aspek);
        });
    }
    
    // Setup skor checkboxes visibility for an aspek
    function setupSkorCheckboxesForAspek(aspekElement) {
        const skor0Checkbox = aspekElement.querySelector('input[name="skor_0[]"]');
        const skor1Checkbox = aspekElement.querySelector('input[name="skor_1[]"]');
        const skor2Checkbox = aspekElement.querySelector('input[name="skor_2[]"]');
        const skor0Item = aspekElement.querySelector('.skor-item.skor-0');
        const skor1Item = aspekElement.querySelector('.skor-item.skor-1');
        const skor2Item = aspekElement.querySelector('.skor-item.skor-2');
        
        const updateVisibility = () => {
            if (skor0Item) skor0Item.style.display = skor0Checkbox && skor0Checkbox.checked ? 'block' : 'none';
            if (skor1Item) skor1Item.style.display = skor1Checkbox && skor1Checkbox.checked ? 'block' : 'none';
            if (skor2Item) skor2Item.style.display = skor2Checkbox && skor2Checkbox.checked ? 'block' : 'none';
        };
        
        if (skor0Checkbox) skor0Checkbox.addEventListener('change', updateVisibility);
        if (skor1Checkbox) skor1Checkbox.addEventListener('change', updateVisibility);
        if (skor2Checkbox) skor2Checkbox.addEventListener('change', updateVisibility);
        
        // Initial update
        updateVisibility();
    }
    
    // Override AspekManager.prototype.initRichTextEditorsForAspek
    if (typeof AspekManager !== 'undefined') {
        const originalInitEditors = AspekManager.prototype.initRichTextEditorsForAspek;
        AspekManager.prototype.initRichTextEditorsForAspek = function(aspekElement) {
            console.log('Overridden initRichTextEditorsForAspek called');
            setTimeout(() => {
                initMiniEditorsInAspek(aspekElement);
            }, 200);
        };
        
        // Also override setupSkorCheckboxes
        const originalSetupSkor = AspekManager.prototype.setupSkorCheckboxes;
        AspekManager.prototype.setupSkorCheckboxes = function(aspekElement) {
            console.log('Overridden setupSkorCheckboxes called');
            setTimeout(() => {
                setupSkorCheckboxesForAspek(aspekElement);
            }, 100);
        };
    }
    
    // Initialize main rich text editors
    function initMainEditors() {
        const editors = [
            { id: 'deskripsiEditor', target: 'deskripsi' },
            { id: 'instruksiPesertaEditor', target: 'instruksi_peserta' },
            { id: 'instruksiPengujiEditor', target: 'instruksi_penguji' }
        ];
        
        editors.forEach(editor => {
            const element = document.getElementById(editor.id);
            if (element && typeof RichTextEditor !== 'undefined') {
                try {
                    // Check if already has content
                    const existingContent = element.querySelector('.editor-content');
                    const textarea = document.getElementById(editor.target);
                    
                    if (!existingContent && textarea && textarea.value) {
                        const newContent = document.createElement('div');
                        newContent.className = 'editor-content';
                        newContent.contentEditable = true;
                        newContent.innerHTML = textarea.value;
                        element.appendChild(newContent);
                    }
                    
                    new RichTextEditor(element);
                    console.log('Initialized main editor:', editor.id);
                } catch(e) {
                    console.error('Error initializing main editor:', editor.id, e);
                }
            }
        });
    }
    
    // Initialize item verifikasi toggle
    function initItemVerifikasiToggle() {
        document.querySelectorAll('.toggle-item-verifikasi').forEach(checkbox => {
            const aspekItem = checkbox.closest('.aspek-item');
            const verifikasiSection = aspekItem?.querySelector('.item-verifikasi-section');
            
            if (verifikasiSection) {
                if (checkbox.checked) {
                    verifikasiSection.style.display = 'block';
                } else {
                    verifikasiSection.style.display = 'none';
                }
                
                checkbox.addEventListener('change', function() {
                    if (verifikasiSection) {
                        verifikasiSection.style.display = this.checked ? 'block' : 'none';
                    }
                });
            }
        });
    }
    
    // Live preview for item verifikasi
    function initItemVerifikasiPreview() {
        document.querySelectorAll('.item-verifikasi-textarea').forEach(textarea => {
            const aspekItem = textarea.closest('.aspek-item');
            const previewSection = aspekItem?.querySelector('.item-preview');
            const previewContent = aspekItem?.querySelector('.preview-content');
            
            if (previewSection && previewContent) {
                if (textarea.value.trim()) {
                    previewSection.style.display = 'block';
                    updatePreview(textarea.value, previewContent);
                }
                
                textarea.addEventListener('input', function() {
                    if (this.value.trim()) {
                        previewSection.style.display = 'block';
                        updatePreview(this.value, previewContent);
                    } else {
                        previewSection.style.display = 'none';
                    }
                });
            }
        });
    }
    
    function updatePreview(value, previewContent) {
        const items = value.split('\n').filter(item => item.trim() !== '');
        let previewHTML = '<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;">';
        
        items.forEach((item) => {
            if (item.trim()) {
                previewHTML += `
                    <div style="display: flex; align-items: center; gap: 5px; background: white; padding: 5px 10px; border-radius: 4px; border: 1px solid #dee2e6;">
                        <input type="checkbox" disabled>
                        <span>${escapeHtml(item.trim())}</span>
                    </div>
                `;
            }
        });
        
        previewHTML += '</div>';
        previewContent.innerHTML = previewHTML;
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // Run all initializations
    setTimeout(() => {
        initMainEditors();
        initAllExistingAspek();
        initItemVerifikasiToggle();
        initItemVerifikasiPreview();
    }, 500);
    
    // Observer for new aspek items added by AspekManager
    const aspekContainer = document.getElementById('aspekContainer');
    if (aspekContainer) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length) {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === 1 && node.classList && node.classList.contains('aspek-item')) {
                            console.log('New aspek item detected, initializing...');
                            setTimeout(() => {
                                initMiniEditorsInAspek(node);
                                setupSkorCheckboxesForAspek(node);
                                initItemVerifikasiToggle();
                                initItemVerifikasiPreview();
                            }, 300);
                        }
                    });
                }
            });
        });
        
        observer.observe(aspekContainer, { childList: true });
    }
    
    // Fix form submission to ensure all data is synced
    const stationForm = document.getElementById('stationForm');
    if (stationForm) {
        stationForm.addEventListener('submit', function(e) {
            console.log('Form submitting, syncing all editors...');
            
            // Sync all rich text editors
            document.querySelectorAll('.mini-editor').forEach(editor => {
                const contentDiv = editor.querySelector('.editor-content');
                const targetName = editor.getAttribute('data-target');
                if (contentDiv && targetName) {
                    const aspekItem = editor.closest('.aspek-item');
                    let textarea;
                    if (aspekItem) {
                        textarea = aspekItem.querySelector(`textarea[name="${targetName}"]`);
                    } else {
                        textarea = document.getElementById(targetName);
                    }
                    if (textarea) {
                        textarea.value = contentDiv.innerHTML;
                        console.log('Synced:', targetName);
                    }
                }
            });
            
            // Sync all skor checkboxes values
            document.querySelectorAll('input[type="checkbox"][name^="skor_"]').forEach(checkbox => {
                checkbox.value = checkbox.checked ? '1' : '0';
            });
        });
    }
});
</script>

<?php include 'footer.php'; ?>