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

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

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

// Jika tidak ada ujian_id, redirect ke dashboard
if (!$ujian_id) {
    // Ambil ujian aktif pertama sebagai default yang memiliki asignasi untuk penguji ini
    $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.php?ujian_id=" . $ujian_aktif['id']);
    } else {
        // Jika tidak ada ujian aktif dengan asignasi, tetap di halaman ini dengan pesan
        $error = "Tidak ada ujian aktif yang tersedia untuk Anda.";
    }
}

// Ambil data ujian jika ujian_id ada
$ujian = null;
$stations = [];
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();
    }
}

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

// 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 {
        // Validasi lainnya
        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) 
                            VALUES (?, ?, ?, ?, ?, ?, ?)
                        ");
                        $result = $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $aspek['id'], $skor, $catatan]);
                    }
                    
                    if ($result) {
                        $success_count++;
                    }
                }
                
                if ($success_count == count($aspeks)) {
                    $success = "Penilaian berhasil disimpan!";
                    // Clear form
                    $_POST = array();
                } else {
                    $error = "Gagal menyimpan beberapa penilaian!";
                }
            }
        }
    }
}
?>

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

<div class="content">
    <h2>Penilaian SOCA/OSCE</h2>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>

    <!-- Pilih Ujian -->
    <div class="card">
        <h3>Pilih 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.php?ujian_id=<?php echo $ujian_item['id']; ?>" 
                       class="ujian-tab <?php echo $ujian_id == $ujian_item['id'] ? 'active' : ''; ?>">
                        <?php echo $ujian_item['nama_ujian']; ?>
                        <small><?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>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>

        <!-- Form Penilaian -->
        <div class="card">
            <h3>Form Penilaian - <?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">Pilih Peserta:</label>
                        <select id="peserta_id" name="peserta_id" required>
                            <option value="">-- Pilih Peserta --</option>
                            <?php
                            // Hanya tampilkan peserta yang diassign ke station yang diassign ke penguji
                            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 echo isset($_POST['peserta_id']) && $_POST['peserta_id'] == $peserta['id'] ? 'selected' : ''; ?>>
                                        <?php echo $peserta['nim'] . ' - ' . $peserta['nama']; ?>
                                    </option>
                                <?php endforeach;
                            } else {
                                echo '<option value="">Pilih ujian terlebih dahulu</option>';
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="station_id">Pilih Station:</label>
                        <select id="station_id" name="station_id" required>
                            <option value="">-- Pilih Station --</option>
                            <?php 
                            $auto_selected = false;
                            foreach ($stations as $station): 
                                // Auto-select station pertama jika hanya ada 1 station
                                $selected = '';
                                if (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>
                    </div>
                </div>

                <!-- Aspek Penilaian akan dimuat via AJAX -->
                <div id="aspekContainer">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Pilih peserta dan station terlebih dahulu untuk menampilkan aspek penilaian.
                    </div>
                </div>
                
                <div class="submit-section">
                    <button type="submit" name="simpan_penilaian" class="btn btn-primary btn-lg">
                        <i class="fas fa-save"></i> Simpan Penilaian
                    </button>
                </div>
            </form>
        </div>

        <!-- Daftar Penilaian Terbaru -->
        <div class="card">
            <h3>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>

<style>
.ujian-tabs {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.ujian-tab {
    display: block;
    padding: 1rem;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    text-decoration: none;
    color: #495057;
    transition: all 0.3s;
    flex: 1;
    min-width: 200px;
}

.ujian-tab:hover {
    background: #e9ecef;
    border-color: #adb5bd;
}

.ujian-tab.active {
    background: #3498db;
    border-color: #3498db;
    color: white;
}

.ujian-tab small {
    display: block;
    font-size: 0.8rem;
    opacity: 0.8;
    margin-top: 0.25rem;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

/* Station Info Styles */
.station-info-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.station-info-card h3 {
    color: white;
    margin-bottom: 1.5rem;
}

.info-section {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    padding: 1.5rem;
    margin-bottom: 1rem;
    backdrop-filter: blur(10px);
}

.info-section h4 {
    color: white;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.info-content {
    line-height: 1.6;
    color: rgba(255, 255, 255, 0.9);
}

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

/* Aspek Penilaian Styles */
.aspek-container {
    margin-top: 2rem;
}

.aspek-item {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
    border-left: 4px solid #3498db;
}

.aspek-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

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

.aspek-number {
    background: #3498db;
    color: white;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1rem;
    flex-shrink: 0;
}

.aspek-title {
    flex: 1;
}

.aspek-title h4 {
    margin: 0 0 0.5rem 0;
    color: #2c3e50;
    font-size: 1.1rem;
}

.aspek-nama {
    font-size: 1rem;
    color: #495057;
    line-height: 1.5;
}

.aspek-nama img {
    max-width: 100%;
    height: auto;
    border-radius: 6px;
    margin: 0.5rem 0;
}

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

.skor-option {
    cursor: pointer;
}

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

.skor-card {
    border: 2px solid #dee2e6;
    border-radius: 8px;
    padding: 1.5rem;
    transition: all 0.3s;
    text-align: center;
    background: white;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.skor-option input[type="radio"]:checked + .skor-card {
    border-color: #3498db;
    background: #e8f4fd;
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

.skor-card:hover {
    border-color: #3498db;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.skor-value {
    font-size: 2rem;
    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.9rem;
    line-height: 1.5;
    color: #6c757d;
    flex: 1;
}

.skor-description img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 0.5rem 0;
}

/* Catatan Section */
.catatan-group {
    margin-top: 1.5rem;
    background: white;
    padding: 1.5rem;
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

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

.catatan-group textarea {
    width: 100%;
    padding: 1rem;
    border: 1px solid #ced4da;
    border-radius: 6px;
    resize: vertical;
    font-family: inherit;
    min-height: 100px;
    transition: border-color 0.3s;
}

.catatan-group textarea:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

/* Submit Section */
.submit-section {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 2px solid #e9ecef;
    text-align: center;
}

.submit-section .btn {
    padding: 1rem 2rem;
    font-size: 1.1rem;
    border-radius: 8px;
}

/* Nilai Badge */
.nilai-badge.nilai-total {
    background: #3498db;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-weight: bold;
    font-size: 1rem;
}

/* Responsive Design */
@media (max-width: 768px) {
    .ujian-tabs {
        flex-direction: column;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .skor-options {
        grid-template-columns: 1fr;
    }
    
    .aspek-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .aspek-number {
        align-self: flex-start;
    }
    
    .station-details {
        grid-template-columns: 1fr;
    }
}

/* Loading Animation */
.loading {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Alert Styles */
.alert {
    padding: 1rem 1.5rem;
    border-radius: 8px;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.alert-info {
    background: #d1ecf1;
    border: 1px solid #bee5eb;
    color: #0c5460;
}

.alert-warning {
    background: #fff3cd;
    border: 1px solid #ffeaa7;
    color: #856404;
}

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

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

/* Di style, tambahkan untuk memastikan gambar di aspek tampil */
.aspek-item img {
    max-width: 100% !important;
    height: auto !important;
    display: block !important;
    border: 2px solid #4CAF50;
    border-radius: 4px;
    margin: 5px 0;
}

/* Untuk preview di detail_station.php */
.aspek-preview-item img {
    max-width: 100% !important;
    height: auto !important;
    display: block !important;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin: 5px 0;
}
</style>

<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');
    
    // Load station info dan aspek penilaian ketika station dipilih
    stationSelect.addEventListener('change', function() {
        loadStationInfo();
        loadAspekPenilaian();
    });
    
    pesertaSelect.addEventListener('change', loadAspekPenilaian);
    
    function loadStationInfo() {
        const stationId = stationSelect.value;
        
        if (!stationId) {
            stationInfo.style.display = 'none';
            return;
        }
        
        // Show loading
        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...';
        
        // Load station info via AJAX
        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;
        }
        
        // Show loading
        aspekContainer.innerHTML = `
            <div class="alert alert-info">
                <div class="loading"></div>
                Memuat aspek penilaian...
            </div>
        `;
        
        // Load aspek via AJAX
        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;
                
                // Add event listeners to radio buttons for better UX
                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>
        `;
    }
    
    // Auto-load jika sudah ada pilihan dari form submission
    if (stationSelect.value) {
        loadStationInfo();
    }
    if (stationSelect.value && pesertaSelect.value) {
        loadAspekPenilaian();
    }
});
</script>

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