<?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();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Soal & Station | SOCA OSCE System</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #eef2f6 100%);
            min-height: 100vh;
        }
        .dashboard-wrapper { display: flex; min-height: 100vh; }
        .sidebar {
            width: 280px;
            background: linear-gradient(180deg, #1a1f2e 0%, #0f1119 100%);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 100;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.08);
        }
        .sidebar-header {
            padding: 1.8rem 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            text-align: center;
        }
        .logo-area {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin-bottom: 0.5rem;
        }
        .logo-icon {
            width: 45px;
            height: 45px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        .logo-text h3 {
            font-size: 1.2rem;
            font-weight: 700;
            letter-spacing: -0.3px;
            background: linear-gradient(135deg, #fff, #a78bfa);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }
        .logo-text p { font-size: 0.7rem; opacity: 0.7; margin-top: 2px; }
        .user-info-sidebar {
            padding: 1.2rem;
            background: rgba(255, 255, 255, 0.05);
            margin: 1rem;
            border-radius: 16px;
            text-align: center;
        }
        .user-avatar {
            width: 55px;
            height: 55px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-size: 1.5rem;
        }
        .nav-menu { padding: 1rem 0; }
        .nav-item {
            padding: 0.75rem 1.5rem;
            margin: 0.25rem 0.75rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            color: rgba(255, 255, 255, 0.7);
            transition: all 0.2s;
            text-decoration: none;
        }
        .nav-item:hover, .nav-item.active {
            background: rgba(102, 126, 234, 0.2);
            color: white;
        }
        .nav-item i { width: 24px; font-size: 1.1rem; }

        .main-content {
            flex: 1;
            margin-left: 280px;
            padding: 1.5rem 2rem 2rem;
        }
        .top-navbar {
            background: white;
            border-radius: 20px;
            padding: 1rem 1.8rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }
        .page-title h2 {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, #1e293b, #334155);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }
        .user-dropdown {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .user-name { font-weight: 600; color: #1e293b; }

        .card {
            background: white;
            border-radius: 24px;
            padding: 1.8rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 14px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 0, 0, 0.04);
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 0 1.2rem 0;
            border-bottom: 2px solid #f1f5f9;
            margin-bottom: 1.5rem;
        }
        .card-header h3 {
            font-size: 1.1rem;
            font-weight: 700;
            color: #0f172a;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .card-header h3 i { color: #667eea; }

        .alert {
            padding: 1rem 1.2rem;
            border-radius: 16px;
            margin-bottom: 1.5rem;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .alert-success { background: #d1fae5; color: #065f46; border-left: 4px solid #10b981; }
        .alert-danger { background: #fee2e2; color: #991b1b; border-left: 4px solid #ef4444; }
        .alert-warning { background: #fef3c7; color: #92400e; border-left: 4px solid #f59e0b; }
        .alert-info { background: #dbeafe; color: #1e40af; border-left: 4px solid #3b82f6; }

        .form-group { margin-bottom: 1.2rem; }
        .form-group label {
            display: block;
            font-weight: 600;
            color: #334155;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
        }
        .form-control, .form-select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 14px;
            font-size: 0.9rem;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s;
            background: #f8fafc;
        }
        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.2rem;
        }

        .btn {
            padding: 0.7rem 1.5rem;
            border-radius: 14px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            font-family: 'Inter', sans-serif;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }
        .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3); }
        .btn-success { background: #10b981; color: white; }
        .btn-success:hover { background: #059669; transform: translateY(-2px); }
        .btn-danger { background: #ef4444; color: white; }
        .btn-danger:hover:not(:disabled) { background: #dc2626; transform: translateY(-2px); }
        .btn-secondary { background: #f1f5f9; color: #475569; }
        .btn-secondary:hover { background: #e2e8f0; }
        .btn-sm { padding: 0.4rem 1rem; font-size: 0.75rem; }
        .btn-lg { padding: 0.9rem 2rem; font-size: 1rem; }

        .form-actions { display: flex; gap: 1rem; margin-top: 1.5rem; }

        /* Table Styles */
        .table-container {
            overflow-x: auto;
            border-radius: 16px;
            border: 1px solid #eef2ff;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }
        .data-table thead tr {
            background: linear-gradient(135deg, #1e293b, #0f172a);
            color: white;
        }
        .data-table th {
            padding: 0.9rem 0.8rem;
            text-align: center;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .data-table td {
            padding: 0.9rem 0.8rem;
            text-align: center;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
        }
        .data-table tbody tr:hover { background: #f8fafc; }
        .data-table tbody tr:last-child td { border-bottom: none; }

        .station-preview {
            font-size: 0.8rem;
            color: #64748b;
            margin-top: 0.3rem;
            line-height: 1.3;
        }

        .action-buttons {
            display: flex;
            gap: 0.4rem;
            flex-wrap: wrap;
            justify-content: center;
        }
        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
        }
        .btn-action span { display: none; }
        .btn-edit { background: #fef3c7; color: #92400e; border: 1px solid #fde68a; }
        .btn-edit:hover { background: #f59e0b; color: white; }
        .btn-manage { background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd; }
        .btn-manage:hover { background: #3b82f6; color: white; }
        .btn-delete { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }
        .btn-delete:hover { background: #ef4444; color: white; }
        .btn-duplicate { background: #f3e8ff; color: #6d28d9; border: 1px solid #d8b4fe; }
        .btn-duplicate:hover { background: #7c3aed; color: white; }
        .btn-preview { background: #e0f2fe; color: #0369a1; border: 1px solid #7dd3fc; }
        .btn-preview:hover { background: #0284c7; color: white; }

        .nilai-maksimal-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .nilai-maksimal-display {
            font-size: 1.1rem;
            font-weight: 700;
            color: #10b981;
        }
        .btn-edit-nilai {
            background: #fef3c7;
            border: none;
            border-radius: 8px;
            padding: 0.3rem 0.6rem;
            cursor: pointer;
            color: #92400e;
            transition: all 0.2s;
            font-size: 0.75rem;
        }
        .btn-edit-nilai:hover { background: #f59e0b; color: white; }

        /* Modal */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .modal-overlay.show { display: flex !important; }
        .modal-content-custom {
            background: white;
            border-radius: 28px;
            max-width: 450px;
            width: 90%;
            padding: 2rem;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease;
        }
        @keyframes modalSlideIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .sidebar { width: 250px; }
            .main-content { margin-left: 250px; }
        }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); position: fixed; }
            .main-content { margin-left: 0; padding: 1rem; }
            .top-navbar { flex-direction: column; gap: 0.5rem; text-align: center; }
            .form-row { grid-template-columns: 1fr; }
            .card-header { flex-direction: column; gap: 0.5rem; align-items: flex-start; }
            .btn-action span { display: inline; }
            .data-table { font-size: 0.75rem; }
            .data-table th, .data-table td { padding: 0.5rem 0.4rem; }
        }
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }

        .row-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 28px;
            height: 28px;
            background: #f1f5f9;
            border-radius: 50%;
            font-weight: 700;
            font-size: 0.8rem;
            color: #475569;
        }
        .total-maksimal-display {
            background: #d1fae5;
            padding: 0.8rem 1.2rem;
            border-radius: 14px;
            text-align: center;
            margin-bottom: 1.5rem;
            border: 2px solid #86efac;
        }
        .total-maksimal-display strong { color: #065f46; }
        .total-maksimal-display span {
            color: #10b981;
            font-size: 1.5rem;
            font-weight: 800;
        }

        .checkbox-group {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin: 0.5rem 0;
        }
        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            font-weight: 500;
        }
        .checkbox-label input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #667eea;
            cursor: pointer;
        }
        .skor-badge {
            display: inline-block;
            padding: 0.2rem 0.8rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
        }
        .skor-0-badge { background: #fee2e2; color: #991b1b; }
        .skor-1-badge { background: #fef3c7; color: #92400e; }
        .skor-2-badge { background: #d1fae5; color: #065f46; }

        .aspek-item {
            background: #f8fafc;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            padding: 1.5rem;
            margin-bottom: 1.2rem;
            transition: all 0.2s;
        }
        .aspek-item:hover { border-color: #c7d2fe; }
        .aspek-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.8rem;
            border-bottom: 2px solid #e2e8f0;
        }
        .aspek-header h5 {
            font-weight: 700;
            color: #0f172a;
            margin: 0;
        }
        .aspek-number {
            background: #667eea;
            color: white;
            padding: 0.2rem 0.8rem;
            border-radius: 30px;
            font-size: 0.8rem;
        }
        .aspek-actions {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e2e8f0;
            text-align: right;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            flex-wrap: wrap;
            gap: 0.5rem;
        }
        .section-header h4 {
            font-weight: 700;
            color: #0f172a;
            margin: 0;
        }
        .aspek-counter {
            font-size: 0.85rem;
            color: #64748b;
            font-weight: 500;
        }
        .aspek-counter span { font-weight: 700; color: #0f172a; }
    </style>
</head>
<body>
<div class="dashboard-wrapper">
    <!-- Sidebar -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo-area">
                <div class="logo-icon"><i class="fas fa-tooth"></i></div>
                <div class="logo-text"><h3>SOCA-OSCE</h3><p>Admin Center</p></div>
            </div>
        </div>
        <div class="user-info-sidebar">
            <div class="user-avatar"><i class="fas fa-user-cog"></i></div>
            <div style="font-weight: 600;"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Administrator'); ?></div>
            <div style="font-size: 0.7rem; opacity: 0.7;">Administrator</div>
        </div>
        <div class="nav-menu">
            <a href="dashboard.php" class="nav-item"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a href="soal.php" class="nav-item active"><i class="fas fa-question-circle"></i> <span>Kelola Soal</span></a>
            <a href="ujian.php" class="nav-item"><i class="fas fa-calendar-alt"></i> <span>Kelola Ujian</span></a>
            <a href="peserta.php" class="nav-item"><i class="fas fa-users"></i> <span>Kelola Peserta</span></a>
            <a href="penguji.php" class="nav-item"><i class="fas fa-chalkboard-user"></i> <span>Kelola Penguji</span></a>
            <a href="nilai.php" class="nav-item"><i class="fas fa-chart-line"></i> <span>Hasil Penilaian</span></a>
            <a href="../logout.php" class="nav-item" style="margin-top: 2rem;"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </div>
    </aside>

    <!-- Main Content -->
    <main class="main-content">
        <div class="top-navbar">
            <div class="page-title">
                <h2><i class="fas fa-question-circle" style="margin-right: 10px; color: #667eea;"></i>Kelola Soal & Station OSCE</h2>
            </div>
            <div class="user-dropdown">
                <span class="user-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Admin'); ?></span>
                <i class="fas fa-bell" style="color: #94a3b8;"></i>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?></div>
        <?php endif; ?>

        <!-- Form Tambah Station -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-plus-circle"></i> Tambah Station Baru</h3>
                <span class="badge" style="background: #10b981; color: white; padding: 0.3rem 1rem; border-radius: 30px; font-size: 0.7rem;">
                    <i class="fas fa-layer-group"></i> Maks. 40 Aspek
                </span>
            </div>
            <div class="card-body">
                <form method="POST" id="stationForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-tag"></i> Nama Station *</label>
                            <input type="text" class="form-control" id="nama_station" name="nama_station" required placeholder="Contoh: Station 1A - Anatomi">
                        </div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-align-left"></i> Deskripsi/Skenario</label>
                        <textarea class="form-control" id="deskripsi" name="deskripsi" rows="3" placeholder="Deskripsi skenario untuk station ini..."></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-user-graduate"></i> Instruksi untuk Peserta</label>
                            <textarea class="form-control" id="instruksi_peserta" name="instruksi_peserta" rows="3" placeholder="Instruksi yang diberikan kepada peserta..."></textarea>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-user-tie"></i> Instruksi untuk Penguji</label>
                            <textarea class="form-control" id="instruksi_penguji" name="instruksi_penguji" rows="3" placeholder="Instruksi yang diberikan kepada penguji..."></textarea>
                        </div>
                    </div>

                    <!-- Total Maksimal Display -->
                    <div class="total-maksimal-display">
                        <strong>Total Nilai Maksimal: </strong>
                        <span id="totalMaksimalDisplay">0</span>
                    </div>

                    <!-- Aspek Penilaian -->
                    <div class="aspek-penilaian-section">
                        <div class="section-header">
                            <h4><i class="fas fa-list-check" style="color: #667eea;"></i> Aspek yang Dinilai</h4>
                            <div class="aspek-counter">
                                <span id="aspekCountDisplay">0</span>/<span id="maxAspekDisplay">40</span> Aspek
                            </div>
                        </div>
                        <div id="aspekContainer">
                            <!-- Aspek akan ditambahkan secara dinamis -->
                        </div>
                        <button type="button" id="tambahAspek" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Tambah Aspek (40 tersedia)
                        </button>
                    </div>

                    <div class="form-actions">
                        <button type="submit" name="tambah_station" class="btn btn-success btn-lg">
                            <i class="fas fa-save"></i> Simpan Station
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Daftar Stations -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-layer-group"></i> Daftar Stations</h3>
                <span class="badge" style="background: #667eea; color: white; padding: 0.3rem 1rem; border-radius: 30px; font-size: 0.7rem;">
                    <i class="fas fa-database"></i> <?php echo count($stations); ?> Station
                </span>
            </div>
            <div class="card-body">
                <?php if (empty($stations)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Belum ada station. Klik "Tambah Station" untuk membuat station baru.
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Nama Station</th>
                                    <th>Aspek</th>
                                    <th>Nilai Maks</th>
                                    <th>Dibuat</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($stations as $index => $station): 
                                    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM aspek_penilaian WHERE station_id = ?");
                                    $stmt->execute([$station['id']]);
                                    $jumlah_aspek = $stmt->fetch()['total'];
                                ?>
                                    <tr>
                                        <td><span class="row-number"><?php echo $index + 1; ?></span></td>
                                        <td>
                                            <strong><?php echo htmlspecialchars($station['nama_station']); ?></strong>
                                            <div class="station-preview">
                                                <?php echo substr(strip_tags($station['deskripsi']), 0, 80) . (strlen(strip_tags($station['deskripsi'])) > 80 ? '...' : ''); ?>
                                            </div>
                                        </td>
                                        <td><?php echo $jumlah_aspek; ?> aspek</td>
                                        <td>
                                            <div class="nilai-maksimal-container">
                                                <span class="nilai-maksimal-display"><?php echo $station['total_maksimal']; ?></span>
                                                <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-pen"></i>
                                                </button>
                                            </div>
                                        </td>
                                        <td><?php echo date('d/m/Y', strtotime($station['created_at'])); ?></td>
                                        <td>
                                            <div class="action-buttons">
                                                <a href="edit_station.php?id=<?php echo $station['id']; ?>" class="btn-action btn-edit" title="Edit Station">
                                                    <i class="fas fa-pen"></i> <span>Edit</span>
                                                </a>
                                                <a href="?duplicate_station=<?php echo $station['id']; ?>" class="btn-action btn-duplicate" onclick="return confirm('Yakin ingin menduplikasi station ini?')" title="Duplicate Station">
                                                    <i class="fas fa-copy"></i> <span>Duplicate</span>
                                                </a>
                                                <a href="detail_station.php?id=<?php echo $station['id']; ?>" class="btn-action btn-preview" title="Preview Station">
                                                    <i class="fas fa-eye"></i> <span>Preview</span>
                                                </a>
                                                <a href="?hapus_station=<?php echo $station['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Yakin ingin menghapus station ini?')" title="Hapus Station">
                                                    <i class="fas fa-trash"></i> <span>Hapus</span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Modal Edit Nilai Maksimal -->
<div class="modal-overlay" id="modalEditNilai">
    <div class="modal-content-custom">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h4 style="font-weight: 700; color: #0f172a;"><i class="fas fa-edit" style="color: #f59e0b;"></i> Edit Nilai Maksimal</h4>
            <button type="button" class="btn btn-secondary btn-sm" onclick="closeModalEditNilai()"><i class="fas fa-times"></i></button>
        </div>
        <form id="formEditNilai" method="POST">
            <input type="hidden" name="station_id" id="edit_station_id">
            <div class="form-group">
                <label><i class="fas fa-hashtag"></i> Nilai Maksimal</label>
                <input type="number" class="form-control" id="edit_total_maksimal" name="total_maksimal" min="0" max="100" required>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeModalEditNilai()">Batal</button>
                <button type="submit" name="edit_nilai_maksimal" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
            </div>
        </form>
    </div>
</div>

<!-- Template Aspek -->
<script type="text/template" id="aspekTemplate">
    <div class="aspek-item">
        <div class="aspek-header">
            <h5><span class="aspek-number">Aspek #<span class="aspek-number-display">1</span></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-row">
            <div class="form-group">
                <label><i class="fas fa-sort-numeric"></i> Nomor Urut</label>
                <input type="number" class="form-control nomor-urut" name="nomor_urut[]" min="1" value="1" required>
            </div>
            <div class="form-group">
                <label><i class="fas fa-heading"></i> Nama Aspek</label>
                <input type="text" class="form-control" name="aspek_nama[]" required placeholder="Contoh: Anamnesis" value="">
            </div>
        </div>

        <div class="form-group">
            <label><i class="fas fa-check-square"></i> Item Verifikasi (Opsional)</label>
            <textarea class="form-control" name="item_verifikasi[]" rows="2" placeholder="Masukkan item-item untuk diverifikasi (satu item per baris)&#10;Contoh:&#10;1. Alat diagnostik&#10;2. Occlusal biterim&#10;3. Sliding caliper"></textarea>
            <small style="color: #64748b; font-size: 0.75rem;"><i class="fas fa-info-circle"></i> Item akan muncul sebagai checklist di halaman penilaian penguji</small>
        </div>

        <div class="form-group">
            <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>

        <div class="form-row">
            <div class="form-group">
                <label><span class="skor-badge skor-0-badge">Deskripsi Skor 0</span></label>
                <input type="text" class="form-control" name="deskripsi_0[]" placeholder="Deskripsi untuk skor 0">
            </div>
            <div class="form-group">
                <label><span class="skor-badge skor-1-badge">Deskripsi Skor 1</span></label>
                <input type="text" class="form-control" name="deskripsi_1[]" placeholder="Deskripsi untuk skor 1">
            </div>
            <div class="form-group">
                <label><span class="skor-badge skor-2-badge">Deskripsi Skor 2</span></label>
                <input type="text" class="form-control" name="deskripsi_2[]" placeholder="Deskripsi untuk skor 2">
            </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>

<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>
</body>
</html>