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

if (!isPenguji()) {
    die('Access denied');
}

$station_id = $_POST['station_id'] ?? null;
$peserta_id = $_POST['peserta_id'] ?? null;
$ujian_id = $_POST['ujian_id'] ?? null;

if (!$station_id || !$peserta_id) {
    die('Missing parameters');
}

// Ambil aspek penilaian untuk station ini
$stmt = $pdo->prepare("
    SELECT ap.* 
    FROM aspek_penilaian ap 
    WHERE ap.station_id = ? 
    ORDER BY ap.nomor_urut ASC
");
$stmt->execute([$station_id]);
$aspeks = $stmt->fetchAll();

if (empty($aspeks)) {
    echo '<div class="alert alert-warning">Tidak ada aspek penilaian untuk station ini.</div>';
    exit;
}

// Ambil penilaian yang sudah ada (jika ada)
$existing_nilai = [];
if ($ujian_id) {
    $stmt = $pdo->prepare("
        SELECT aspek_id, nilai, catatan 
        FROM penilaian 
        WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
    ");
    $stmt->execute([$ujian_id, $peserta_id, $station_id, $_SESSION['user_id']]);
    $existing_results = $stmt->fetchAll();
    
    foreach ($existing_results as $row) {
        $existing_nilai[$row['aspek_id']] = [
            'nilai' => $row['nilai'],
            'catatan' => $row['catatan']
        ];
    }
}

// Total maksimal
$stmt = $pdo->prepare("SELECT total_maksimal FROM stations WHERE id = ?");
$stmt->execute([$station_id]);
$station = $stmt->fetch();
$total_maksimal = $station['total_maksimal'] ?? 0;

echo '<div class="total-maksimal-info">';
echo '<h4><i class="fas fa-chart-line"></i> Total Nilai Maksimal Station: <span style="color: #28a745;">' . $total_maksimal . '</span></h4>';
echo '</div>';

foreach ($aspeks as $index => $aspek) {
    $existing = $existing_nilai[$aspek['id']] ?? null;
    
    // Bersihkan HTML dengan lebih agresif
    $nama_aspek = strip_tags(html_entity_decode($aspek['nama_aspek']));
    
    // Format ulang teks jika ada list
    if (strpos($nama_aspek, '1.') !== false || strpos($nama_aspek, '2.') !== false) {
        $nama_aspek = nl2br($nama_aspek);
    }
    
    // Bersihkan deskripsi skor
    $deskripsi_0 = strip_tags(html_entity_decode($aspek['deskripsi_0'] ?? ''));
    $deskripsi_1 = strip_tags(html_entity_decode($aspek['deskripsi_1'] ?? ''));
    $deskripsi_2 = strip_tags(html_entity_decode($aspek['deskripsi_2'] ?? ''));
    
    // Pastikan tidak ada teks kosong
    if (empty($deskripsi_0)) $deskripsi_0 = "Tidak memadai";
    if (empty($deskripsi_1)) $deskripsi_1 = "Cukup";
    if (empty($deskripsi_2)) $deskripsi_2 = "Baik";
    ?>
    <div class="aspek-item" id="aspek-<?php echo $aspek['id']; ?>" data-aspek-id="<?php echo $aspek['id']; ?>">
        <div class="aspek-header">
            <div class="aspek-number"><?php echo $aspek['nomor_urut']; ?></div>
            <div class="aspek-title">
                <h4>Aspek Penilaian <?php echo $aspek['nomor_urut']; ?></h4>
                <div class="aspek-nama"><?php echo htmlspecialchars($nama_aspek); ?></div>
            </div>
        </div>
        
        <div class="skor-options">
            <!-- SKOR 0 -->
            <?php if ($aspek['skor_0']): ?>
            <div class="skor-option skor-0">
                <input type="radio" 
                       id="skor_<?php echo $aspek['id']; ?>_0" 
                       name="skor_<?php echo $aspek['id']; ?>" 
                       value="0" 
                       <?php echo ($existing && $existing['nilai'] === '0') ? 'checked' : ''; ?>
                       class="skor-radio"
                       data-aspek-id="<?php echo $aspek['id']; ?>">
                <label for="skor_<?php echo $aspek['id']; ?>_0" class="skor-card">
                    <div class="skor-value">0</div>
                    <div class="skor-description"><?php echo htmlspecialchars($deskripsi_0); ?></div>
                </label>
            </div>
            <?php endif; ?>
            
            <!-- SKOR 1 -->
            <?php if ($aspek['skor_1']): ?>
            <div class="skor-option skor-1">
                <input type="radio" 
                       id="skor_<?php echo $aspek['id']; ?>_1" 
                       name="skor_<?php echo $aspek['id']; ?>" 
                       value="1" 
                       <?php echo ($existing && $existing['nilai'] === '1') ? 'checked' : ''; ?>
                       class="skor-radio"
                       data-aspek-id="<?php echo $aspek['id']; ?>">
                <label for="skor_<?php echo $aspek['id']; ?>_1" class="skor-card">
                    <div class="skor-value">1</div>
                    <div class="skor-description"><?php echo htmlspecialchars($deskripsi_1); ?></div>
                </label>
            </div>
            <?php endif; ?>
            
            <!-- SKOR 2 -->
            <?php if ($aspek['skor_2']): ?>
            <div class="skor-option skor-2">
                <input type="radio" 
                       id="skor_<?php echo $aspek['id']; ?>_2" 
                       name="skor_<?php echo $aspek['id']; ?>" 
                       value="2" 
                       <?php echo ($existing && $existing['nilai'] === '2') ? 'checked' : ''; ?>
                       class="skor-radio"
                       data-aspek-id="<?php echo $aspek['id']; ?>">
                <label for="skor_<?php echo $aspek['id']; ?>_2" class="skor-card">
                    <div class="skor-value">2</div>
                    <div class="skor-description"><?php echo htmlspecialchars($deskripsi_2); ?></div>
                </label>
            </div>
            <?php endif; ?>
        </div>

        <?php 
        $item_verifikasi = $aspek['item_verifikasi'] ?? '';
        if (!empty($item_verifikasi)): 
            // Parse item verifikasi yang sudah ada (jika ada)
            $existing_items = [];
            if ($existing && !empty($existing['catatan'])) {
                // Coba parse catatan untuk item yang sudah dicek
                preg_match_all('/\[item_checked:([^\]]+)\]/', $existing['catatan'], $matches);
                if (!empty($matches[1])) {
                    $existing_items = $matches[1];
                }
            }
            
            $items = array_filter(explode("\n", $item_verifikasi), function($item) {
                return trim($item) !== '';
            });
            
            if (!empty($items)):
        ?>
        <div class="item-verifikasi-container" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 10px; border: 2px solid #e9ecef;">
            <div class="item-verifikasi-header" style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                <h5 style="margin: 0; color: #495057; font-size: 1rem;">
                    <i class="fas fa-list-check"></i> Item Verifikasi
                    <small style="font-weight: normal; color: #6c757d; font-size: 0.85rem;">
                        (Centang Alat, Bahan, Prosedur yang sudah disebut/dilakukan oleh peserta)
                    </small>
                </h5>
                <div class="item-counter" style="background: #667eea; color: white; padding: 3px 10px; border-radius: 15px; font-size: 0.8rem;">
                    <span id="checked-count-<?php echo $aspek['id']; ?>">0</span>/<?php echo count($items); ?> item
                </div>
            </div>
            
            <div class="item-verifikasi-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;">
                <?php foreach ($items as $itemIndex => $item): 
                    $item = trim($item);
                    $itemId = 'item_' . $aspek['id'] . '_' . $itemIndex;
                    $isChecked = in_array($item, $existing_items);
                ?>
                <div class="item-checkbox" style="display: flex; align-items: center; gap: 8px; padding: 10px; background: white; border-radius: 8px; border: 2px solid <?php echo $isChecked ? '#28a745' : '#dee2e6'; ?>; transition: all 0.3s;">
                    <input type="checkbox" 
                           id="<?php echo $itemId; ?>" 
                           class="verifikasi-item-checkbox" 
                           data-aspek-id="<?php echo $aspek['id']; ?>"
                           data-item="<?php echo htmlspecialchars($item); ?>"
                           <?php echo $isChecked ? 'checked' : ''; ?>
                           style="width: 18px; height: 18px; cursor: pointer;">
                    <label for="<?php echo $itemId; ?>" style="margin: 0; cursor: pointer; font-size: 0.9rem; color: #495057; flex: 1;">
                        <?php echo htmlspecialchars($item); ?>
                    </label>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="item-actions" style="margin-top: 15px; display: flex; gap: 10px;">
                <button type="button" class="btn-select-all" data-aspek-id="<?php echo $aspek['id']; ?>" style="padding: 5px 15px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 0.85rem;">
                    <i class="fas fa-check-double"></i> Centang Semua
                </button>
                <button type="button" class="btn-unselect-all" data-aspek-id="<?php echo $aspek['id']; ?>" style="padding: 5px 15px; background: #e74c3c; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 0.85rem;">
                    <i class="fas fa-times"></i> Hapus Centang
                </button>
            </div>
        </div>
        <?php endif; ?>
        <?php endif; ?>
        
       <!-- <div class="catatan-group">
            <label for="catatan_<?php echo $aspek['id']; ?>">
                <i class="fas fa-sticky-note"></i> Catatan (Opsional)
            </label>
            <textarea id="catatan_<?php echo $aspek['id']; ?>" 
                      name="catatan_<?php echo $aspek['id']; ?>" 
                      class="catatan-textarea"
                      placeholder="Tambahkan catatan khusus jika perlu..."><?php 
                echo $existing ? htmlspecialchars($existing['catatan']) : ''; 
            ?></textarea>
        </div> -->
        
        <?php if ($index < count($aspeks) - 1): ?>
        <hr class="aspek-divider">
        <?php endif; ?>
    </div>
    <?php
}

// Tambahkan script untuk progress indicator
?>
<script>
// Inisialisasi progress indicator setelah aspek dimuat
setTimeout(function() {
    if (typeof updateProgressIndicator === 'function') {
        updateProgressIndicator();
    }
    
    // Tambahkan event listener untuk radio buttons
    document.querySelectorAll('.skor-radio').forEach(radio => {
        radio.addEventListener('change', function() {
            // Update progress indicator
            if (typeof updateProgressIndicator === 'function') {
                setTimeout(updateProgressIndicator, 100);
            }
            
            // Tambahkan visual feedback
            const card = this.closest('.skor-option').querySelector('.skor-card');
            document.querySelectorAll('.skor-card').forEach(c => {
                c.classList.remove('selected');
            });
            card.classList.add('selected');
        });
    });
    
    // Load existing global performance
    if (typeof loadExistingGlobalPerformance === 'function') {
        loadExistingGlobalPerformance();
    }
}, 500);
</script>