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

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

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$basePath = str_replace('/admin', '', dirname($_SERVER['PHP_SELF']));
$baseUrl = $protocol . '://' . $host . rtrim($basePath, '/');

// Untuk digunakan dalam JavaScript
echo "<script>const BASE_URL = '" . $baseUrl . "';</script>";

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


    } 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 (termasuk item_verifikasi)
            $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ?");
            $stmt->execute([$station_id]);
            $aspeks = $stmt->fetchAll();
            
            foreach ($aspeks as $aspek) {
                // PERBAIKAN: Tambahkan item_verifikasi ke query INSERT
                $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([
                    $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'],
                    $aspek['item_verifikasi']  // TAMBAHKAN INI
                ]);
            }
            
            $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>
    </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>

    <div class="item-verifikasi-section" style="margin-top: 20px; display: none;">
    <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 class="item-preview" style="margin-top: 10px; padding: 10px; background: #f8f9fa; border-radius: 5px; display: none;">
        <strong>Preview:</strong>
        <div class="preview-content" style="margin-top: 5px;"></div>
    </div>
</div>

<!-- Tambahkan checkbox untuk toggle item verifikasi -->
<div class="form-group" style="margin-top: 15px;">
    <label class="checkbox-label" style="display: flex; align-items: center; gap: 8px;">
        <input type="checkbox" class="toggle-item-verifikasi" name="enable_item_verifikasi[]">
        <span style="font-weight: 600; color: #3498db;">
            <i class="fas fa-check-square"></i> Tambahkan Item Verifikasi untuk Aspek ini
        </span>
    </label>
    <small style="color: #6c757d; display: block; margin-left: 28px;">
        Aktifkan untuk menambahkan daftar item yang perlu diverifikasi oleh penguji
    </small>
</div>
    
    <!-- SKOR PENILAIAN -->
    <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>
    </div>
    
    <!-- DESKRIPSI SKOR -->
    <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 untuk checklist dalam editor */
.checklist-container {
    margin: 10px 0;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 5px;
    border: 1px solid #e9ecef;
}

.checklist-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 8px;
    padding: 5px;
    background: white;
    border-radius: 3px;
}

.checklist-item input[type="checkbox"] {
    margin: 5px 10px 0 0;
    cursor: pointer;
    min-width: 16px;
    height: 16px;
}

.checklist-item label {
    flex: 1;
    margin: 0;
    cursor: text;
    padding: 3px 0;
    line-height: 1.4;
}

.checklist-item label[contenteditable="true"]:focus {
    background: #fffde7;
    outline: none;
    border-radius: 3px;
    padding: 2px 5px;
}

/* Style untuk preview checklist di halaman penguji */
.checklist-preview {
    margin: 15px 0;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #dee2e6;
}

.checklist-preview .checklist-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 10px;
    background: white;
    border-radius: 5px;
    border: 1px solid #e9ecef;
    transition: all 0.2s;
}

.checklist-preview .checklist-item:hover {
    background: #f8f9fa;
    border-color: #adb5bd;
}

.checklist-preview .checklist-item input[type="checkbox"] {
    margin-right: 12px;
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.checklist-preview .checklist-item label {
    flex: 1;
    margin: 0;
    font-size: 14px;
    line-height: 1.5;
    cursor: pointer;
}

.checklist-preview .checklist-item.checked {
    background: #d4edda;
    border-color: #c3e6cb;
}

.checklist-preview .checklist-item.checked label {
    color: #155724;
    text-decoration: line-through;
}

.checklist-preview .checklist-item.partial {
    background: #fff3cd;
    border-color: #ffeaa7;
}

.checklist-preview .checklist-item.partial label {
    color: #856404;
}

/* Tombol checklist di toolbar */
.toolbar-btn .fa-check-square,
.toolbar-btn .fa-check-circle {
    color: #28a745;
}

.toolbar-btn:hover .fa-check-square,
.toolbar-btn:hover .fa-check-circle {
    color: #218838;
}

/* Responsive design untuk checklist */
@media (max-width: 768px) {
    .checklist-preview .checklist-item {
        padding: 8px;
    }
    
    .checklist-preview .checklist-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        margin-right: 8px;
    }
}

/* Animasi untuk checklist */
@keyframes checklistCheck {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.checklist-preview .checklist-item input[type="checkbox"]:checked {
    animation: checklistCheck 0.3s ease;
}
</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>

<script>
// Fungsi untuk mengubah batas maksimal aspek dari 19 ke 40
document.addEventListener('DOMContentLoaded', function() {
    // Ganti teks maksimal aspek di UI
    const maxAspekDisplay = document.getElementById('maxAspekDisplay');
    if (maxAspekDisplay) {
        maxAspekDisplay.textContent = '40';
    }
    
    // Update teks tombol tambah aspek
    const tambahButton = document.getElementById('tambahAspek');
    if (tambahButton) {
        const updateTambahButtonText = () => {
            const currentCount = document.querySelectorAll('.aspek-item').length;
            const remaining = 40 - currentCount;
            if (remaining > 0) {
                tambahButton.innerHTML = `<i class="fas fa-plus"></i> Tambah Aspek (${remaining} tersedia)`;
                tambahButton.disabled = false;
                tambahButton.style.opacity = '1';
            } else {
                tambahButton.innerHTML = '<i class="fas fa-plus"></i> Maksimal Aspek Tercapai';
                tambahButton.disabled = true;
                tambahButton.style.opacity = '0.6';
            }
        };
        
        // Initial update
        updateTambahButtonText();
        
        // Update saat aspek berubah (gunakan MutationObserver untuk mendeteksi perubahan)
        const observer = new MutationObserver(updateTambahButtonText);
        const aspekContainer = document.getElementById('aspekContainer');
        if (aspekContainer) {
            observer.observe(aspekContainer, { childList: true, subtree: true });
        }
    }
    
    // Override fungsi AspekManager untuk mengubah batas maksimal
    if (window.aspekManager) {
        window.aspekManager.maxAspek = 40;
        
        // Override metode updateTambahButton
        const originalUpdateTambahButton = window.aspekManager.updateTambahButton;
        window.aspekManager.updateTambahButton = function() {
            const tambahButton = document.getElementById('tambahAspek');
            if (!tambahButton) return;
            
            const remaining = 40 - this.aspekCount;
            
            if (this.aspekCount >= 40) {
                tambahButton.disabled = true;
                tambahButton.innerHTML = '<i class="fas fa-plus"></i> Maksimal Aspek Tercapai';
                tambahButton.style.opacity = '0.6';
            } else {
                tambahButton.disabled = false;
                tambahButton.innerHTML = `<i class="fas fa-plus"></i> Tambah Aspek (${remaining} tersedia)`;
                tambahButton.style.opacity = '1';
            }
        };
        
        // Override metode tambahAspek untuk validasi baru
        const originalTambahAspek = window.aspekManager.tambahAspek;
        window.aspekManager.tambahAspek = function() {
            console.log('tambahAspek called, current count:', this.aspekCount);
            
            if (this.aspekCount >= 40) {
                alert(`Maksimal 40 aspek penilaian!`);
                return;
            }
            
            // Panggil fungsi original
            originalTambahAspek.call(this);
        };
    }
});

// Script untuk memodifikasi class AspekManager secara langsung
document.addEventListener('DOMContentLoaded', function() {
    // Tunggu hingga AspekManager selesai diinisialisasi
    setTimeout(() => {
        if (window.aspekManager) {
            // Ubah maxAspek menjadi 40
            window.aspekManager.maxAspek = 40;
            console.log('AspekManager maxAspek diubah menjadi:', window.aspekManager.maxAspek);
            
            // Update display counter
            const maxDisplay = document.getElementById('maxAspekDisplay');
            if (maxDisplay) {
                maxDisplay.textContent = '40';
            }
            
            // Update tombol tambah
            window.aspekManager.updateTambahButton();
        }
    }, 500);
});

// Backup: Modifikasi langsung pada class AspekManager
function patchAspekManager() {
    const originalAspekManager = window.AspekManager;
    
    if (originalAspekManager) {
        // Simpan constructor asli
        const OriginalConstructor = originalAspekManager;
        
        // Buat constructor baru dengan maxAspek = 40
        window.AspekManager = function() {
            // Panggil constructor asli
            const instance = new OriginalConstructor();
            
            // Modifikasi instance
            instance.maxAspek = 40;
            
            // Modifikasi metode tambahAspek
            const originalTambahAspek = instance.tambahAspek;
            instance.tambahAspek = function() {
                console.log('Patched tambahAspek called, current count:', this.aspekCount);
                
                if (this.aspekCount >= 40) {
                    alert(`Maksimal 40 aspek penilaian!`);
                    return;
                }
                
                return originalTambahAspek.call(this);
            };
            
            // Modifikasi metode duplikatAspek
            const originalDuplikatAspek = instance.duplikatAspek;
            instance.duplikatAspek = function(sourceElement) {
                if (this.aspekCount >= 40) {
                    alert(`Maksimal 40 aspek penilaian!`);
                    return;
                }
                
                return originalDuplikatAspek.call(this, sourceElement);
            };
            
            return instance;
        };
        
        // Copy prototype
        window.AspekManager.prototype = OriginalConstructor.prototype;
        
        console.log('AspekManager berhasil dipatch ke maksimal 40 aspek');
    }
}

// Eksekusi patch saat DOM siap
document.addEventListener('DOMContentLoaded', patchAspekManager);
</script>

<script>
// Fungsi untuk mengkonversi checklist HTML dari editor ke format interaktif
function convertChecklistForPenguji(htmlContent) {
    // Buat temporary element
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlContent;
    
    // Temukan semua checklist container
    const checklistContainers = tempDiv.querySelectorAll('.checklist-container');
    
    checklistContainers.forEach((container, containerIndex) => {
        // Ubah menjadi div checklist preview
        container.className = 'checklist-preview';
        
        // Ubah semua checklist item menjadi interaktif
        const checklistItems = container.querySelectorAll('.checklist-item');
        
        checklistItems.forEach((item, itemIndex) => {
            // Buat ID unik
            const uniqueId = `check_${containerIndex}_${itemIndex}_${Date.now()}`;
            
            // Dapatkan label text
            const labelElement = item.querySelector('label');
            const labelText = labelElement ? labelElement.textContent : `Item ${itemIndex + 1}`;
            
            // Replace dengan checkbox interaktif
            item.innerHTML = `
                <input type="checkbox" id="${uniqueId}" class="checklist-checkbox" 
                       data-aspek-id="" data-item-index="${itemIndex}">
                <label for="${uniqueId}">${labelText}</label>
            `;
            
            // Tambahkan class untuk styling
            item.classList.add('checklist-item-penguji');
        });
    });
    
    return tempDiv.innerHTML;
}

// Fungsi untuk menghitung skor berdasarkan checklist
function calculateChecklistScore(container) {
    const checkboxes = container.querySelectorAll('.checklist-checkbox');
    const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
    const totalCount = checkboxes.length;
    
    return {
        checked: checkedCount,
        total: totalCount,
        percentage: totalCount > 0 ? (checkedCount / totalCount) * 100 : 0
    };
}

// Fungsi untuk update nilai berdasarkan checklist
function updateScoreFromChecklist(aspekId, container) {
    const score = calculateChecklistScore(container);
    
    // Tentukan skor berdasarkan persentase
    let selectedScore = 0;
    
    if (score.percentage >= 90) {
        selectedScore = 2;
    } else if (score.percentage >= 60) {
        selectedScore = 1;
    } else {
        selectedScore = 0;
    }
    
    // Update radio button atau input skor
    const scoreInput = document.querySelector(`input[name="nilai[${aspekId}]"][value="${selectedScore}"]`);
    if (scoreInput) {
        scoreInput.checked = true;
        
        // Trigger change event
        scoreInput.dispatchEvent(new Event('change', { bubbles: true }));
    }
    
    return selectedScore;
}

// Event listener untuk checklist checkboxes
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('checklist-checkbox')) {
        const checklistItem = e.target.closest('.checklist-item');
        const container = e.target.closest('.checklist-preview');
        
        // Update class untuk styling
        if (e.target.checked) {
            checklistItem.classList.add('checked');
            checklistItem.classList.remove('partial');
        } else {
            checklistItem.classList.remove('checked');
            checklistItem.classList.remove('partial');
        }
        
        // Dapatkan aspek ID dari data attribute
        const aspekId = e.target.getAttribute('data-aspek-id');
        if (aspekId) {
            updateScoreFromChecklist(aspekId, container);
        }
    }
});

// Fungsi untuk menambahkan checklist secara otomatis ke skor
function autoScoreFromChecklist() {
    document.querySelectorAll('.checklist-preview').forEach((container, index) => {
        const checkboxes = container.querySelectorAll('.checklist-checkbox');
        const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const totalCount = checkboxes.length;
        
        // Tentukan class berdasarkan persentase
        if (checkedCount === totalCount) {
            container.classList.add('completed');
        } else if (checkedCount > 0) {
            container.classList.add('partial');
        } else {
            container.classList.add('not-started');
        }
        
        // Tampilkan statistik
        const statsDiv = document.createElement('div');
        statsDiv.className = 'checklist-stats';
        statsDiv.innerHTML = `
            <small class="text-muted">
                ${checkedCount}/${totalCount} checklist selesai 
                (${Math.round((checkedCount / totalCount) * 100)}%)
            </small>
        `;
        
        // Hapus stats lama jika ada
        const oldStats = container.querySelector('.checklist-stats');
        if (oldStats) oldStats.remove();
        
        container.appendChild(statsDiv);
    });
}

// Panggil fungsi ini di halaman penilaian penguji
function initializeChecklists() {
    // Konversi semua checklist di halaman
    document.querySelectorAll('.aspek-deskripsi, .instruksi-content').forEach(element => {
        const originalHTML = element.innerHTML;
        const convertedHTML = convertChecklistForPenguji(originalHTML);
        element.innerHTML = convertedHTML;
    });
    
    // Auto score setiap 2 detik
    setInterval(autoScoreFromChecklist, 2000);
    
    // Initial call
    autoScoreFromChecklist();
}

// Jika halaman sudah siap
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeChecklists);
} else {
    initializeChecklists();
}
</script>

<script>
// Checklist Helper System (Client-side only)
class ChecklistHelper {
    constructor() {
        this.storageKey = 'checklist_helper_data';
        this.init();
    }
    
    init() {
        this.loadSavedChecklist();
        this.setupEventListeners();
        this.setupAutoSave();
    }
    
    loadSavedChecklist() {
        const saved = localStorage.getItem(this.storageKey);
        if (saved) {
            try {
                const data = JSON.parse(saved);
                // Apply saved checkbox states
                Object.keys(data).forEach(aspekId => {
                    data[aspekId].forEach(itemIndex => {
                        const checkbox = document.querySelector(
                            `.checklist-checkbox-helper[data-aspek-id="${aspekId}"][data-item-index="${itemIndex}"]`
                        );
                        if (checkbox) {
                            checkbox.checked = true;
                            this.updateItemVisual(checkbox);
                        }
                    });
                });
                this.updateAllStats();
            } catch (e) {
                console.log('No saved checklist data');
            }
        }
    }
    
    setupEventListeners() {
        // Checkbox changes
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('checklist-checkbox-helper')) {
                this.updateItemVisual(e.target);
                this.saveToLocalStorage();
                this.updateStatsForAspek(e.target.dataset.aspekId);
            }
        });
        
        // Reset buttons
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('btn-reset-checklist')) {
                const aspekId = e.target.dataset.aspekId;
                this.resetChecklistForAspek(aspekId);
            }
        });
        
        // Reset all button
        document.getElementById('btn-reset-all-checklist')?.addEventListener('click', () => {
            if (confirm('Reset semua checklist? Data tidak bisa dikembalikan.')) {
                this.resetAllChecklists();
            }
        });
    }
    
    updateItemVisual(checkbox) {
        const item = checkbox.closest('.checklist-item-helper');
        if (checkbox.checked) {
            item.style.background = '#e7f3ff';
            item.style.borderColor = '#4dabf7';
        } else {
            item.style.background = 'white';
            item.style.borderColor = '#ced4da';
        }
    }
    
    updateStatsForAspek(aspekId) {
        const checkboxes = document.querySelectorAll(
            `.checklist-checkbox-helper[data-aspek-id="${aspekId}"]`
        );
        const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const totalCount = checkboxes.length;
        
        // Update stats display if exists
        const statsEl = document.getElementById(`stats-${aspekId}`);
        if (statsEl) {
            statsEl.innerHTML = `${checkedCount}/${totalCount}`;
        }
    }
    
    updateAllStats() {
        const aspekIds = new Set();
        document.querySelectorAll('.checklist-checkbox-helper').forEach(cb => {
            aspekIds.add(cb.dataset.aspekId);
        });
        
        aspekIds.forEach(aspekId => {
            this.updateStatsForAspek(aspekId);
        });
    }
    
    saveToLocalStorage() {
        const data = {};
        
        // Collect all checklist states
        document.querySelectorAll('.checklist-item-helper').forEach((item, index) => {
            const checkbox = item.querySelector('.checklist-checkbox-helper');
            if (checkbox) {
                const aspekId = checkbox.dataset.aspekId;
                if (!data[aspekId]) data[aspekId] = [];
                
                if (checkbox.checked) {
                    data[aspekId].push(index);
                }
            }
        });
        
        // Save to localStorage
        localStorage.setItem(this.storageKey, JSON.stringify(data));
    }
    
    resetChecklistForAspek(aspekId) {
        const checkboxes = document.querySelectorAll(
            `.checklist-checkbox-helper[data-aspek-id="${aspekId}"]`
        );
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            this.updateItemVisual(checkbox);
        });
        
        this.saveToLocalStorage();
        this.updateStatsForAspek(aspekId);
    }
    
    resetAllChecklists() {
        const checkboxes = document.querySelectorAll('.checklist-checkbox-helper');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            this.updateItemVisual(checkbox);
        });
        
        localStorage.removeItem(this.storageKey);
        this.updateAllStats();
        
        // Show notification
        this.showNotification('Semua checklist telah direset', 'info');
    }
    
    setupAutoSave() {
        // Auto-save every 10 seconds
        setInterval(() => {
            this.saveToLocalStorage();
        }, 10000);
        
        // Save before page unload
        window.addEventListener('beforeunload', () => {
            this.saveToLocalStorage();
        });
    }
    
    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'info' ? '#4dabf7' : '#fa5252'};
            color: white;
            padding: 12px 20px;
            border-radius: 6px;
            z-index: 9999;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            animation: slideIn 0.3s ease;
        `;
        
        notification.innerHTML = `
            <i class="fas fa-${type === 'info' ? 'info-circle' : 'exclamation-circle'}"></i>
            ${message}
        `;
        
        document.body.appendChild(notification);
        
        // Remove after 3 seconds
        setTimeout(() => {
            notification.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
        
        // Add CSS animations
        if (!document.getElementById('checklist-animations')) {
            const style = document.createElement('style');
            style.id = 'checklist-animations';
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOut {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
        }
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelector('.checklist-checkbox-helper')) {
        window.checklistHelper = new ChecklistHelper();
        
        // Add reset all button if not exists
        if (!document.getElementById('btn-reset-all-checklist')) {
            const resetBtn = document.createElement('button');
            resetBtn.id = 'btn-reset-all-checklist';
            resetBtn.innerHTML = '<i class="fas fa-broom"></i> Reset Semua Checklist';
            resetBtn.style.cssText = `
                position: fixed;
                bottom: 20px;
                right: 20px;
                background: #868e96;
                color: white;
                border: none;
                padding: 10px 15px;
                border-radius: 6px;
                cursor: pointer;
                z-index: 1000;
                font-size: 14px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            `;
            document.body.appendChild(resetBtn);
        }
        
        // Add stats panel
        const statsPanel = document.createElement('div');
        statsPanel.id = 'checklist-stats-panel';
        statsPanel.style.cssText = `
            position: fixed;
            bottom: 70px;
            right: 20px;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-width: 200px;
            max-height: 300px;
            overflow-y: auto;
        `;
        statsPanel.innerHTML = `
            <h6 style="margin-top: 0; color: #495057;">
                <i class="fas fa-chart-bar"></i> Checklist Progress
            </h6>
            <div id="checklist-stats-content"></div>
            <small style="color: #868e96; font-size: 11px; display: block; margin-top: 10px;">
                <i class="fas fa-info-circle"></i> Data tersimpan di browser Anda
            </small>
        `;
        document.body.appendChild(statsPanel);
        
        // Update stats every 5 seconds
        setInterval(() => {
            checklistHelper.updateStatsPanel();
        }, 5000);
        
        // Add method to update stats panel
        checklistHelper.updateStatsPanel = function() {
            const content = document.getElementById('checklist-stats-content');
            if (!content) return;
            
            const data = {};
            let totalChecked = 0;
            let totalItems = 0;
            
            // Collect stats
            document.querySelectorAll('.checklist-checkbox-helper').forEach(cb => {
                const aspekId = cb.dataset.aspekId;
                if (!data[aspekId]) {
                    data[aspekId] = { checked: 0, total: 0 };
                }
                data[aspekId].total++;
                if (cb.checked) data[aspekId].checked++;
            });
            
            // Build HTML
            let html = '';
            Object.keys(data).forEach(aspekId => {
                const aspekName = document.querySelector(`[data-aspek-id="${aspekId}"] h4`)?.textContent || `Aspek ${aspekId}`;
                const progress = data[aspekId].total > 0 ? 
                    Math.round((data[aspekId].checked / data[aspekId].total) * 100) : 0;
                
                html += `
                    <div style="margin-bottom: 10px;">
                        <div style="font-size: 12px; color: #495057; margin-bottom: 3px;">
                            ${aspekName.substring(0, 20)}...
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div style="flex: 1; background: #e9ecef; height: 6px; border-radius: 3px; overflow: hidden;">
                                <div style="width: ${progress}%; background: #4dabf7; height: 100%;"></div>
                            </div>
                            <span style="font-size: 11px; color: #868e96; min-width: 40px;">
                                ${data[aspekId].checked}/${data[aspekId].total}
                            </span>
                        </div>
                    </div>
                `;
                
                totalChecked += data[aspekId].checked;
                totalItems += data[aspekId].total;
            });
            
            // Add total
            const totalProgress = totalItems > 0 ? Math.round((totalChecked / totalItems) * 100) : 0;
            html += `
                <div style="margin-top: 15px; padding-top: 10px; border-top: 1px dashed #dee2e6;">
                    <div style="font-size: 13px; font-weight: bold; color: #495057; margin-bottom: 5px;">
                        Total Progress
                    </div>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="flex: 1; background: #e9ecef; height: 8px; border-radius: 4px; overflow: hidden;">
                            <div style="width: ${totalProgress}%; background: #40c057; height: 100%;"></div>
                        </div>
                        <span style="font-size: 12px; font-weight: bold; color: #40c057;">
                            ${totalProgress}%
                        </span>
                    </div>
                </div>
            `;
            
            content.innerHTML = html;
        };
        
        // Initial update
        checklistHelper.updateStatsPanel();
    }
});
</script>

<script>
    function saveChecklistHelperForStorage(itemsArray) {
    // Format HTML sederhana yang mudah diparsing
    const checklistHtml = `
        <div class="checklist-helper" data-type="penguji-helper">
            <ul>
                ${itemsArray.map(item => `<li>${item.trim()}</li>`).join('')}
            </ul>
        </div>
    `;
    return checklistHtml;
}
</script>

<!-- Style lainnya tetap sama -->
<style>

  /* Style untuk checklist helper di editor */
.checklist-helper {
    background: #f8f9fa;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
    position: relative;
}

.checklist-helper::before {
    content: "CHECKLIST HELPER";
    position: absolute;
    top: -10px;
    left: 10px;
    background: #4dabf7;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: bold;
}

.checklist-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ced4da;
}

.checklist-items {
    max-height: 200px;
    overflow-y: auto;
    padding: 5px;
}

.checklist-item-helper {
    display: flex;
    align-items: center;
    padding: 8px 10px;
    margin: 5px 0;
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    transition: all 0.2s;
}

.checklist-item-helper:hover {
    border-color: #4dabf7;
    background: #f8f9fa;
}

.checklist-item-helper input[type="checkbox"] {
    margin-right: 10px;
    width: 16px;
    height: 16px;
    cursor: pointer;
}

.checklist-item-helper label {
    flex: 1;
    margin: 0;
    font-size: 14px;
    cursor: pointer;
}

.checklist-note {
    margin-top: 10px;
    padding: 8px;
    background: #fff3cd;
    border-radius: 4px;
    border: 1px solid #ffeaa7;
}

/* Dropdown untuk checklist template */
.checklist-helper-dropdown {
    position: relative;
    display: inline-block;
}

.checklist-helper-menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    z-index: 1000;
    min-width: 180px;
    padding: 5px;
}

.checklist-template-btn {
    display: block;
    width: 100%;
    padding: 8px 12px;
    border: none;
    background: none;
    text-align: left;
    cursor: pointer;
    font-size: 13px;
    border-radius: 4px;
    color: #495057;
}

.checklist-template-btn:hover {
    background: #f8f9fa;
    color: #007bff;
}

.checklist-template-btn i {
    margin-right: 8px;
    width: 16px;
    text-align: center;
}

/* Style untuk tombol checklist di toolbar */
.toolbar-btn .fa-tasks {
    color: #4dabf7;
}

.toolbar-btn:hover .fa-tasks {
    color: #339af0;
}

/* Responsive design */
@media (max-width: 768px) {
    .checklist-helper {
        padding: 10px;
    }
    
    .checklist-item-helper {
        padding: 6px 8px;
        font-size: 13px;
    }
    
    .checklist-helper-menu {
        min-width: 150px;
    }
}

/* 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 untuk banyak aspek */
.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;
}

.aspek-penilaian-section::-webkit-scrollbar-thumb:hover {
    background: #764ba2;
}

/* Compact view untuk aspek banyak */
.aspek-item.compact {
    padding: 15px;
    margin-bottom: 10px;
}

.aspek-header.compact {
    padding-bottom: 10px;
    margin-bottom: 10px;
}

.compact .form-group {
    margin-bottom: 10px;
}

.compact .skor-item {
    padding: 10px;
    margin-bottom: 8px;
}

/* Tombol toggle compact view */
#toggleCompactView {
    margin-left: 10px;
    padding: 5px 10px;
    font-size: 12px;
    background: #6c757d;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#toggleCompactView:hover {
    background: #545b62;
}
</style>

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