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

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

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

// Tambah station baru
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tambah_station'])) {
    $nama_station = sanitize($_POST['nama_station']);
    $deskripsi = $_POST['deskripsi'];
    $instruksi_peserta = $_POST['instruksi_peserta'];
    $instruksi_penguji = $_POST['instruksi_penguji'];
    
    // Hitung total maksimal
    $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_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;
                
                // Hitung skor maksimal untuk aspek ini
                if ($skor_2) $total_maksimal += 2;
                else if ($skor_1) $total_maksimal += 1;
                else if ($skor_0) $total_maksimal += 0;
            }
        }
    }
    
    $stmt = $pdo->prepare("INSERT INTO stations (nama_station, deskripsi, instruksi_peserta, instruksi_penguji, total_maksimal) VALUES (?, ?, ?, ?, ?)");
    
    if ($stmt->execute([$nama_station, $deskripsi, $instruksi_peserta, $instruksi_penguji, $total_maksimal])) {
        $station_id = $pdo->lastInsertId();
        $success = "Station berhasil ditambahkan! Total Maksimal: " . $total_maksimal;
        
        // Tambah aspek penilaian 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] ?? '';
                    
                    $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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$station_id, $nomor_urut, $aspek_nama, $skor_0, $skor_1, $skor_2, $deskripsi_0, $deskripsi_1, $deskripsi_2]);
                }
            }
        }
    } else {
        $error = "Gagal menambahkan station!";
    }
}

// Edit nilai maksimal station
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_nilai_maksimal'])) {
    $station_id = $_POST['station_id'];
    $total_maksimal = intval($_POST['total_maksimal']);
    
    $stmt = $pdo->prepare("UPDATE stations SET total_maksimal = ? WHERE id = ?");
    if ($stmt->execute([$total_maksimal, $station_id])) {
        $success = "Nilai maksimal berhasil diperbarui!";
    } else {
        $error = "Gagal memperbarui nilai maksimal!";
    }
}

// Hapus station
if (isset($_GET['hapus_station'])) {
    $station_id = $_GET['hapus_station'];
    
    $stmt = $pdo->prepare("DELETE FROM stations WHERE id = ?");
    if ($stmt->execute([$station_id])) {
        $success = "Station berhasil dihapus!";
    } else {
        $error = "Gagal menghapus station!";
    }
}

// Duplicate station
if (isset($_GET['duplicate_station'])) {
    $station_id = $_GET['duplicate_station'];
    
    try {
        $pdo->beginTransaction();
        
        // Ambil data station yang akan diduplikasi
        $stmt = $pdo->prepare("SELECT * FROM stations WHERE id = ?");
        $stmt->execute([$station_id]);
        $original_station = $stmt->fetch();
        
        if ($original_station) {
            // Insert station baru dengan nama yang berbeda
            $new_nama_station = $original_station['nama_station'] . ' (Copy)';
            $stmt = $pdo->prepare("INSERT INTO stations (nama_station, deskripsi, instruksi_peserta, instruksi_penguji, total_maksimal) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $new_nama_station,
                $original_station['deskripsi'],
                $original_station['instruksi_peserta'],
                $original_station['instruksi_penguji'],
                $original_station['total_maksimal']
            ]);
            
            $new_station_id = $pdo->lastInsertId();
            
            // Duplikasi aspek penilaian
            $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ?");
            $stmt->execute([$station_id]);
            $aspeks = $stmt->fetchAll();
            
            foreach ($aspeks as $aspek) {
                $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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $new_station_id,
                    $aspek['nomor_urut'],
                    $aspek['nama_aspek'],
                    $aspek['skor_0'],
                    $aspek['skor_1'],
                    $aspek['skor_2'],
                    $aspek['deskripsi_0'],
                    $aspek['deskripsi_1'],
                    $aspek['deskripsi_2']
                ]);
            }
            
            $pdo->commit();
            $success = "Station berhasil diduplikasi!";
        } else {
            $error = "Station tidak ditemukan!";
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Gagal menduplikasi station: " . $e->getMessage();
    }
}

// Ambil data stations
$stmt = $pdo->query("SELECT * FROM stations ORDER BY id DESC");
$stations = $stmt->fetchAll();
?>

<?php // Quick fix untuk variabel header
if (!isset($ujian)) $ujian = null;
if (!isset($ujian_id)) $ujian_id = null;

include 'header.php'; ?>

<div class="content">
    <h2>KELOLA SOAL & STATIONS</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; ?>
    
    <!-- Form Tambah Station -->
    <div class="card">
        <h3>Tambah Station Baru</h3>
        <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" required>
            </div>
            
            <div class="form-group">
                <label for="deskripsi">Deskripsi/Skenario:</label>
                <div id="deskripsiEditor" class="rich-text-editor" data-target="deskripsi"></div>
                <textarea id="deskripsi" name="deskripsi" style="display: none;"></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"></div>
                <textarea id="instruksi_peserta" name="instruksi_peserta" style="display: none;"></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"></div>
                <textarea id="instruksi_penguji" name="instruksi_penguji" style="display: none;"></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">1</span>/<span id="maxAspekDisplay">20</span> Aspek
                    </div>
                </div>
                <div id="aspekContainer">

                    <!-- Aspek akan ditambahkan secara dinamis di sini -->
                </div>
                <button type="button" id="tambahAspek" class="btn btn-secondary">
                    <i class="fas fa-plus"></i> Tambah Aspek
                </button>
            </div>
            
            <button type="submit" name="tambah_station" class="btn btn-primary">Simpan Station</button>
        </form>
    </div>
    
    <!-- Daftar Stations -->
<div class="card">
    <h3>Daftar Stations</h3>
    <div class="table-container">
        <table class="data-table stations-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama Station</th>
                    <th>Jumlah Aspek</th>
                    <th>Nilai Maksimal</th>
                    <th>Tanggal Dibuat</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($stations)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center;">Belum ada station</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($stations as $index => $station): 
                        // Hitung jumlah aspek
                        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM aspek_penilaian WHERE station_id = ?");
                        $stmt->execute([$station['id']]);
                        $jumlah_aspek = $stmt->fetch()['total'];
                    ?>
                        <tr>
                            <td class="text-center"><?php echo $index + 1; ?></td>
                            <td>
                                <strong><?php echo $station['nama_station']; ?></strong>
                                <div class="station-preview">
                                    <?php echo substr(strip_tags($station['deskripsi']), 0, 100) . '...'; ?>
                                </div>
                            </td>
                            <td class="text-center"><?php echo $jumlah_aspek; ?> aspek</td>
                            <td class="text-center">
                                <div class="nilai-maksimal-container">
                                    <strong class="nilai-maksimal-display" style="color: #28a745; font-size: 1.1em;">
                                        <?php echo $station['total_maksimal']; ?>
                                    </strong>
                                    <button type="button" class="btn-edit-nilai" data-station-id="<?php echo $station['id']; ?>" data-current-value="<?php echo $station['total_maksimal']; ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </td>
                            <td class="text-center"><?php echo formatTanggal($station['created_at']); ?></td>
                            <td class="text-center">
                                <div class="action-buttons">
                                    <a href="edit_station.php?id=<?php echo $station['id']; ?>" class="btn btn-primary btn-sm">
                                        <i class="fas fa-edit"></i> Edit
                                    </a>
                                    <a href="?hapus_station=<?php echo $station['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menghapus station ini?')">
                                        <i class="fas fa-trash"></i> Hapus
                                    </a>
                                    <a href="?duplicate_station=<?php echo $station['id']; ?>" class="btn btn-info btn-sm" onclick="return confirm('Yakin ingin menduplikasi station ini?')">
                                        <i class="fas fa-copy"></i> Duplicate
                                    </a>
                                    <a href="detail_station.php?id=<?php echo $station['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-eye"></i> Preview
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Edit Nilai Maksimal -->
<div id="modalEditNilai" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Edit Nilai Maksimal</h4>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body">
            <form id="formEditNilai" method="POST">
                <input type="hidden" name="station_id" id="edit_station_id">
                <div class="form-group">
                    <label for="edit_total_maksimal">Nilai Maksimal:</label>
                    <input type="number" id="edit_total_maksimal" name="total_maksimal" min="0" max="100" required class="form-control">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" id="btnCancelEdit">Batal</button>
                    <button type="submit" name="edit_nilai_maksimal" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </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 with-image" data-target="aspek_nama[]"></div>
            <textarea name="aspek_nama[]" style="display: none;"></textarea>
        </div>
        
        <div class="skor-options">
            <label>Pilih Skor yang Tersedia:</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>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="../assets/js/soal.js"></script>

<style>
/* Style untuk tabel stations */
.stations-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.stations-table th {
    background: linear-gradient(135deg,  #4b92ddff 0%, #3039b8ff 100%);
    color: white;
    font-weight: 600;
    padding: 15px 12px;
    text-align: center;
    border: none;
    font-size: 14px;
}

.stations-table td {
    padding: 15px 12px;
    border-bottom: 1px solid #667eea;
    vertical-align: top;
}

.stations-table tr:hover {
    background-color: #d2e2f1ff;
}

.stations-table tr:last-child td {
    border-bottom: 2px solid #667eea;
}

/* Style untuk container nilai maksimal */
.nilai-maksimal-container {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.btn-edit-nilai {
    background: #ffc107;
    border: none;
    border-radius: 4px;
    padding: 6px 10px;
    cursor: pointer;
    color: #000;
    transition: all 0.3s;
    font-size: 12px;
}

.btn-edit-nilai:hover {
    background: #e0a800;
    transform: scale(1.1);
}

/* Style untuk modal */
.modal {
    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: #fefefe;
    margin: 10% auto;
    padding: 0;
    border-radius: 8px;
    width: 400px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
}

.modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 15px 20px;
    border-radius: 8px 8px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h4 {
    margin: 0;
    font-size: 18px;
}

.close {
    color: white;
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
}

.close:hover {
    color: #ffeb3b;
}

.modal-body {
    padding: 20px;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}

.form-control {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.form-control:focus {
    border-color: #667eea;
    outline: none;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* Style untuk action buttons */
.action-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    justify-content: center;
}

.text-center {
    text-align: center;
}

/* Responsive design */
@media (max-width: 768px) {
    .stations-table {
        font-size: 12px;
    }
    
    .stations-table th,
    .stations-table td {
        padding: 8px 6px;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .modal-content {
        width: 95%;
        margin: 5% auto;
    }
    
    .nilai-maksimal-container {
        flex-direction: column;
        gap: 5px;
    }
}

/* Style untuk font size controls */
.font-size-controls {
    display: flex;
    align-items: center;
    gap: 2px;
    margin-right: 5px;
    border-right: 1px solid #ccc;
    padding-right: 5px;
}

.font-size-select {
    padding: 4px 6px;
    border: 1px solid #ccc;
    border-radius: 3px;
    background: white;
    font-size: 12px;
    cursor: pointer;
}

.font-size-select:focus {
    outline: none;
    border-color: #667eea;
}

/* Untuk mini editor */
.mini-toolbar .font-size-controls {
    margin-right: 3px;
    padding-right: 3px;
}

.mini-toolbar .font-size-select {
    padding: 2px 4px;
    font-size: 11px;
    max-width: 60px;
}

/* Responsive design untuk font controls */
@media (max-width: 768px) {
    .font-size-controls {
        flex-wrap: wrap;
        gap: 1px;
    }
    
    .font-size-select {
        max-width: 50px;
        font-size: 10px;
    }
}
</style>

<script>
// Fungsi untuk menghitung total maksimal
function hitungTotalMaksimal() {
    let total = 0;
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    aspekItems.forEach(item => {
        const skor0 = item.querySelector('input[name="skor_0[]"]').checked;
        const skor1 = item.querySelector('input[name="skor_1[]"]').checked;
        const skor2 = item.querySelector('input[name="skor_2[]"]').checked;
        
        // Hitung skor maksimal untuk aspek ini
        if (skor2) total += 2;
        else if (skor1) total += 1;
        else if (skor0) total += 0;
    });
    
    return total;
}

// Fungsi untuk update tampilan total maksimal
function updateTotalMaksimalDisplay() {
    const total = hitungTotalMaksimal();
    const displayElement = document.getElementById('totalMaksimalDisplay');
    if (displayElement) {
        displayElement.textContent = total;
    }
}

// Event listener untuk perubahan checkbox skor
document.addEventListener('change', function(e) {
    if (e.target.name && (e.target.name === 'skor_0[]' || e.target.name === 'skor_1[]' || e.target.name === 'skor_2[]')) {
        updateTotalMaksimalDisplay();
    }
});

// Tambahkan elemen display total maksimal di form
document.addEventListener('DOMContentLoaded', function() {
    const formHeader = document.querySelector('.card h3');
    if (formHeader && !document.getElementById('totalMaksimalDisplay')) {
        const totalDisplay = document.createElement('div');
        totalDisplay.className = 'total-maksimal-display';
        totalDisplay.innerHTML = `
            <div style="background: #e8f5e8; padding: 10px; border-radius: 5px; margin: 10px 0; text-align: center;">
                <strong>Total Nilai Maksimal: </strong>
                <span id="totalMaksimalDisplay" style="color: #28a745; font-size: 1.2em; font-weight: bold;">0</span>
            </div>
        `;
        formHeader.parentNode.insertBefore(totalDisplay, formHeader.nextSibling);
        
        // Initial calculation
        updateTotalMaksimalDisplay();
    }
});

// Fungsi untuk modal edit nilai maksimal
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('modalEditNilai');
    const btnCancel = document.getElementById('btnCancelEdit');
    const closeBtn = document.querySelector('.close');
    const formEditNilai = document.getElementById('formEditNilai');
    
    // Event listener untuk tombol edit nilai
    document.querySelectorAll('.btn-edit-nilai').forEach(btn => {
        btn.addEventListener('click', function() {
            const stationId = this.getAttribute('data-station-id');
            const currentValue = this.getAttribute('data-current-value');
            
            document.getElementById('edit_station_id').value = stationId;
            document.getElementById('edit_total_maksimal').value = currentValue;
            
            modal.style.display = 'block';
        });
    });
    
    // Tutup modal
    function closeModal() {
        modal.style.display = 'none';
    }
    
    if (closeBtn) closeBtn.addEventListener('click', closeModal);
    if (btnCancel) btnCancel.addEventListener('click', closeModal);
    
    // Tutup modal ketika klik di luar
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            closeModal();
        }
    });
    
    // Handle form submission
    if (formEditNilai) {
        formEditNilai.addEventListener('submit', function(e) {
            // Validasi client-side
            const nilai = document.getElementById('edit_total_maksimal').value;
            if (nilai < 0 || nilai > 100) {
                e.preventDefault();
                alert('Nilai maksimal harus antara 0 dan 100');
                return false;
            }
            
            // Tutup modal setelah submit
            setTimeout(closeModal, 100);
        });
    }
});
</script>

<!-- Script debug lainnya tetap sama -->
<script>
// Debug function untuk memeriksa state aspek
function debugAspek() {
    const aspekItems = document.querySelectorAll('.aspek-item');
    console.log('Total aspek:', aspekItems.length);
    
    aspekItems.forEach((item, index) => {
        const namaTextarea = item.querySelector('textarea[name="aspek_nama[]"]');
        const editorContent = item.querySelector('.nama-aspek-editor .editor-content');
        
        console.log(`Aspek ${index + 1}:`, {
            textareaValue: namaTextarea ? namaTextarea.value : 'null',
            editorContent: editorContent ? editorContent.innerHTML : 'null',
            hasText: namaTextarea && namaTextarea.value.trim() !== ''
        });
    });
}

// Panggil debug saat form disubmit
document.getElementById('stationForm')?.addEventListener('submit', function(e) {
    console.log('=== DEBUG BEFORE SUBMIT ===');
    debugAspek();
});
</script>

<script>
// Debug script untuk memastikan semua komponen terload
document.addEventListener('DOMContentLoaded', function() {
    console.log('=== DEBUG SOAL.PHP ===');
    console.log('aspekContainer:', document.getElementById('aspekContainer'));
    console.log('aspekTemplate:', document.getElementById('aspekTemplate'));
    console.log('tambahAspek button:', document.getElementById('tambahAspek'));
    
    // Test manual tambah aspek
    window.debugTambahAspek = function() {
        const manager = new AspekManager();
        manager.tambahAspek();
    };
    
    // Force initialize jika diperlukan
    setTimeout(() => {
        if (document.querySelectorAll('.aspek-item').length === 0) {
            console.log('No aspek items found, forcing initialization...');
            const manager = new AspekManager();
        }
    }, 1000);
});

// Debug function untuk memeriksa state skor checkboxes
function debugSkorCheckboxes() {
    console.log('=== DEBUG SKOR CHECKBOXES ===');
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    aspekItems.forEach((item, index) => {
        const checkboxes = item.querySelectorAll('input[type="checkbox"][name^="skor_"]');
        const skorItems = item.querySelectorAll('.skor-item');
        
        console.log(`Aspek ${index + 1}:`);
        checkboxes.forEach((checkbox, cbIndex) => {
            const skorMatch = checkbox.name.match(/skor_(\d+)\[\]/);
            const skorValue = skorMatch ? skorMatch[1] : 'unknown';
            const skorItem = item.querySelector(`.skor-${skorValue}`);
            
            console.log(`  Skor ${skorValue}:`, {
                checked: checkbox.checked,
                skorItemExists: !!skorItem,
                skorItemDisplay: skorItem ? skorItem.style.display : 'N/A'
            });
        });
    });
    console.log('=== DEBUG END ===');
}

// Panggil debug setelah inisialisasi
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        debugSkorCheckboxes();
    }, 1000);
});
</script>

<!-- Style lainnya tetap sama -->
<style>
/* Style untuk tombol aksi */
.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    padding: 0.4rem 0.8rem;
    border: none;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.3s;
}

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

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

.btn-primary:hover {
    background: #2980b9;
    transform: translateY(-1px);
}

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

.btn-danger:hover {
    background: #c0392b;
    transform: translateY(-1px);
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
    transform: translateY(-1px);
}

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

.btn-secondary:hover {
    background: #545b62;
    transform: translateY(-1px);
}

/* Style untuk tabel aksi */
.data-table td:last-child {
    display: flex;
    gap: 0.3rem;
    flex-wrap: wrap;
}

.station-preview {
    font-size: 0.85rem;
    color: #6c757d;
    margin-top: 0.25rem;
    line-height: 1.3;
}

/* Responsive design untuk tombol aksi */
@media (max-width: 768px) {
    .data-table td:last-child {
        flex-direction: column;
    }
    
    .btn {
        width: 100%;
        justify-content: center;
    }
}

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

.mini-toolbar {
    background: #7ab2e6ff;
    padding: 5px;
    border-bottom: 1px solid #7ab2e6ff;
    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-toolbar .toolbar-btn:active {
    transform: translateY(0);
}

.mini-editor-content {
    min-height: 80px;
    padding: 12px;
    max-height: 200px;
    overflow-y: auto;
    line-height: 1.5;
}

/* Style untuk gambar dalam editor */
.mini-editor-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 5px 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Responsive design untuk toolbar */
@media (max-width: 768px) {
    .mini-toolbar {
        gap: 1px;
    }
    
    .mini-toolbar .toolbar-btn {
        padding: 3px 6px;
        font-size: 11px;
    }
}

/* Style untuk aspek item */
.aspek-item {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: #eeeeeeff; 
    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 #0d7ae8ff;
}

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

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

.skor-0-badge {
    background: #e74c3c;
    color: white;
}

.skor-1-badge {
    background: #f39c12;
    color: white;
}

.skor-2-badge {
    background: #27ae60;
    color: white;
}

.skor-description {
    margin-top: 20px;
}

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

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

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

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