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

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

$penguji_id = $_SESSION['user_id'];
$ujian_id = $_GET['ujian_id'] ?? null;
$station_id = $_GET['station_id'] ?? null;
$peserta_id = $_GET['peserta_id'] ?? null;

// Jika tidak ada ujian_id, redirect ke dashboard
if (!$ujian_id) {
    $stmt = $pdo->prepare("
        SELECT DISTINCT u.id 
        FROM ujian u 
        INNER JOIN ujian_stations us ON u.id = us.ujian_id 
        INNER JOIN penguji_station ps ON us.station_id = ps.station_id 
        WHERE u.status = 'aktif' AND ps.penguji_id = ? 
        ORDER BY u.tanggal_ujian DESC 
        LIMIT 1
    ");
    $stmt->execute([$penguji_id]);
    $ujian_aktif = $stmt->fetch();
    
    if ($ujian_aktif) {
        redirect("penilaian_detail.php?ujian_id=" . $ujian_aktif['id']);
    } else {
        $error = "Tidak ada ujian aktif yang tersedia untuk Anda.";
    }
}

// Ambil data ujian jika ujian_id ada
$ujian = null;
$stations = [];
$selected_peserta = null;
$selected_station = null;

if ($ujian_id) {
    $stmt = $pdo->prepare("
        SELECT u.* 
        FROM ujian u 
        INNER JOIN ujian_stations us ON u.id = us.ujian_id 
        INNER JOIN penguji_station ps ON us.station_id = ps.station_id 
        WHERE u.id = ? AND u.status = 'aktif' AND ps.penguji_id = ?
        LIMIT 1
    ");
    $stmt->execute([$ujian_id, $penguji_id]);
    $ujian = $stmt->fetch();

    if ($ujian) {
        // Ambil stations untuk ujian ini yang diassign ke penguji ini
        $stmt = $pdo->prepare("
            SELECT s.*, us.urutan 
            FROM stations s 
            INNER JOIN ujian_stations us ON s.id = us.station_id 
            INNER JOIN penguji_station ps ON s.id = ps.station_id 
            WHERE us.ujian_id = ? AND ps.penguji_id = ? 
            ORDER BY us.urutan
        ");
        $stmt->execute([$ujian_id, $penguji_id]);
        $stations = $stmt->fetchAll();

        // Jika ada peserta_id dari parameter, ambil data peserta
        if ($peserta_id) {
            $stmt = $pdo->prepare("SELECT * FROM peserta WHERE id = ?");
            $stmt->execute([$peserta_id]);
            $selected_peserta = $stmt->fetch();
        }

        // Jika ada station_id dari parameter, ambil data station
        if ($station_id) {
            $stmt = $pdo->prepare("SELECT * FROM stations WHERE id = ?");
            $stmt->execute([$station_id]);
            $selected_station = $stmt->fetch();
        }
    }
}

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

// Di bagian atas file, setelah mengambil data station
$stmt = $pdo->prepare("SELECT s.*, COUNT(ap.id) as jumlah_aspek 
                       FROM stations s 
                       LEFT JOIN aspek_penilaian ap ON s.id = ap.station_id 
                       WHERE s.id = ? 
                       GROUP BY s.id");
$stmt->execute([$station_id]);
$station = $stmt->fetch();

// ============================================
// [TAMBAHAN] SET STATUS MENJADI "mulai_penilaian"
// Kode ini akan berjalan saat halaman penilaian_detail.php diakses
// ============================================
if ($peserta_id && $station_id && $ujian_id) {
    $stmt = $pdo->prepare("
        UPDATE penilaian 
        SET status_penilaian = 'mulai_penilaian' 
        WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
        AND (status_penilaian IS NULL OR status_penilaian = 'belum_mulai')
    ");
    $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
    
    // Optional: Debug log
    error_log("Status penilaian diubah menjadi 'mulai_penilaian' untuk peserta_id: $peserta_id, station_id: $station_id");
}
// ============================================

// Proses form penilaian
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['simpan_penilaian'])) {
    $peserta_id = $_POST['peserta_id'];
    $station_id = $_POST['station_id'];
    
    // Validasi: Pastikan station yang dipilih benar-benar diassign ke penguji
    $stmt = $pdo->prepare("
        SELECT id FROM penguji_station 
        WHERE station_id = ? AND penguji_id = ?
    ");
    $stmt->execute([$station_id, $penguji_id]);
    
    if ($stmt->rowCount() == 0) {
        $error = "Station ini tidak diassign kepada Anda!";
    } else {
        if (empty($peserta_id) || empty($station_id)) {
            $error = "Pilih peserta dan station terlebih dahulu!";
        } else {
            // Ambil aspek penilaian untuk station ini
            $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ? ORDER BY nomor_urut");
            $stmt->execute([$station_id]);
            $aspeks = $stmt->fetchAll();
            
            $all_scored = true;
            $success_count = 0;
            
            foreach ($aspeks as $aspek) {
                $skor_field = 'skor_' . $aspek['id'];
                if (!isset($_POST[$skor_field]) || $_POST[$skor_field] === '') {
                    $all_scored = false;
                    break;
                }
            }
            
            if (!$all_scored) {
                $error = "Semua aspek penilaian harus diberi skor!";
            } else {
                // Simpan penilaian untuk setiap aspek
                foreach ($aspeks as $aspek) {
                    $skor_field = 'skor_' . $aspek['id'];
                    $skor = intval($_POST[$skor_field]);
                    $catatan = sanitize($_POST['catatan_' . $aspek['id']] ?? '');
                    
                    // Cek apakah sudah dinilai
                    $stmt = $pdo->prepare("
                        SELECT id FROM penilaian 
                        WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
                        AND penguji_id = ? AND aspek_id = ?
                    ");
                    $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $aspek['id']]);
                    
                    if ($stmt->rowCount() > 0) {
                        // Update existing
                        $stmt = $pdo->prepare("
                            UPDATE penilaian 
                            SET nilai = ?, catatan = ? 
                            WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
                            AND penguji_id = ? AND aspek_id = ?
                        ");
                        $result = $stmt->execute([$skor, $catatan, $ujian_id, $peserta_id, $station_id, $penguji_id, $aspek['id']]);
                    } else {
                        // Insert new
                        $stmt = $pdo->prepare("
                            INSERT INTO penilaian (ujian_id, peserta_id, station_id, penguji_id, aspek_id, nilai, catatan, status_penilaian) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, 'mulai_penilaian')
                        ");
                        $result = $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $aspek['id'], $skor, $catatan]);
                    }
                    
                    if ($result) {
                        $success_count++;
                    }
                }

                // ===================== SIMPAN CHECKLIST VERIFIKASI =====================
                if (isset($_POST['checklist_item']) && is_array($_POST['checklist_item'])) {
                    $checklist_success_count = 0;
                    
                    foreach ($_POST['checklist_item'] as $aspek_id => $items) {
                        if (is_array($items)) {
                            foreach ($items as $index => $item_text) {
                                $item_text = sanitize($item_text);
                                $status = $_POST['checklist_status'][$aspek_id][$index] ?? 'belum';
                                $catatan = $_POST['checklist_catatan'][$aspek_id][$index] ?? '';
                                
                                // Cek apakah sudah ada
                                $stmt = $pdo->prepare("
                                    SELECT id FROM checklist_verifikasi 
                                    WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
                                    AND penguji_id = ? AND aspek_id = ? AND checklist_item = ?
                                ");
                                $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $aspek_id, $item_text]);
                                
                                if ($stmt->rowCount() > 0) {
                                    // Update existing
                                    $stmt = $pdo->prepare("
                                        UPDATE checklist_verifikasi 
                                        SET status = ?, catatan = ?, updated_at = CURRENT_TIMESTAMP 
                                        WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
                                        AND penguji_id = ? AND aspek_id = ? AND checklist_item = ?
                                    ");
                                    $result = $stmt->execute([
                                        $status, $catatan, 
                                        $ujian_id, $peserta_id, $station_id, $penguji_id, $aspek_id, $item_text
                                    ]);
                                } else {
                                    // Insert new
                                    $stmt = $pdo->prepare("
                                        INSERT INTO checklist_verifikasi 
                                        (ujian_id, peserta_id, station_id, penguji_id, aspek_id, checklist_item, status, catatan) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                    ");
                                    $result = $stmt->execute([
                                        $ujian_id, $peserta_id, $station_id, $penguji_id, $aspek_id, 
                                        $item_text, $status, $catatan
                                    ]);
                                }
                                
                                if ($result) {
                                    $checklist_success_count++;
                                }
                            }
                        }
                    }
                    
                    if ($checklist_success_count > 0) {
                        $success .= " Checklist verifikasi berhasil disimpan.";
                    }
                }
                // ===================== END SIMPAN CHECKLIST =====================
                
                // Simpan global performance scale jika semua aspek sudah dinilai
                if ($success_count == count($aspeks)) {
                    // PERBAIKAN: Gunakan isset() dan !empty() untuk mengecek global_performance
                    if (isset($_POST['global_performance']) && !empty($_POST['global_performance'])) {
                        $global_performance = sanitize($_POST['global_performance']);
                        
                        // Debug: Cek nilai global_performance
                        error_log("Global Performance Value: " . $global_performance);
                        
                        // Cek apakah sudah ada penilaian global
                        $stmt = $pdo->prepare("
                            SELECT id FROM penilaian_global 
                            WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
                        ");
                        $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id]);
                        
                        if ($stmt->rowCount() > 0) {
                            // Update existing
                            $stmt = $pdo->prepare("
                                UPDATE penilaian_global 
                                SET global_performance = ?, updated_at = CURRENT_TIMESTAMP 
                                WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
                            ");
                            $global_result = $stmt->execute([$global_performance, $ujian_id, $peserta_id, $station_id, $penguji_id]);
                        } else {
                            // Insert new
                            $stmt = $pdo->prepare("
                                INSERT INTO penilaian_global (ujian_id, peserta_id, station_id, penguji_id, global_performance) 
                                VALUES (?, ?, ?, ?, ?)
                            ");
                            $global_result = $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $global_performance]);
                        }
                        
                        if ($global_result) {
                            $success = "Penilaian dan global performance berhasil disimpan!";
                        } else {
                            $success = "Penilaian berhasil disimpan! (Global performance gagal disimpan)";
                        }
                    } else {
                        // PERBAIKAN: Debug untuk melihat apa yang ada di $_POST
                        error_log("Global Performance POST data: " . print_r($_POST, true));
                        $success = "Penilaian berhasil disimpan! (Global performance belum dipilih)";
                    }
                    
                    // SIMPAN CATATAN UMUM
                    if (isset($_POST['catatan_umum'])) {
                        $catatan_umum = sanitize($_POST['catatan_umum']);
                        
                        // Cek apakah sudah ada catatan
                        $stmt = $pdo->prepare("
                            SELECT id FROM penilaian_catatan 
                            WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
                        ");
                        $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id]);
                        
                        if ($stmt->rowCount() > 0) {
                            // Update existing
                            $stmt = $pdo->prepare("
                                UPDATE penilaian_catatan 
                                SET catatan_umum = ?, updated_at = CURRENT_TIMESTAMP 
                                WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
                            ");
                            $catatan_result = $stmt->execute([$catatan_umum, $ujian_id, $peserta_id, $station_id, $penguji_id]);
                        } else {
                            // Insert new
                            $stmt = $pdo->prepare("
                                INSERT INTO penilaian_catatan (ujian_id, peserta_id, station_id, penguji_id, catatan_umum) 
                                VALUES (?, ?, ?, ?, ?)
                            ");
                            $catatan_result = $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $catatan_umum]);
                        }
                        
                        if ($catatan_result) {
                            $success .= " Catatan umum berhasil disimpan.";
                        } else {
                            $error = "Gagal menyimpan catatan umum.";
                        }
                    }
                    
                    // ============================================
                    // [TAMBAHAN] UPDATE STATUS MENJADI "selesai"
                    // Kode ini berjalan setelah semua penilaian berhasil disimpan
                    // ============================================
                    $stmt = $pdo->prepare("
                        UPDATE penilaian 
                        SET status_penilaian = 'selesai' 
                        WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
                    ");
                    $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
                    
                    // Optional: Debug log
                    error_log("Status penilaian diubah menjadi 'selesai' untuk peserta_id: $peserta_id, station_id: $station_id");
                    // ============================================
                    
                    $_POST = array();
                    
                    echo "<script>
                        setTimeout(function() {
                            window.location.href = 'daftar_peserta.php?ujian_id=' + $ujian_id + '&station_id=' + $station_id;
                        }, 2000);
                    </script>";
                }
            }
        }
    }
}


if ($selected_peserta && $selected_station) {
    // Query untuk mengambil data checklist
    $stmt_checklist = $pdo->prepare("
        SELECT 
            ap.id as aspek_id,
            ap.nama_aspek,
            ap.checklist_items,
            cv.id as checklist_id,
            cv.checklist_item,
            cv.status,
            cv.catatan
        FROM aspek_penilaian ap
        LEFT JOIN checklist_verifikasi cv ON ap.id = cv.aspek_id 
            AND cv.ujian_id = ? 
            AND cv.peserta_id = ? 
            AND cv.station_id = ?
            AND cv.penguji_id = ?
        WHERE ap.station_id = ?
        ORDER BY ap.nomor_urut
    ");
    $stmt_checklist->execute([
        $ujian_id, 
        $peserta_id, 
        $station_id, 
        $penguji_id,
        $station_id
    ]);
    $checklist_data = $stmt_checklist->fetchAll();
    
    // Group by aspek
    $checklist_by_aspek = [];
    foreach ($checklist_data as $item) {
        $aspek_id = $item['aspek_id'];
        if (!isset($checklist_by_aspek[$aspek_id])) {
            $checklist_by_aspek[$aspek_id] = [
                'nama_aspek' => $item['nama_aspek'],
                'checklist_items' => $item['checklist_items'],
                'items' => []
            ];
        }
        
        if ($item['checklist_item']) {
            $checklist_by_aspek[$aspek_id]['items'][] = [
                'item' => $item['checklist_item'],
                'status' => $item['status'],
                'catatan' => $item['catatan'],
                'checklist_id' => $item['checklist_id']
            ];
        }
    }
}

// Ambil data penguji dari database berdasarkan session
$stmt = $pdo->prepare("
    SELECT p.nama 
    FROM penguji p 
    WHERE p.id = ? OR p.nip IN (SELECT username FROM users WHERE id = ?)
");
$stmt->execute([$penguji_id, $penguji_id]);
$penguji_data = $stmt->fetch();

$nama_penguji = $penguji_data['nama'] ?? $_SESSION['user_name'];


?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Penilaian Detail -  OSCE</title>
    <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: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Header Styles */
        .main-header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 2.2rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 0.5rem;
        }
        
        .header-title .subtitle {
            color: #6c757d;
            font-size: 1.1rem;
        }
        
        .user-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 12px;
            text-align: center;
        }
        
        .user-info strong {
            display: block;
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .user-name {
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        /* Navigation */
        .nav-actions {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* Card Styles */
        .card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .card h3 {
            color: #2c3e50;
            margin-bottom: 1.5rem;
            font-size: 1.4rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .card h3 i {
            color: #667eea;
        }
        
        /* Ujian Tabs */
        .ujian-tabs {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1rem;
        }
        
        .ujian-tab {
            display: block;
            padding: 1.5rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            text-decoration: none;
            color: white;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .ujian-tab::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: 0.5s;
        }
        
        .ujian-tab:hover::before {
            left: 100%;
        }
        
        .ujian-tab:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.3);
        }
        
        .ujian-tab.active {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
        }
        
        .ujian-tab small {
            display: block;
            font-size: 0.85rem;
            opacity: 0.9;
            margin-top: 0.5rem;
        }
        
        /* Station Info */
        .station-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .station-info-card h3 {
            color: white;
        }
        
        .station-info-card h3 i {
            color: white;
        }
        
        .station-details {
            display: grid;
            gap: 1.5rem;
        }
        
        .info-section {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 1.5rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .info-section h4 {
            color: white;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 1.1rem;
        }
        
        .info-content {
            line-height: 1.7;
            color: rgba(255, 255, 255, 0.95);
        }
        
        /* Form Styles */
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .form-group select {
            width: 100%;
            padding: 1rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
            background: white;
        }
        
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
       /* PERBAIKAN: Aspek item styling */
.aspek-item {
    background: white;
    border: 2px solid #e9ecef;
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    transition: all 0.3s ease;
    border-left: 5px solid #667eea;
    position: relative;
    overflow: hidden;
}

.aspek-item.completed {
    border-color: #27ae60;
    background: linear-gradient(to right, #f8fff8, #ffffff);
}

.aspek-number {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
    margin-right: 1rem;
}

.aspek-nama {
    font-size: 1rem;
    color: #495057;
    line-height: 1.6;
    margin-top: 0.5rem;
    white-space: pre-line;
    word-wrap: break-word;
}
        
        /* Skor Options */
        .skor-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .skor-option {
            cursor: pointer;
        }
        
        .skor-option input[type="radio"] {
            display: none;
        }
        
        .skor-card {
            border: 3px solid #e9ecef;
            border-radius: 15px;
            padding: 1.5rem;
            transition: all 0.3s;
            text-align: center;
            background: white;
            height: 100%;
            display: flex;
            flex-direction: column;
            position: relative;
            overflow: hidden;
        }
        
        .skor-option input[type="radio"]:checked + .skor-card {
            border-color: #667eea;
            background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
            transform: scale(1.02);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
        }
        
        .skor-card:hover {
            border-color: #667eea;
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .skor-value {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 1rem;
        }
        
        .skor-0 .skor-value { color: #e74c3c; }
        .skor-1 .skor-value { color: #f39c12; }
        .skor-2 .skor-value { color: #27ae60; }
        
        .skor-description {
            font-size: 0.95rem;
            line-height: 1.5;
            color: #6c757d;
            flex: 1;
        }
        
       
        
        /* Submit Section */
        .submit-section {
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 3px solid #e9ecef;
            text-align: center;
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 2.5rem;
            font-size: 1.1rem;
            border-radius: 12px;
        }
        
        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }
        
        /* Peserta Info */
        .peserta-info-current {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 15px;
            margin-bottom: 1.5rem;
        }
        
        .info-row {
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            backdrop-filter: blur(10px);
        }
        
        .info-row:last-child {
            margin-bottom: 0;
        }
        
        .info-row strong {
            color: rgba(255, 255, 255, 0.9);
            min-width: 100px;
            display: inline-block;
        }
        
        /* Table Styles */
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
            border: 2px solid #e9ecef;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }
        
        .data-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        .data-table tr:hover {
            background: #f8f9fa;
        }
        
        .nilai-badge.nilai-total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: bold;
            font-size: 1rem;
            display: inline-block;
        }
        
        /* Alert Styles */
        .alert {
            padding: 1.25rem 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            border: 2px solid transparent;
        }
        
        .alert-success {
            background: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        
        .alert-error {
            background: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        
        .alert-info {
            background: #d1ecf1;
            border-color: #bee5eb;
            color: #0c5460;
        }
        
        .alert-warning {
            background: #fff3cd;
            border-color: #ffeaa7;
            color: #856404;
        }
        
        /* Loading Animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .header-title h1 {
                font-size: 1.8rem;
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .skor-options {
                grid-template-columns: 1fr;
            }
            
            .ujian-tabs {
                grid-template-columns: 1fr;
            }
            
            .submit-section {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
        select:disabled {
    background-color: #f8f9fa;
    color: #495057;
    opacity: 1;
    cursor: not-allowed;
}

/* Indikator Progres Penilaian */
.progress-indicator {
    margin: 2rem 0;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 15px;
    border: 2px solid #e9ecef;
}

.progress-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.progress-numbers {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    justify-content: center;
}

.progress-number {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 3px solid transparent;
}

.progress-number.unscored {
    background: #6c757d;
    color: white;
}

.progress-number.scored {
    background: #28a745;
    color: white;
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.progress-number.current {
    border-color: #007bff;
    transform: scale(1.1);
}

.progress-number:hover {
    transform: scale(1.05);
}

/* Global Performance Scale */
.global-scale {
    margin: 2rem 0;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 15px;
    border: 2px solid #e9ecef;
    display: none;
}

.global-scale.show {
    display: block;
    animation: fadeIn 0.5s ease;
}

.global-scale-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.scale-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
    margin-top: 1rem;
}

.scale-option {
    cursor: pointer;
}

.scale-option input[type="radio"] {
    display: none;
}

.scale-card {
    border: 3px solid #e9ecef;
    border-radius: 15px;
    padding: 1.5rem;
    transition: all 0.3s;
    text-align: center;
    background: white;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.scale-option input[type="radio"]:checked + .scale-card {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
    transform: scale(1.02);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.scale-card:hover {
    border-color: #667eea;
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.scale-value {
    font-size: 1.3rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
}

.scale-tidak-lulus .scale-value { color: #e74c3c; }
.scale-borderline .scale-value { color: #f39c12; }
.scale-lulus .scale-value { color: #27ae60; }

.scale-description {
    font-size: 0.9rem;
    line-height: 1.4;
    color: #6c757d;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* PERBAIKAN: Responsive design */
@media (max-width: 992px) {
    .skor-options {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .scale-options {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .skor-options {
        grid-template-columns: 1fr;
    }
    
    .scale-options {
        grid-template-columns: 1fr;
    }
    
    .aspek-item {
        padding: 1.5rem;
    }
    
    .skor-card {
        min-height: 180px;
        padding: 1.2rem;
    }
}

/* Style untuk Aspek Penilaian dengan Garis Pemisah */
.aspek-item {
    background: white;
    border: 2px solid #667eea;
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
    border-left: 5px solid #667eea;
    position: relative;
}

.aspek-divider {
    height: 2px;
    background: linear-gradient(90deg, transparent, #667eea, transparent);
    margin: 1.5rem 0;
    border: none;
}

.aspek-header {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 2px solid #f8f9fa;
    position: relative;
}

.aspek-number {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.1rem;
    flex-shrink: 0;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

/* Skor Options dengan Garis */
.skor-options {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 1.5rem;
    margin-bottom: 1.5rem;
    position: relative;
}

.skor-option {
    cursor: pointer;
    position: relative;
}

.skor-option::before {
    content: '';
    position: absolute;
    left: -0.75rem;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 80%;
    background: #e9ecef;
    border-radius: 2px;
    transition: all 0.3s ease;
}

.skor-option:first-child::before {
    display: none;
}

.skor-option:hover::before {
    background: #667eea;
}

.skor-card {
    border: 3px solid #e9ecef;
    border-radius: 15px;
    padding: 1.5rem;
    transition: all 0.3s;
    text-align: center;
    background: white;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
}

.skor-card::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: #e9ecef;
    transition: all 0.3s ease;
}

.skor-0 .skor-card::after { background: #e74c3c; }
.skor-1 .skor-card::after { background: #f39c12; }
.skor-2 .skor-card::after { background: #27ae60; }

.skor-option input[type="radio"]:checked + .skor-card::after {
    height: 6px;
}

.skor-option input[type="radio"]:checked + .skor-card {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
    transform: scale(1.02);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.skor-card:hover {
    border-color: #667eea;
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* Garis Pemisah antara Skor Options */
.skor-separator {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 1rem 0;
    position: relative;
}

.skor-separator::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    height: 1px;
    background: #e9ecef;
}

.skor-separator-text {
    background: white;
    padding: 0 1rem;
    color: #6c757d;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 1px;
    position: relative;
    z-index: 1;
}



/* PERBAIKAN: Progress indicator */
#progressIndicator {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 2px solid #667eea;
    border-radius: 15px;
    padding: 1.5rem;
    margin: 2rem 0;
    display: block;
    opacity: 1;
    transition: all 0.5s ease;
}

.progress-numbers {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    justify-content: center;
    margin-top: 1rem;
    padding: 1rem;
    background: white;
    border-radius: 10px;
    border: 1px solid #dee2e6;
}

.progress-number {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 3px solid transparent;
    position: relative;
}

.progress-number.unscored {
    background: #6c757d;
    color: white;
}

.progress-number.scored {
    background: #28a745;
    color: white;
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.progress-number.current {
    border-color: #007bff;
    transform: scale(1.1);
    animation: pulse 2s infinite;
}

/* Garis untuk Global Performance Scale */
.global-scale {
    margin: 2rem 0;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 15px;
    border: 2px solid #e9ecef;
    display: none;
    position: relative;
}

.global-scale::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 4px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 2px;
}

.scale-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
    margin-top: 1rem;
    position: relative;
}

.scale-option {
    cursor: pointer;
    position: relative;
}

.scale-option::before {
    content: '';
    position: absolute;
    left: -0.5rem;
    top: 50%;
    transform: translateY(-50%);
    width: 2px;
    height: 60%;
    background: #e9ecef;
    border-radius: 1px;
}

.scale-option:first-child::before {
    display: none;
}

.scale-card {
    border: 3px solid #e9ecef;
    border-radius: 15px;
    padding: 1.5rem;
    transition: all 0.3s;
    text-align: center;
    background: white;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
}

.scale-card::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 4px;
    border-radius: 0 0 12px 12px;
    transition: all 0.3s ease;
}

.scale-tidak-lulus .scale-card::after { background: #e74c3c; }
.scale-borderline .scale-card::after { background: #f39c12; }
.scale-lulus .scale-card::after { background: #27ae60; }

.scale-option input[type="radio"]:checked + .scale-card::after {
    height: 6px;
}

/* Responsive Design */
@media (max-width: 768px) {
    .skor-options {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    
    .skor-option::before {
        display: none;
    }
    
    .scale-options {
        grid-template-columns: 1fr;
    }
    
    .scale-option::before {
        display: none;
    }
    
    .progress-numbers::before {
        display: none;
    }
}

/* Badge untuk skor */
.skor-badge {
    margin-top: 0.5rem;
    padding: 0.3rem 0.8rem;
    border-radius: 15px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

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

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

.skor-2 .skor-badge {
    background: #27ae60;
    color: white;
}
/* Visual feedback untuk progress */
.progress-number.current {
    border-color: #007bff;
    transform: scale(1.1);
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.3);
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(0, 123, 255, 0.4);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(0, 123, 255, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(0, 123, 255, 0);
    }
}

/* Highlight untuk aspek yang sedang aktif */
.aspek-item:target {
    border-color: #007bff;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
    animation: highlight 2s ease-in-out;
}

@keyframes highlight {
    0% {
        background-color: #fff3cd;
    }
    100% {
        background-color: white;
    }
}

.total-maksimal-display {
    margin: 15px 0;
}

.total-maksimal-info {
    background: linear-gradient(135deg, #e8f5e8, #d4edda);
    border: 2px solid #28a745;
    padding: 15px;
    border-radius: 8px;
    margin: 15px 0;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.total-maksimal-info h4 {
    margin: 0;
    color: #155724;
    font-size: 1.2em;
}

/* Feedback Comments Styles */
.feedback-section {
    margin: 2rem 0;
}

.feedback-grid {
    border: 2px solid #e9ecef;
    border-radius: 10px;
    overflow: hidden;
}

.feedback-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
    border-bottom: 1px solid #e9ecef;
}

.feedback-row:last-child {
    border-bottom: none;
}

.feedback-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: bold;
}

.feedback-col {
    padding: 12px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e9ecef;
}

.feedback-col:last-child {
    border-right: none;
}

.feedback-item {
    justify-content: flex-start;
    font-weight: 600;
    color: #2c3e50;
}

.feedback-header .feedback-col {
    text-align: center;
    font-size: 0.9rem;
}

/* Checkbox dan Select Styling */
.feedback-col input[type="checkbox"] {
    width: 20px;
    height: 20px;
    cursor: pointer;
    accent-color: #667eea;
}

.feedback-col select {
    padding: 6px 10px;
    border: 1px solid #ced4da;
    border-radius: 5px;
    font-size: 0.9rem;
    width: 70px;
    text-align: center;
}

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

/* Responsive */
@media (max-width: 768px) {
    .feedback-row {
        grid-template-columns: 1fr;
        border-bottom: 2px solid #e9ecef;
        padding: 10px 0;
    }
    
    .feedback-col {
        border-right: none;
        border-bottom: 1px solid #e9ecef;
        padding: 8px 10px;
        justify-content: space-between;
    }
    
    .feedback-col:last-child {
        border-bottom: none;
    }
    
    .feedback-header {
        display: none;
    }
    
    .feedback-col::before {
        content: attr(data-label);
        font-weight: bold;
        color: #495057;
        min-width: 60px;
    }
}

/* Catatan Umum Styles */
.catatan-umum-section {
    margin: 2rem 0;
    background: white;
    border: 2px solid #667eea;
    box-shadow: 0 5px 20px rgba(102, 126, 234, 0.1);
}

.catatan-umum-section h3 {
    color: #2c3e50;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding-bottom: 1rem;
    border-bottom: 2px solid #f8f9fa;
}

.catatan-umum-section h3 i {
    color: #667eea;
}

.catatan-umum-content {
    padding: 0.5rem 0;
}

.catatan-umum-content .form-group {
    margin-bottom: 1rem;
}

.catatan-umum-content label {
    display: block;
    margin-bottom: 0.75rem;
    font-weight: 600;
    color: #495057;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 1rem;
}

.catatan-umum-content textarea {
    width: 100%;
    padding: 1rem;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    resize: vertical;
    font-family: inherit;
    min-height: 150px;
    font-size: 1rem;
    line-height: 1.6;
    transition: all 0.3s;
    background: #f8f9fa;
}

.catatan-umum-content textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    background: white;
}

.catatan-umum-content textarea:hover {
    border-color: #667eea;
    background: white;
}

.catatan-info {
    margin-top: 1rem;
    padding: 0.75rem 1rem;
    background: #f8f9fa;
    border-radius: 8px;
    color: #6c757d;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    border: 1px solid #e9ecef;
}

.catatan-info i {
    color: #667eea;
}

/* Highlight efek */
.catatan-umum-section.highlight {
    animation: highlightPulse 2s ease-in-out;
    border-color: #27ae60;
}

@keyframes highlightPulse {
    0% {
        box-shadow: 0 0 0 0 rgba(39, 174, 96, 0.4);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(39, 174, 96, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(39, 174, 96, 0);
    }
}

@media (max-width: 768px) {
    .catatan-umum-content textarea {
        min-height: 120px;
    }
    
    .catatan-umum-section {
        margin: 1.5rem 0;
    }
}

/* Di dalam style tag di penilaian_detail.php, tambahkan: */

/* Checklist Verifikasi Styles */
.checklist-verifikasi-box {
    background: #f8f9fa;
    border: 2px solid #dee2e6;
    border-radius: 10px;
    margin: 25px 0;
    padding: 20px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.08);
}

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

.checklist-header h5 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    gap: 8px;
}

.checklist-stats {
    background: #4dabf7;
    color: white;
    padding: 6px 15px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.9rem;
    min-width: 80px;
    text-align: center;
}

.checklist-items-list {
    max-height: 350px;
    overflow-y: auto;
    margin-bottom: 20px;
    padding-right: 10px;
}

.checklist-items-list::-webkit-scrollbar {
    width: 6px;
}

.checklist-items-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.checklist-items-list::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.checklist-items-list::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

.checklist-item-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    margin: 8px 0;
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    transition: all 0.2s;
}

.checklist-item-row:hover {
    border-color: #4dabf7;
    box-shadow: 0 2px 8px rgba(77, 171, 247, 0.15);
}

.checklist-item-info {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 200px;
}

.checklist-number {
    background: #4dabf7;
    color: white;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.85rem;
    font-weight: bold;
    flex-shrink: 0;
}

.checklist-text {
    font-size: 0.95rem;
    color: #495057;
    line-height: 1.4;
}

.checklist-actions {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
    min-width: 350px;
    justify-content: flex-end;
}

.checklist-status-select {
    padding: 8px 12px;
    border: 1px solid #ced4da;
    border-radius: 6px;
    background: white;
    font-size: 0.85rem;
    min-width: 160px;
    cursor: pointer;
    transition: all 0.2s;
    appearance: none;
    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 16px;
    padding-right: 35px;
}

.checklist-status-select:hover {
    border-color: #4dabf7;
    box-shadow: 0 0 0 2px rgba(77, 171, 247, 0.1);
}

.checklist-status-select:focus {
    outline: none;
    border-color: #4dabf7;
    box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.2);
}

.checklist-catatan-input {
    padding: 8px 12px;
    border: 1px solid #ced4da;
    border-radius: 6px;
    font-size: 0.85rem;
    min-width: 200px;
    transition: all 0.2s;
    flex: 1;
}

.checklist-catatan-input:focus {
    outline: none;
    border-color: #4dabf7;
    box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.2);
}

.checklist-summary {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin-top: 20px;
    padding: 20px;
    background: white;
    border-radius: 10px;
    border: 1px solid #dee2e6;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.summary-row {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 10px;
    border-radius: 8px;
    background: #f8f9fa;
}

.summary-label {
    font-size: 0.85rem;
    color: #6c757d;
    margin-bottom: 8px;
    font-weight: 500;
}

.summary-value {
    font-size: 1.4rem;
    font-weight: bold;
    font-family: 'Segoe UI', Arial, sans-serif;
}

.summary-value.total-items {
    color: #6c757d;
}

.summary-value.verified-items {
    color: #28a745;
}

.summary-value.percentage {
    color: #4dabf7;
    transition: color 0.3s;
}

/* Status colors */
.checklist-item-row.verified {
    background: #e7f6ec;
    border-color: #c3e6cb;
    border-left: 4px solid #28a745;
}

.checklist-item-row.not-verified {
    background: #fdf0f0;
    border-color: #f5c6cb;
    border-left: 4px solid #dc3545;
}

.checklist-item-row.partial {
    background: #fff9e6;
    border-color: #ffeaa7;
    border-left: 4px solid #ffc107;
}

/* Responsive Design */
@media (max-width: 992px) {
    .checklist-item-row {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }
    
    .checklist-item-info {
        min-width: auto;
    }
    
    .checklist-actions {
        min-width: auto;
        justify-content: flex-start;
        width: 100%;
    }
    
    .checklist-status-select,
    .checklist-catatan-input {
        min-width: 100%;
        width: 100%;
    }
}

@media (max-width: 768px) {
    .checklist-summary {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .checklist-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .checklist-stats {
        align-self: flex-start;
    }
    
    .checklist-verifikasi-box {
        padding: 15px;
    }
}

/* Animation for checklist update */
@keyframes highlightChecklist {
    0% { background-color: #fff3cd; }
    100% { background-color: white; }
}

.checklist-item-row.updated {
    animation: highlightChecklist 1s ease-in-out;
}

/* CSS untuk item verifikasi */
.item-verifikasi-container {
    background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
    border: 2px solid #667eea;
    border-radius: 12px;
    padding: 20px;
    margin: 20px 0;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}

.item-verifikasi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 12px;
    margin: 15px 0;
}

.item-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px;
    background: white;
    border-radius: 10px;
    border: 2px solid #dee2e6;
    transition: all 0.3s ease;
    cursor: pointer;
}

.item-checkbox:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    border-color: #667eea;
}

.item-checkbox input[type="checkbox"] {
    width: 20px;
    height: 20px;
    cursor: pointer;
    accent-color: #28a745;
}

.item-checkbox label {
    margin: 0;
    cursor: pointer;
    font-size: 0.95rem;
    color: #495057;
    flex: 1;
    line-height: 1.4;
}

.item-checkbox.checked {
    border-color: #28a745;
    background: #e8f5e8;
}

.item-checkbox.checked label {
    color: #155724;
}

.item-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #dee2e6;
}

.btn-select-all, .btn-unselect-all {
    padding: 8px 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.3s;
}

.btn-select-all {
    background: #28a745;
    color: white;
}

.btn-select-all:hover {
    background: #218838;
    transform: translateY(-2px);
}

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

.btn-unselect-all:hover {
    background: #c0392b;
    transform: translateY(-2px);
}

.item-counter {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 5px 15px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.9rem;
}

/* Responsive design */
@media (max-width: 768px) {
    .item-verifikasi-grid {
        grid-template-columns: 1fr;
    }
    
    .item-actions {
        flex-direction: column;
    }
}

.save-indicator {
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 10px;
    background: #f8f9fa;
    animation: fadeInOut 0.3s ease;
}

@keyframes fadeInOut {
    from { opacity: 0; transform: translateX(-5px); }
    to { opacity: 1; transform: translateX(0); }
}
    </style>
</head>
<body>
    <div class="container">
        <!-- Main Header -->
        <div class="main-header">
            <div class="header-content">
                <div class="header-title">
                    <h1><i class="fas fa-clipboard-check"></i> Penilaian Detail OSCE</h1>
                    <div class="subtitle">Sistem Penilaian OSCE</div>
                </div>
                <div class="user-info">
    <strong>Anda login sebagai:</strong>
    <div class="penguji-nama"><?php echo htmlspecialchars($nama_penguji); ?></div>
</div>
            </div>
        </div>

        <!-- Navigation -->
        <div class="nav-actions">
            <?php if ($station_id): ?>
                <a href="daftar_peserta.php?ujian_id=<?php echo $ujian_id; ?>&station_id=<?php echo $station_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Kembali ke Daftar Peserta
                </a>
            <?php else: ?>
                <a href="dashboard_penguji.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
                </a>
            <?php endif; ?>
        </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-error">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <!-- Pilih Ujian -->
        <div class="card">
            <h3><i class="fas fa-file-alt"></i> NAMA UJIAN</h3>
            <?php
            $stmt = $pdo->prepare("
                SELECT DISTINCT u.* 
                FROM ujian u 
                INNER JOIN ujian_stations us ON u.id = us.ujian_id 
                INNER JOIN penguji_station ps ON us.station_id = ps.station_id 
                WHERE u.status = 'aktif' AND ps.penguji_id = ? 
                ORDER BY u.tanggal_ujian DESC
            ");
            $stmt->execute([$penguji_id]);
            $semua_ujian = $stmt->fetchAll();
            ?>
            
            <?php if (empty($semua_ujian)): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    Tidak ada ujian aktif yang diassign kepada Anda.
                </div>
            <?php else: ?>
                <div class="ujian-tabs">
                    <?php foreach ($semua_ujian as $ujian_item): ?>
                        <a href="penilaian_detail.php?ujian_id=<?php echo $ujian_item['id']; ?>" 
                           class="ujian-tab <?php echo $ujian_id == $ujian_item['id'] ? 'active' : ''; ?>">
                            <strong><?php echo $ujian_item['nama_ujian']; ?></strong>
                            <small><i class="fas fa-calendar"></i> <?php echo formatTanggal($ujian_item['tanggal_ujian']); ?></small>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($ujian && !empty($stations)): ?>
            <!-- Informasi Station -->
            <div class="card station-info-card" id="stationInfo" style="display: none;">
                <h3><i class="fas fa-info-circle"></i> Informasi Station</h3>
                <div class="station-details">
                    <div class="info-section">
                        <h4><i class="fas fa-scroll"></i> Deskripsi/Skenario</h4>
                        <div class="info-content" id="stationDeskripsi"></div>
                    </div>
                    
                    <div class="info-section">
                        <h4><i class="fas fa-user-graduate"></i> Instruksi untuk Peserta</h4>
                        <div class="info-content" id="stationInstruksiPeserta"></div>
                    </div>
                    
                    <div class="info-section">
                        <h4><i class="fas fa-chalkboard-teacher"></i> Instruksi untuk Penguji</h4>
                        <div class="info-content" id="stationInstruksiPenguji"></div>
                    </div>
                </div>
            </div>

            <!-- Info Peserta yang Sedang Dinilai 
            <?php if ($selected_peserta): ?>
            <div class="card">
                <h3><i class="fas fa-user"></i> Informasi Peserta</h3>
                <div class="peserta-info-current">
                    <div class="info-row">
                        <strong>NIM:</strong> <?php echo $selected_peserta['nim']; ?>
                    </div>
                    <div class="info-row">
                        <strong>Nama:</strong> <?php echo $selected_peserta['nama']; ?>
                    </div>
                    <div class="info-row">
                        <strong>Station:</strong> <?php echo $selected_station ? $selected_station['nama_station'] : ''; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?> -->

            <!-- Form Penilaian -->
            <div class="card">
                <h3><i class="fas fa-edit"></i> Form Penilaian Detail - <?php echo $ujian['nama_ujian']; ?></h3>
                
                <form method="POST" id="penilaianForm">
                    <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
                    
                   <div class="form-row">
    <div class="form-group">
        <label for="peserta_id"><i class="fas fa-user-graduate"></i> Nama Peserta:</label>
        <select id="peserta_id" name="peserta_id" required disabled>
            <option value="">-- Pilih Peserta --</option>
            <?php
            if ($ujian_id) {
                $stmt = $pdo->prepare("
                    SELECT DISTINCT p.* 
                    FROM peserta p 
                    INNER JOIN peserta_station ps ON p.id = ps.peserta_id 
                    INNER JOIN penguji_station pgs ON ps.station_id = pgs.station_id 
                    WHERE pgs.penguji_id = ? AND ps.ujian_id = ? 
                    ORDER BY p.nama
                ");
                $stmt->execute([$penguji_id, $ujian_id]);
                $semua_peserta = $stmt->fetchAll();
                
                foreach ($semua_peserta as $peserta): ?>
                    <option value="<?php echo $peserta['id']; ?>" 
                        <?php 
                        if (isset($_POST['peserta_id']) && $_POST['peserta_id'] == $peserta['id']) {
                            echo 'selected';
                        } elseif ($peserta_id && $peserta['id'] == $peserta_id) {
                            echo 'selected';
                        }
                        ?>>
                        <?php echo $peserta['nim'] . ' - ' . $peserta['nama']; ?>
                    </option>
                <?php endforeach;
            } else {
                echo '<option value="">Pilih ujian terlebih dahulu</option>';
            }
            ?>
        </select>
        <!-- Tambahkan input hidden untuk mengirim nilai ketika disabled -->
        <input type="hidden" name="peserta_id" value="<?php echo $peserta_id ?? ''; ?>">
    </div>
    
    <div class="form-group">
        <label for="station_id"><i class="fas fa-clinic-medical"></i> Nama Station:</label>
        <select id="station_id" name="station_id" required disabled>
            <option value="">-- Pilih Station --</option>
            <?php 
            $auto_selected = false;
            foreach ($stations as $station): 
                $selected = '';
                if ($station_id && $station['id'] == $station_id) {
                    $selected = 'selected';
                    $auto_selected = true;
                } elseif (count($stations) === 1 && !$auto_selected) {
                    $selected = 'selected';
                    $auto_selected = true;
                } elseif (isset($_POST['station_id']) && $_POST['station_id'] == $station['id']) {
                    $selected = 'selected';
                }
            ?>
                <option value="<?php echo $station['id']; ?>" <?php echo $selected; ?>>
                    Station <?php echo $station['urutan']; ?>: <?php echo $station['nama_station']; ?>
                </option>
            <?php endforeach; ?>
        </select>
        <!-- Tambahkan input hidden untuk mengirim nilai ketika disabled -->
        <input type="hidden" name="station_id" value="<?php echo $station_id ?? ''; ?>">
    </div>
</div>

                    <!-- Aspek Penilaian akan dimuat via AJAX -->
                    <div id="aspekContainer">
                        <?php if ($peserta_id && $station_id): ?>
                            <div class="alert alert-info">
                                <div class="loading"></div>
                                Memuat aspek penilaian...
                            </div>
                            <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    loadAspekPenilaian();
                                    loadStationInfo();
                                });
                            </script>
                        <?php else: ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i>
                                Pilih peserta dan station terlebih dahulu untuk menampilkan aspek penilaian.
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Tambahkan sebelum bagian Submit Section -->

                    

<!-- Indikator Progres Penilaian -->
<div class="progress-indicator" id="progressIndicator" style="display: none;">
    <div class="progress-title">
        <i class="fas fa-tasks"></i> Progres Penilaian Aspek
    </div>
    <div class="progress-numbers" id="progressNumbers">
        <!-- Angka-angka akan diisi via JavaScript -->
    </div>
</div>

<!-- Catatan Umum -->
<div class="catatan-umum-section card" id="catatanUmum" style="display: none;">
    <h3><i class="fas fa-sticky-note"></i> Catatan Umum</h3>
    
    <div class="catatan-umum-content">
        <div class="form-group">
            <label for="catatan_umum">
                <i class="fas fa-comment-alt"></i> Masukkan catatan umum untuk peserta ini (opsional):
            </label>
            <textarea 
                id="catatan_umum" 
                name="catatan_umum" <!-- PASTIKAN ADA NAME INI -->
                
                <?php 
                // Ambil catatan umum yang sudah ada (jika ada)
                if ($peserta_id && $station_id && $ujian_id) {
    try {
        // Cek apakah sudah ada record penilaian untuk aspek pertama?
        $stmt = $pdo->prepare("
            SELECT id FROM penilaian 
            WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
            LIMIT 1
        ");
        $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
        
        if ($stmt->rowCount() == 0) {
            // Insert record awal jika belum ada
            $stmt = $pdo->prepare("
                INSERT INTO penilaian (ujian_id, station_id, peserta_id, penguji_id, status_penilaian, created_at)
                VALUES (?, ?, ?, ?, 'mulai_penilaian', NOW())
            ");
            $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
        } else {
            // Update status jika sudah ada
            $stmt = $pdo->prepare("
                UPDATE penilaian 
                SET status_penilaian = 'mulai_penilaian' 
                WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
                AND (status_penilaian IS NULL OR status_penilaian = 'belum_mulai')
            ");
            $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
        }
        
        error_log("Status penilaian diubah menjadi 'mulai_penilaian' untuk peserta_id: $peserta_id");
    } catch (PDOException $e) {
        error_log("Error update status: " . $e->getMessage());
    }
}

            ?></textarea>
        </div>
        
        <div class="catatan-info">
            <small><i class="fas fa-info-circle"></i> Catatan ini akan disimpan sebagai feedback tambahan untuk peserta.</small>
        </div>
    </div>
</div>

<!-- Global Performance Scale -->
<div class="global-scale" id="globalScale">
    <div class="global-scale-title">
        <i class="fas fa-chart-bar"></i> Global Performance Scale
    </div>
    <p>Pilih penilaian global berdasarkan performa keseluruhan peserta:</p>
    
    <div class="scale-options">
        <div class="scale-option">
            <input type="radio" id="scale_tidak_lulus" name="global_performance" value="tidak_lulus" required>
            <label for="scale_tidak_lulus" class="scale-card scale-tidak-lulus">
                <div class="scale-value">Tidak Lulus</div>
                <div class="scale-description">
                    Performa tidak memenuhi standar kompetensi minimum
                </div>
            </label>
        </div>
        
        <div class="scale-option">
            <input type="radio" id="scale_borderline" name="global_performance" value="borderline" required>
            <label for="scale_borderline" class="scale-card scale-borderline">
                <div class="scale-value">Borderline</div>
                <div class="scale-description">
                    Performa mendekati standar tetapi masih perlu perbaikan
                </div>
            </label>
        </div>
        
        <div class="scale-option">
            <input type="radio" id="scale_lulus" name="global_performance" value="lulus" required>
            <label for="scale_lulus" class="scale-card scale-lulus">
                <div class="scale-value">Lulus</div>
                <div class="scale-description">
                    Performa memenuhi atau melebihi standar kompetensi
                </div>
            </label>
        </div>
    </div>
</div>
                    
                    <div class="submit-section">
                        <button type="submit" name="simpan_penilaian" class="btn btn-primary">
                            <i class="fas fa-save"></i> Simpan Penilaian
                        </button>
                       
                    </div>
                </form>
            </div>

        <?php elseif ($ujian && empty($stations)): ?>
            <!-- Daftar Penilaian Terbaru 
            <div class="card">
                <h3><i class="fas fa-history"></i> Penilaian Terbaru Anda</h3>
                <?php
                $stmt = $pdo->prepare("
                    SELECT 
                        p.nama as peserta_nama,
                        p.nim,
                        s.nama_station,
                        SUM(n.nilai) as total_nilai,
                        MAX(n.created_at) as terakhir_dinilai
                    FROM penilaian n
                    INNER JOIN peserta p ON n.peserta_id = p.id
                    INNER JOIN stations s ON n.station_id = s.id
                    WHERE n.penguji_id = ? AND n.ujian_id = ?
                    GROUP BY p.id, p.nama, p.nim, s.nama_station
                    ORDER BY terakhir_dinilai DESC
                    LIMIT 10
                ");
                $stmt->execute([$penguji_id, $ujian_id]);
                $penilaian_terbaru = $stmt->fetchAll();
                ?>
                
                <?php if (empty($penilaian_terbaru)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Belum ada penilaian untuk ujian ini.
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Peserta</th>
                                    <th>Station</th>
                                    <th>Total Nilai</th>
                                    <th>Waktu</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($penilaian_terbaru as $nilai): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo $nilai['peserta_nama']; ?></strong>
                                            <br><small class="text-muted"><?php echo $nilai['nim']; ?></small>
                                        </td>
                                        <td><?php echo $nilai['nama_station']; ?></td>
                                        <td>
                                            <span class="nilai-badge nilai-total">
                                                <?php echo $nilai['total_nilai']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo formatTanggal($nilai['terakhir_dinilai']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        <?php elseif ($ujian && empty($stations)): ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i>
                Tidak ada stations untuk ujian ini.
            </div>
        <?php endif; ?>
    </div> -->

    <script src="smart_image.js"></script>
    
    <script>
        // Validasi form sebelum submit
document.getElementById('penilaianForm').addEventListener('submit', function(e) {
    const globalScale = document.getElementById('globalScale');
    const globalPerformanceRadios = document.querySelectorAll('input[name="global_performance"]');
    let globalPerformanceSelected = false;
    
    // Cek apakah global scale visible dan apakah sudah dipilih
    if (globalScale.classList.contains('show')) {
        globalPerformanceRadios.forEach(radio => {
            if (radio.checked) {
                globalPerformanceSelected = true;
            }
        });
        
        if (!globalPerformanceSelected) {
            e.preventDefault();
            alert('Silakan pilih Global Performance Scale sebelum menyimpan penilaian!');
            globalScale.scrollIntoView({ behavior: 'smooth', block: 'center' });
            
            // Highlight global scale
            globalScale.style.backgroundColor = '#fff3cd';
            setTimeout(() => {
                globalScale.style.backgroundColor = '';
            }, 3000);
        }
    }
});
    </script>

    <script>
        // Fungsi untuk memuat global performance yang sudah ada
function loadExistingGlobalPerformance() {
    const globalPerformanceRadios = document.querySelectorAll('input[name="global_performance"]');
    
    // Cek apakah sudah ada nilai global performance yang disimpan
    <?php
    if ($peserta_id && $station_id && $ujian_id) {
        $stmt = $pdo->prepare("
            SELECT global_performance FROM penilaian_global 
            WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
        ");
        $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id]);
        $existing_global = $stmt->fetch();
        
        if ($existing_global) {
            echo "const existingGlobal = '" . $existing_global['global_performance'] . "';";
            echo "
            globalPerformanceRadios.forEach(radio => {
                if (radio.value === existingGlobal) {
                    radio.checked = true;
                    // Trigger change event untuk update tampilan
                    radio.dispatchEvent(new Event('change'));
                }
            });
            ";
        }
    }
    ?>
}
        // Update fungsi updateProgressIndicator
function updateProgressIndicator() {
    const progressIndicator = document.getElementById('progressIndicator');
    const progressNumbers = document.getElementById('progressNumbers');
    const catatanUmum = document.getElementById('catatanUmum');
    const globalScale = document.getElementById('globalScale');
    
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    console.log('updateProgressIndicator dipanggil, aspekItems:', aspekItems.length); // Debug
    
    if (aspekItems.length === 0) {
        if (progressIndicator) progressIndicator.style.display = 'none';
        if (catatanUmum) catatanUmum.style.display = 'none';
        if (globalScale) globalScale.style.display = 'none';
        return;
    }
    
    // Tampilkan progress indicator
    if (progressIndicator) {
        progressIndicator.style.display = 'block';
    }
    
    // Buat progress numbers
    if (progressNumbers) {
        progressNumbers.innerHTML = '';
        
        let scoredCount = 0;
        
        aspekItems.forEach((aspek, index) => {
            const aspekNumber = index + 1;
            const radioButtons = aspek.querySelectorAll('input[type="radio"]');
            let isScored = false;
            
            // Cek apakah aspek sudah dinilai
            radioButtons.forEach(radio => {
                if (radio.checked) {
                    isScored = true;
                    scoredCount++;
                }
            });
            
            const progressNumber = document.createElement('div');
            progressNumber.className = `progress-number ${isScored ? 'scored' : 'unscored'}`;
            progressNumber.textContent = aspekNumber;
            progressNumber.title = `Aspek ${aspekNumber}: ${isScored ? 'Sudah dinilai' : 'Belum dinilai'}`;
            
            // Tambahkan klik untuk scroll ke aspek tersebut
            progressNumber.addEventListener('click', function() {
                aspek.scrollIntoView({ behavior: 'smooth', block: 'center' });
                aspek.style.backgroundColor = '#fff3cd';
                setTimeout(() => {
                    aspek.style.backgroundColor = '';
                }, 2000);
            });
            
            progressNumbers.appendChild(progressNumber);
        });
        
        // TAMPILKAN CATATAN UMUM LANGSUNG (tidak perlu menunggu semua aspek)
        if (catatanUmum) {
            catatanUmum.style.display = 'block';
            console.log('Catatan Umum ditampilkan'); // Debug
        }
        
        // Global scale hanya jika semua aspek sudah dinilai
        if (globalScale) {
            if (scoredCount === aspekItems.length && aspekItems.length > 0) {
                globalScale.style.display = 'block';
                globalScale.classList.add('show');
                console.log('Global scale ditampilkan karena semua aspek sudah dinilai'); // Debug
            } else {
                globalScale.style.display = 'none';
                globalScale.classList.remove('show');
                console.log('Global scale disembunyikan, scoredCount:', scoredCount, 'total:', aspekItems.length); // Debug
            }
        }
    }
}

// Fungsi untuk memuat progress dari penilaian yang sudah ada
function loadExistingProgress() {
    const scoredRadios = document.querySelectorAll('input[type="radio"]:checked');
    if (scoredRadios.length > 0) {
        updateProgressIndicator();
    }
}

// Panggil fungsi updateProgressIndicator ketika radio button berubah
document.addEventListener('change', function(e) {
    if (e.target.type === 'radio' && e.target.name.startsWith('skor_')) {
        updateProgressIndicator();
    }
});

// Panggil fungsi updateProgressIndicator ketika radio button berubah
document.addEventListener('change', function(e) {
    if (e.target.type === 'radio' && e.target.name.startsWith('skor_')) {
        updateProgressIndicator();
    }
});

// Inisialisasi: Tampilkan catatan umum segera setelah aspek dimuat
function initCatatanUmum() {
    const catatanUmum = document.getElementById('catatanUmum');
    const aspekItems = document.querySelectorAll('.aspek-item');
    
    if (aspekItems.length > 0 && catatanUmum) {
        catatanUmum.style.display = 'block';
        // Beri highlight agar penguji tahu catatan umum tersedia
        setTimeout(() => {
            catatanUmum.classList.add('highlight');
            setTimeout(() => {
                catatanUmum.classList.remove('highlight');
            }, 2000);
        }, 500);
    }
}

// Override fungsi loadAspekPenilaian untuk memanggil initCatatanUmum
const originalLoadAspekPenilaian = loadAspekPenilaian;
window.loadAspekPenilaian = function() {
    originalLoadAspekPenilaian();
    setTimeout(initCatatanUmum, 500);
};

// Modifikasi fungsi loadAspekPenilaian untuk menambahkan progress indicator
function loadAspekPenilaian() {
    const stationId = stationSelect.value;
    const pesertaId = pesertaSelect.value;
    
    if (!stationId || !pesertaId) {
        aspekContainer.innerHTML = `
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i>
                Pilih peserta dan station terlebih dahulu untuk menampilkan aspek penilaian.
            </div>
        `;
        document.getElementById('progressIndicator').style.display = 'none';
        document.getElementById('globalScale').classList.remove('show');
        return;
    }
    
    aspekContainer.innerHTML = `
        <div class="alert alert-info">
            <div class="loading"></div>
            Memuat aspek penilaian...
        </div>
    `;
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'get_aspek_penilaian.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            aspekContainer.innerHTML = xhr.responseText;
            
            const radioButtons = aspekContainer.querySelectorAll('input[type="radio"]');
            radioButtons.forEach(radio => {
                radio.addEventListener('change', function() {
                    const card = this.closest('.skor-option').querySelector('.skor-card');
                    document.querySelectorAll('.skor-card').forEach(c => c.classList.remove('active'));
                    card.classList.add('active');
                });
            });
            
            // Update progress indicator setelah aspek dimuat
            setTimeout(updateProgressIndicator, 100);
            setTimeout(loadExistingProgress, 200);
            setTimeout(loadExistingGlobalPerformance, 300);
            
        } else {
            aspekContainer.innerHTML = `
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    Gagal memuat aspek penilaian.
                </div>
            `;
            document.getElementById('progressIndicator').style.display = 'none';
            document.getElementById('globalScale').classList.remove('show');
        }
    };
    
    xhr.send('station_id=' + encodeURIComponent(stationId) + 
             '&peserta_id=' + encodeURIComponent(pesertaId) +
             '&ujian_id=' + encodeURIComponent(<?php echo $ujian_id ?? 'null'; ?>));
}
    </script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const stationSelect = document.getElementById('station_id');
        const pesertaSelect = document.getElementById('peserta_id');
        const aspekContainer = document.getElementById('aspekContainer');
        const stationInfo = document.getElementById('stationInfo');
        
        stationSelect.addEventListener('change', function() {
            loadStationInfo();
            loadAspekPenilaian();
        });
        
        pesertaSelect.addEventListener('change', loadAspekPenilaian);
        
        function loadStationInfo() {
            const stationId = stationSelect.value;
            
            if (!stationId) {
                stationInfo.style.display = 'none';
                return;
            }
            
            stationInfo.style.display = 'block';
            document.getElementById('stationDeskripsi').innerHTML = '<div class="loading"></div> Memuat...';
            document.getElementById('stationInstruksiPeserta').innerHTML = '<div class="loading"></div> Memuat...';
            document.getElementById('stationInstruksiPenguji').innerHTML = '<div class="loading"></div> Memuat...';
            
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'get_station_info.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        if (data.success) {
                            document.getElementById('stationDeskripsi').innerHTML = data.deskripsi || '<em>Tidak ada deskripsi</em>';
                            document.getElementById('stationInstruksiPeserta').innerHTML = data.instruksi_peserta || '<em>Tidak ada instruksi untuk peserta</em>';
                            document.getElementById('stationInstruksiPenguji').innerHTML = data.instruksi_penguji || '<em>Tidak ada instruksi untuk penguji</em>';
                        } else {
                            showError('Gagal memuat informasi station');
                        }
                    } catch (e) {
                        showError('Error parsing data station');
                    }
                } else {
                    showError('Gagal memuat informasi station');
                }
            };
            
            xhr.send('station_id=' + encodeURIComponent(stationId));
        }
        
        function loadAspekPenilaian() {
            const stationId = stationSelect.value;
            const pesertaId = pesertaSelect.value;
            
            if (!stationId || !pesertaId) {
                aspekContainer.innerHTML = `
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Pilih peserta dan station terlebih dahulu untuk menampilkan aspek penilaian.
                    </div>
                `;
                return;
            }
            
            aspekContainer.innerHTML = `
                <div class="alert alert-info">
                    <div class="loading"></div>
                    Memuat aspek penilaian...
                </div>
            `;
            
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'get_aspek_penilaian.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    aspekContainer.innerHTML = xhr.responseText;
                    
                    const radioButtons = aspekContainer.querySelectorAll('input[type="radio"]');
                    radioButtons.forEach(radio => {
                        radio.addEventListener('change', function() {
                            const card = this.closest('.skor-option').querySelector('.skor-card');
                            document.querySelectorAll('.skor-card').forEach(c => c.classList.remove('active'));
                            card.classList.add('active');
                        });
                    });
                } else {
                    aspekContainer.innerHTML = `
                        <div class="alert alert-error">
                            <i class="fas fa-exclamation-triangle"></i>
                            Gagal memuat aspek penilaian.
                        </div>
                    `;
                }
            };
            
            xhr.send('station_id=' + encodeURIComponent(stationId) + 
                     '&peserta_id=' + encodeURIComponent(pesertaId) +
                     '&ujian_id=' + encodeURIComponent(<?php echo $ujian_id ?? 'null'; ?>));
        }
        
        function showError(message) {
            stationInfo.style.display = 'none';
            aspekContainer.innerHTML = `
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    ${message}
                </div>
            `;
        }
        
        if (stationSelect.value) {
            loadStationInfo();
        }
        if (stationSelect.value && pesertaSelect.value) {
            loadAspekPenilaian();
        }
    });
    </script>
    <script>
        // Efek hover dan focus untuk skor options
document.addEventListener('DOMContentLoaded', function() {
    const skorOptions = document.querySelectorAll('.skor-option');
    
    skorOptions.forEach(option => {
        option.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(5px)';
        });
        
        option.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
        });
        
        // Highlight ketika dipilih
        const radio = option.querySelector('input[type="radio"]');
        radio.addEventListener('change', function() {
            // Reset semua border
            document.querySelectorAll('.skor-card').forEach(card => {
                card.style.borderColor = '#e9ecef';
            });
            
            // Set border untuk yang dipilih
            if (this.checked) {
                const card = this.closest('.skor-option').querySelector('.skor-card');
                card.style.borderColor = '#667eea';
                card.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.3)';
            }
        });
    });
    
    // Auto-focus ke textarea catatan ketika skor dipilih
    document.addEventListener('change', function(e) {
        if (e.target.type === 'radio' && e.target.name.startsWith('skor_')) {
            const aspekItem = e.target.closest('.aspek-item');
            const textarea = aspekItem.querySelector('textarea');
            if (textarea) {
                setTimeout(() => {
                    textarea.focus();
                }, 300);
            }
        }
    });
});
    </script>

    <script>
        class ChecklistVerifikasi {
    constructor() {
        this.init();
    }
    
    init() {
        // Event listener untuk perubahan status
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('checklist-status-select')) {
                this.updateChecklistStatus(e.target);
                this.updateChecklistSummary(e.target.closest('.checklist-verifikasi-box'));
            }
        });
        
        // Event listener untuk catatan
        document.addEventListener('input', (e) => {
            if (e.target.classList.contains('checklist-catatan-input')) {
                this.saveChecklistNote(e.target);
            }
        });
        
        // Initial update for all checklists
        document.querySelectorAll('.checklist-verifikasi-box').forEach(box => {
            this.updateChecklistSummary(box);
            this.colorCodeItems(box);
        });
    }
    
    updateChecklistStatus(select) {
        const row = select.closest('.checklist-item-row');
        const status = select.value;
        
        // Update row color based on status
        row.classList.remove('verified', 'not-verified', 'partial');
        
        switch(status) {
            case 'terverifikasi':
                row.classList.add('verified');
                break;
            case 'tidak_terverifikasi':
                row.classList.add('not-verified');
                break;
            case 'belum':
                row.classList.add('partial');
                break;
        }
        
        // Show/hide catatan input based on status
        const catatanInput = row.querySelector('.checklist-catatan-input');
        if (status === 'tidak_terverifikasi') {
            catatanInput.style.display = 'block';
            catatanInput.placeholder = 'Alasan tidak terverifikasi...';
        } else if (status === 'terverifikasi') {
            catatanInput.style.display = 'block';
            catatanInput.placeholder = 'Catatan tambahan...';
        } else {
            catatanInput.style.display = 'none';
        }
    }
    
    updateChecklistSummary(box) {
        const rows = box.querySelectorAll('.checklist-item-row');
        const totalItems = rows.length;
        let verifiedCount = 0;
        
        rows.forEach(row => {
            const select = row.querySelector('.checklist-status-select');
            if (select && select.value === 'terverifikasi') {
                verifiedCount++;
            }
        });
        
        const percentage = totalItems > 0 ? Math.round((verifiedCount / totalItems) * 100) : 0;
        
        // Update stats display
        const stats = box.querySelector('.checklist-stats');
        if (stats) {
            stats.innerHTML = `
                <span class="stat-verified">${verifiedCount}</span>/
                <span class="stat-total">${totalItems}</span> Terverifikasi
            `;
        }
        
        // Update summary
        box.querySelector('.total-items').textContent = totalItems;
        box.querySelector('.verified-items').textContent = verifiedCount;
        box.querySelector('.percentage').textContent = `${percentage}%`;
        
        // Update progress bar color
        const percentageElement = box.querySelector('.percentage');
        if (percentage >= 80) {
            percentageElement.style.color = '#28a745';
        } else if (percentage >= 50) {
            percentageElement.style.color = '#ffc107';
        } else {
            percentageElement.style.color = '#dc3545';
        }
    }
    
    colorCodeItems(box) {
        const rows = box.querySelectorAll('.checklist-item-row');
        rows.forEach(row => {
            const select = row.querySelector('.checklist-status-select');
            if (select) {
                this.updateChecklistStatus(select);
            }
        });
    }
    
    saveChecklistNote(input) {
        // You can implement auto-save to server here
        // For now, just save in localStorage
        const aspekId = input.dataset.aspekId;
        const item = input.dataset.item;
        const value = input.value;
        
        const key = `checklist_note_${aspekId}_${item}`;
        localStorage.setItem(key, value);
    }
    
    // Method untuk mengambil semua data checklist
    getAllChecklistData() {
        const data = {};
        
        document.querySelectorAll('.checklist-verifikasi-box').forEach(box => {
            const aspekId = box.closest('.aspek-item').id.replace('aspek-', '');
            data[aspekId] = [];
            
            box.querySelectorAll('.checklist-item-row').forEach(row => {
                const item = row.querySelector('.checklist-text').textContent;
                const status = row.querySelector('.checklist-status-select').value;
                const catatan = row.querySelector('.checklist-catatan-input').value;
                
                data[aspekId].push({
                    item: item,
                    status: status,
                    catatan: catatan
                });
            });
        });
        
        return data;
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelector('.checklist-verifikasi-box')) {
        window.checklistVerifikasi = new ChecklistVerifikasi();
    }
});
    </script>   

    <script>
        // Fungsi untuk mengelola item verifikasi
function initItemVerifikasi() {
    // Update counter
    function updateItemCounter(aspekId) {
        const checkboxes = document.querySelectorAll(`.verifikasi-item-checkbox[data-aspek-id="${aspekId}"]`);
        const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const counterElement = document.getElementById(`checked-count-${aspekId}`);
        if (counterElement) {
            counterElement.textContent = checkedCount;
            
            // Update visual feedback
            checkboxes.forEach(cb => {
                const itemDiv = cb.closest('.item-checkbox');
                if (cb.checked) {
                    itemDiv.style.borderColor = '#28a745';
                    itemDiv.style.background = '#e8f5e8';
                } else {
                    itemDiv.style.borderColor = '#dee2e6';
                    itemDiv.style.background = 'white';
                }
            });
        }
    }
    
    // Event listener untuk checkbox
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('verifikasi-item-checkbox')) {
            const aspekId = e.target.dataset.aspekId;
            updateItemCounter(aspekId);
            
            // Auto-update catatan textarea
            updateCatatanFromCheckboxes(aspekId);
        }
    });
    
    // Button untuk centang semua
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-select-all') || e.target.closest('.btn-select-all')) {
            const aspekId = e.target.dataset?.aspekId || e.target.closest('.btn-select-all').dataset.aspekId;
            const checkboxes = document.querySelectorAll(`.verifikasi-item-checkbox[data-aspek-id="${aspekId}"]`);
            checkboxes.forEach(cb => cb.checked = true);
            updateItemCounter(aspekId);
            updateCatatanFromCheckboxes(aspekId);
        }
        
        if (e.target.classList.contains('btn-unselect-all') || e.target.closest('.btn-unselect-all')) {
            const aspekId = e.target.dataset?.aspekId || e.target.closest('.btn-unselect-all').dataset.aspekId;
            const checkboxes = document.querySelectorAll(`.verifikasi-item-checkbox[data-aspek-id="${aspekId}"]`);
            checkboxes.forEach(cb => cb.checked = false);
            updateItemCounter(aspekId);
            updateCatatanFromCheckboxes(aspekId);
        }
    });
    
    // Fungsi untuk update catatan dari checkbox
    function updateCatatanFromCheckboxes(aspekId) {
        const catatanTextarea = document.getElementById(`catatan_${aspekId}`);
        if (!catatanTextarea) return;
        
        const checkboxes = document.querySelectorAll(`.verifikasi-item-checkbox[data-aspek-id="${aspekId}"]`);
        const checkedItems = [];
        const uncheckedItems = [];
        
        checkboxes.forEach(cb => {
            const item = cb.dataset.item;
            if (cb.checked) {
                checkedItems.push(item);
            } else {
                uncheckedItems.push(item);
            }
        });
        
        // Simpan dalam format khusus di awal catatan
        let currentCatatan = catatanTextarea.value;
        
        // Hapus item verifikasi dari catatan yang lama
        currentCatatan = currentCatatan.replace(/\[item_verifikasi\].*?\[\/item_verifikasi\]/s, '');
        
        // Bangun string item verifikasi
        let itemVerifikasiText = '';
        if (checkedItems.length > 0) {
            itemVerifikasiText += '\n\n[item_verifikasi]\n';
            itemVerifikasiText += '✓ Item yang sudah disebut/dilakukan:\n';
            checkedItems.forEach(item => {
                itemVerifikasiText += `- ${item}\n`;
            });
            
            if (uncheckedItems.length > 0) {
                itemVerifikasiText += '\n✗ Item yang belum disebut/dilakukan:\n';
                uncheckedItems.forEach(item => {
                    itemVerifikasiText += `- ${item}\n`;
                });
            }
            itemVerifikasiText += '[/item_verifikasi]\n\n';
        }
        
        // Gabungkan dengan catatan lainnya
        const userCatatan = currentCatatan.trim();
        if (userCatatan && !userCatatan.startsWith('[item_verifikasi]')) {
            catatanTextarea.value = itemVerifikasiText + userCatatan;
        } else {
            catatanTextarea.value = itemVerifikasiText;
        }
    }
    
    // Initial update untuk semua aspek yang memiliki item verifikasi
    document.querySelectorAll('.item-verifikasi-container').forEach(container => {
        const aspekId = container.querySelector('.verifikasi-item-checkbox')?.dataset.aspekId;
        if (aspekId) {
            updateItemCounter(aspekId);
        }
    });
}

// Panggil di DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
    initItemVerifikasi();
});
    </script>

<script>
    // Fungsi untuk menyimpan checklist verifikasi ke server// ===================== AUTO-SAVE CHECKLIST =====================
class ChecklistAutoSave {
    constructor() {
        this.saveQueue = new Map();
        this.saveTimeout = null;
        this.isSaving = false;
        this.init();
    }
    
    init() {
        // Event listener untuk perubahan status
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('checklist-status-select')) {
                this.queueSave(e.target);
            }
        });
        
        // Event listener untuk catatan (debounce)
        document.addEventListener('input', (e) => {
            if (e.target.classList.contains('checklist-catatan-input')) {
                this.debounceSave(e.target, 1000);
            }
        });
    }
    
    queueSave(element) {
        const row = element.closest('.checklist-item-row');
        if (!row) return;
        
        const aspekId = row.dataset.aspekId;
        const checklistItem = row.dataset.checklistItem;
        const status = element.value;
        const catatan = row.querySelector('.checklist-catatan-input')?.value || '';
        
        const key = `${aspekId}_${checklistItem}`;
        this.saveQueue.set(key, {
            aspek_id: aspekId,
            checklist_item: checklistItem,
            status: status,
            catatan: catatan
        });
        
        // Tampilkan indikator saving
        this.showSavingIndicator(row, 'menyimpan...');
        
        // Proses save setelah delay
        if (this.saveTimeout) clearTimeout(this.saveTimeout);
        this.saveTimeout = setTimeout(() => this.processSaveQueue(), 500);
    }
    
    debounceSave(element, delay) {
        if (element.debounceTimer) clearTimeout(element.debounceTimer);
        
        element.debounceTimer = setTimeout(() => {
            const row = element.closest('.checklist-item-row');
            if (!row) return;
            
            const aspekId = row.dataset.aspekId;
            const checklistItem = row.dataset.checklistItem;
            const status = row.querySelector('.checklist-status-select')?.value || 'belum';
            const catatan = element.value;
            
            const key = `${aspekId}_${checklistItem}`;
            this.saveQueue.set(key, {
                aspek_id: aspekId,
                checklist_item: checklistItem,
                status: status,
                catatan: catatan
            });
            
            this.showSavingIndicator(row, 'menyimpan...');
            
            if (this.saveTimeout) clearTimeout(this.saveTimeout);
            this.saveTimeout = setTimeout(() => this.processSaveQueue(), 500);
        }, delay);
    }
    
    async processSaveQueue() {
        if (this.isSaving) return;
        
        const queueItems = Array.from(this.saveQueue.entries());
        if (queueItems.length === 0) return;
        
        this.isSaving = true;
        
        for (const [key, data] of queueItems) {
            await this.saveToServer(data);
            this.saveQueue.delete(key);
        }
        
        this.isSaving = false;
    }
    
    async saveToServer(data) {
        const pesertaId = document.getElementById('peserta_id')?.value;
        const stationId = document.getElementById('station_id')?.value;
        const ujianId = <?php echo $ujian_id ?? 'null'; ?>;
        
        if (!pesertaId || !stationId || !ujianId) return;
        
        const formData = new URLSearchParams();
        formData.append('ujian_id', ujianId);
        formData.append('peserta_id', pesertaId);
        formData.append('station_id', stationId);
        formData.append('aspek_id', data.aspek_id);
        formData.append('checklist_item', data.checklist_item);
        formData.append('status', data.status);
        formData.append('catatan', data.catatan);
        
        try {
            const response = await fetch('auto_save_checklist.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: formData.toString()
            });
            
            const result = await response.json();
            
            // Update indikator
            const row = document.querySelector(`.checklist-item-row[data-checklist-item="${data.checklist_item}"]`);
            if (row) {
                if (result.success) {
                    this.showSavingIndicator(row, 'tersimpan', 'success');
                } else {
                    this.showSavingIndicator(row, 'gagal', 'error');
                }
            }
        } catch (error) {
            console.error('Auto-save error:', error);
            const row = document.querySelector(`.checklist-item-row[data-checklist-item="${data.checklist_item}"]`);
            if (row) {
                this.showSavingIndicator(row, 'offline - akan dicoba lagi', 'warning');
                // Re-queue untuk dicoba lagi
                setTimeout(() => this.saveToServer(data), 5000);
            }
        }
    }
    
    showSavingIndicator(row, message, type = 'info') {
        let indicator = row.querySelector('.save-indicator');
        if (!indicator) {
            indicator = document.createElement('span');
            indicator.className = 'save-indicator';
            indicator.style.marginLeft = '10px';
            indicator.style.fontSize = '0.75rem';
            const actionsDiv = row.querySelector('.checklist-actions');
            if (actionsDiv) {
                actionsDiv.appendChild(indicator);
            }
        }
        
        indicator.innerHTML = message;
        indicator.style.color = type === 'success' ? '#28a745' : (type === 'error' ? '#dc3545' : '#ffc107');
        
        if (type !== 'info') {
            setTimeout(() => {
                if (indicator && indicator.innerHTML === message) {
                    indicator.innerHTML = '';
                }
            }, 2000);
        }
    }
    
    // Load data yang sudah tersimpan saat halaman dimuat
    async loadSavedChecklists() {
        const pesertaId = document.getElementById('peserta_id')?.value;
        const stationId = document.getElementById('station_id')?.value;
        const ujianId = <?php echo $ujian_id ?? 'null'; ?>;
        
        if (!pesertaId || !stationId || !ujianId) return;
        
        try {
            const response = await fetch(`get_saved_checklists.php?ujian_id=${ujianId}&peserta_id=${pesertaId}&station_id=${stationId}`);
            const data = await response.json();
            
            if (data.success && data.checklists) {
                this.restoreChecklistData(data.checklists);
            }
        } catch (error) {
            console.error('Load saved checklists error:', error);
        }
    }
    
    restoreChecklistData(checklists) {
        checklists.forEach(item => {
            const row = document.querySelector(`.checklist-item-row[data-checklist-item="${item.checklist_item}"]`);
            if (row) {
                const statusSelect = row.querySelector('.checklist-status-select');
                const catatanInput = row.querySelector('.checklist-catatan-input');
                
                if (statusSelect && item.status) {
                    statusSelect.value = item.status;
                    this.updateRowColor(row, item.status);
                }
                if (catatanInput && item.catatan) {
                    catatanInput.value = item.catatan;
                }
            }
        });
    }
    
    updateRowColor(row, status) {
        row.classList.remove('verified', 'not-verified', 'partial');
        switch(status) {
            case 'terverifikasi':
                row.classList.add('verified');
                break;
            case 'tidak_terverifikasi':
                row.classList.add('not-verified');
                break;
            default:
                row.classList.add('partial');
        }
    }
}

// Inisialisasi auto-save setelah aspek dimuat
let checklistAutoSave;

function initChecklistAutoSave() {
    if (!checklistAutoSave) {
        checklistAutoSave = new ChecklistAutoSave();
    }
    // Load data yang sudah tersimpan
    setTimeout(() => {
        if (checklistAutoSave) {
            checklistAutoSave.loadSavedChecklists();
        }
    }, 500);
}

// Override loadAspekPenilaian untuk inisialisasi auto-save
const originalLoadAspek = window.loadAspekPenilaian || function() {};
window.loadAspekPenilaian = function() {
    originalLoadAspek();
    setTimeout(initChecklistAutoSave, 300);
};

// Panggil saat DOM ready
document.addEventListener('DOMContentLoaded', function() {
    initChecklistAutoSave();
});
    </script>

</body>
</html>