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

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

$aspek_id = $_GET['id'] ?? 0;
$ujian_id = $_GET['ujian_id'] ?? 0;
$peserta_id = $_GET['peserta_id'] ?? 0;

// Ambil data aspek
$stmt = $pdo->prepare("SELECT ap.*, s.nama_station 
    FROM aspek_penilaian ap 
    JOIN stations s ON ap.station_id = s.id 
    WHERE ap.id = ?");
$stmt->execute([$aspek_id]);
$aspek = $stmt->fetch();

if (!$aspek) {
    die("Aspek tidak ditemukan");
}

// Ambil data penilaian yang sudah ada
$stmt = $pdo->prepare("SELECT * FROM penilaian WHERE aspek_id = ? AND ujian_id = ? AND peserta_id = ?");
$stmt->execute([$aspek_id, $ujian_id, $peserta_id]);
$penilaian = $stmt->fetch();

// Ambil checklist verifikasi yang sudah ada
$stmt = $pdo->prepare("SELECT * FROM checklist_verifikasi WHERE aspek_id = ? AND ujian_id = ? AND peserta_id = ?");
$stmt->execute([$aspek_id, $ujian_id, $peserta_id]);
$checklist_data = $stmt->fetch();
$checked_items = $checklist_data ? json_decode($checklist_data['checked_items'], true) : [];

// Proses simpan checklist verifikasi (TERPISAH dari nilai)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['simpan_checklist'])) {
    $checked_items = $_POST['checked_items'] ?? [];
    $total_items = count(explode("\n", trim($aspek['checklist_items'])));
    
    // Simpan checklist verifikasi (hanya pencatatan)
    $stmt = $pdo->prepare("INSERT INTO checklist_verifikasi 
        (aspek_id, ujian_id, peserta_id, penguji_id, checked_items, total_items) 
        VALUES (?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
        checked_items = VALUES(checked_items),
        total_items = VALUES(total_items),
        penguji_id = VALUES(penguji_id)");
    
    $checked_items_json = json_encode($checked_items);
    $stmt->execute([$aspek_id, $ujian_id, $peserta_id, $_SESSION['user_id'], $checked_items_json, $total_items]);
    
    $success_checklist = "Checklist verifikasi berhasil disimpan!";
}

// Proses simpan nilai (TERPISAH dari checklist)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['simpan_nilai'])) {
    $skor = intval($_POST['skor']);
    
    // Validasi skor sesuai yang tersedia
    $valid_skor = false;
    if ($skor == 0 && $aspek['skor_0']) $valid_skor = true;
    if ($skor == 1 && $aspek['skor_1']) $valid_skor = true;
    if ($skor == 2 && $aspek['skor_2']) $valid_skor = true;
    
    if ($valid_skor) {
        // Simpan nilai ke tabel penilaian
        $stmt = $pdo->prepare("INSERT INTO penilaian 
            (aspek_id, ujian_id, peserta_id, penguji_id, nilai, catatan) 
            VALUES (?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE 
            nilai = VALUES(nilai),
            catatan = VALUES(catatan),
            penguji_id = VALUES(penguji_id)");
        
        $stmt->execute([$aspek_id, $ujian_id, $peserta_id, $_SESSION['user_id'], $skor, $_POST['catatan'] ?? '']);
        
        $success_nilai = "Nilai berhasil disimpan! Skor: " . $skor;
        $penilaian = $stmt->fetch();
    } else {
        $error = "Skor tidak valid untuk aspek ini!";
    }
}

// Parse checklist items
$checklist_items = [];
if ($aspek['checklist_items']) {
    $lines = explode("\n", trim($aspek['checklist_items']));
    foreach ($lines as $line) {
        if (trim($line) != '') {
            $checklist_items[] = trim($line);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Penilaian - <?php echo htmlspecialchars($aspek['nama_aspek']); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 40px;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
        }
        .section-title {
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
            margin-bottom: 20px;
            color: #333;
        }
        .checklist-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        .checklist-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            margin: 8px 0;
            background: white;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .checklist-item:hover {
            border-color: #6c757d;
        }
        .checklist-item.checked {
            background: #e7f3ff;
            border-color: #007bff;
        }
        .checklist-item input[type="checkbox"] {
            margin-right: 15px;
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        .checklist-item label {
            flex: 1;
            margin: 0;
            font-size: 15px;
            cursor: pointer;
        }
        .checklist-stats {
            background: #e9ecef;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
            font-size: 16px;
        }
        .skor-options {
            display: flex;
            gap: 20px;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        .skor-option {
            flex: 1;
            min-width: 200px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .skor-option:hover {
            border-color: #007bff;
            background: #f0f7ff;
        }
        .skor-option.selected {
            border-color: #28a745;
            background: #d4edda;
        }
        .skor-option input[type="radio"] {
            margin-right: 10px;
            transform: scale(1.2);
        }
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2><?php echo htmlspecialchars($aspek['nama_station']); ?></h2>
            <h3><?php echo htmlspecialchars($aspek['nama_aspek']); ?></h3>
            <p><strong>ID Ujian:</strong> <?php echo $ujian_id; ?> | 
               <strong>ID Peserta:</strong> <?php echo $peserta_id; ?></p>
        </div>
        
        <?php if (isset($success_nilai)): ?>
            <div class="alert alert-success"><?php echo $success_nilai; ?></div>
        <?php endif; ?>
        
        <?php if (isset($success_checklist)): ?>
            <div class="alert alert-success"><?php echo $success_checklist; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <!-- BAGIAN 1: CHECKLIST VERIFIKASI (Opsional) -->
        <?php if ($aspek['has_checklist'] && !empty($checklist_items)): ?>
        <div class="section">
            <h3 class="section-title">
                <i class="fas fa-check-circle"></i> Checklist Verifikasi Penguji
            </h3>
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> 
                <strong>Catatan Penting:</strong> Checklist ini HANYA untuk membantu penguji mencatat item yang sudah diverifikasi. 
                <strong>TIDAK mempengaruhi nilai akhir.</strong> Nilai ditentukan oleh skor di bagian bawah.
            </div>
            
            <form method="POST" id="checklistForm">
                <div class="checklist-container">
                    <h4>Verifikasi Item yang Disebutkan Peserta:</h4>
                    <p>Centang item yang telah disebutkan/dilakukan oleh peserta:</p>
                    
                    <?php foreach ($checklist_items as $index => $item): 
                        $item_id = 'check_item_' . $index;
                        $is_checked = in_array($index, $checked_items);
                    ?>
                        <div class="checklist-item <?php echo $is_checked ? 'checked' : ''; ?>">
                            <input type="checkbox" 
                                   id="<?php echo $item_id; ?>" 
                                   name="checked_items[]" 
                                   value="<?php echo $index; ?>"
                                   <?php echo $is_checked ? 'checked' : ''; ?>>
                            <label for="<?php echo $item_id; ?>">
                                <?php echo htmlspecialchars($item); ?>
                            </label>
                        </div>
                    <?php endforeach; ?>
                    
                    <div class="checklist-stats">
                        <span id="checked-count"><?php echo count($checked_items); ?></span> / 
                        <span id="total-count"><?php echo count($checklist_items); ?></span> item terverifikasi
                    </div>
                </div>
                
                <input type="hidden" name="aspek_id" value="<?php echo $aspek_id; ?>">
                <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
                <input type="hidden" name="peserta_id" value="<?php echo $peserta_id; ?>">
                
                <button type="submit" name="simpan_checklist" class="btn btn-secondary">
                    <i class="fas fa-clipboard-check"></i> Simpan Checklist Verifikasi
                </button>
                
                <small style="color: #666; margin-left: 15px;">
                    (Checklist ini bisa disimpan terpisah dari nilai)
                </small>
            </form>
        </div>
        <?php endif; ?>
        
        <!-- BAGIAN 2: PENILAIAN NILAI (Utama) -->
        <div class="section">
            <h3 class="section-title">
                <i class="fas fa-star"></i> Penilaian Nilai (WAJIB)
            </h3>
            
            <form method="POST" id="nilaiForm">
                <!-- Deskripsi Skor yang Tersedia -->
                <h4>Deskripsi Skor:</h4>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <?php if ($aspek['skor_0']): ?>
                        <div style="margin-bottom: 10px;">
                            <span class="skor-badge" style="background: #e74c3c; color: white; padding: 4px 12px; border-radius: 4px; font-weight: bold;">Skor 0</span>
                            <div style="margin-left: 20px; margin-top: 5px;">
                                <?php echo $aspek['deskripsi_0'] ? htmlspecialchars($aspek['deskripsi_0']) : 'Tidak ada deskripsi'; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($aspek['skor_1']): ?>
                        <div style="margin-bottom: 10px;">
                            <span class="skor-badge" style="background: #f39c12; color: white; padding: 4px 12px; border-radius: 4px; font-weight: bold;">Skor 1</span>
                            <div style="margin-left: 20px; margin-top: 5px;">
                                <?php echo $aspek['deskripsi_1'] ? htmlspecialchars($aspek['deskripsi_1']) : 'Tidak ada deskripsi'; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($aspek['skor_2']): ?>
                        <div style="margin-bottom: 10px;">
                            <span class="skor-badge" style="background: #27ae60; color: white; padding: 4px 12px; border-radius: 4px; font-weight: bold;">Skor 2</span>
                            <div style="margin-left: 20px; margin-top: 5px;">
                                <?php echo $aspek['deskripsi_2'] ? htmlspecialchars($aspek['deskripsi_2']) : 'Tidak ada deskripsi'; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Pilihan Skor -->
                <h4>Pilih Skor:</h4>
                <div class="skor-options">
                    <?php if ($aspek['skor_0']): ?>
                        <div class="skor-option <?php echo ($penilaian && $penilaian['nilai'] == 0) ? 'selected' : ''; ?>">
                            <input type="radio" name="skor" id="skor_0" value="0" required 
                                   <?php echo ($penilaian && $penilaian['nilai'] == 0) ? 'checked' : ''; ?>>
                            <label for="skor_0" style="font-weight: bold; color: #e74c3c;">
                                <span style="font-size: 20px;">Skor 0</span><br>
                                <small><?php echo htmlspecialchars(substr($aspek['deskripsi_0'] ?? 'Tidak memenuhi', 0, 50)) . '...'; ?></small>
                            </label>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($aspek['skor_1']): ?>
                        <div class="skor-option <?php echo ($penilaian && $penilaian['nilai'] == 1) ? 'selected' : ''; ?>">
                            <input type="radio" name="skor" id="skor_1" value="1" 
                                   <?php echo ($penilaian && $penilaian['nilai'] == 1) ? 'checked' : ''; ?>>
                            <label for="skor_1" style="font-weight: bold; color: #f39c12;">
                                <span style="font-size: 20px;">Skor 1</span><br>
                                <small><?php echo htmlspecialchars(substr($aspek['deskripsi_1'] ?? 'Cukup memenuhi', 0, 50)) . '...'; ?></small>
                            </label>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($aspek['skor_2']): ?>
                        <div class="skor-option <?php echo ($penilaian && $penilaian['nilai'] == 2) ? 'selected' : ''; ?>">
                            <input type="radio" name="skor" id="skor_2" value="2" 
                                   <?php echo ($penilaian && $penilaian['nilai'] == 2) ? 'checked' : ''; ?>>
                            <label for="skor_2" style="font-weight: bold; color: #27ae60;">
                                <span style="font-size: 20px;">Skor 2</span><br>
                                <small><?php echo htmlspecialchars(substr($aspek['deskripsi_2'] ?? 'Sangat memenuhi', 0, 50)) . '...'; ?></small>
                            </label>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Catatan Tambahan -->
                <div class="form-group" style="margin-top: 20px;">
                    <label for="catatan">Catatan Penguji (Opsional):</label>
                    <textarea name="catatan" id="catatan" rows="3" style="width: 100%; padding: 10px; border: 1px solid #ced4da; border-radius: 4px;"><?php echo $penilaian['catatan'] ?? ''; ?></textarea>
                </div> 
                
                <input type="hidden" name="aspek_id" value="<?php echo $aspek_id; ?>">
                <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
                <input type="hidden" name="peserta_id" value="<?php echo $peserta_id; ?>">
                
                <button type="submit" name="simpan_nilai" class="btn btn-success" style="font-size: 18px; padding: 15px 30px;">
                    <i class="fas fa-save"></i> SIMPAN NILAI (Skor: <span id="selected-skor">0</span>)
                </button>
                
                <button type="button" class="btn btn-primary" onclick="window.history.back()">
                    <i class="fas fa-arrow-left"></i> Kembali
                </button>
            </form>
        </div>
    </div>
    
    <script>
        // Update checklist stats
        function updateChecklistStats() {
            const checkboxes = document.querySelectorAll('input[name="checked_items[]"]');
            const checked = document.querySelectorAll('input[name="checked_items[]"]:checked');
            
            document.getElementById('checked-count').textContent = checked.length;
            
            // Update visual state
            checkboxes.forEach(checkbox => {
                const item = checkbox.closest('.checklist-item');
                if (checkbox.checked) {
                    item.classList.add('checked');
                } else {
                    item.classList.remove('checked');
                }
            });
        }
        
        // Update skor selection
        function updateSkorSelection() {
            const radios = document.querySelectorAll('input[name="skor"]');
            const selectedSkorDisplay = document.getElementById('selected-skor');
            
            radios.forEach(radio => {
                const option = radio.closest('.skor-option');
                radio.addEventListener('change', function() {
                    // Remove selected class from all
                    document.querySelectorAll('.skor-option').forEach(el => {
                        el.classList.remove('selected');
                    });
                    
                    // Add selected class to current
                    if (option) option.classList.add('selected');
                    
                    // Update display
                    selectedSkorDisplay.textContent = this.value;
                });
                
                // Initial check
                if (radio.checked && option) {
                    option.classList.add('selected');
                    selectedSkorDisplay.textContent = radio.value;
                }
            });
        }
        
        // Attach event listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Checklist events
            const checklistCheckboxes = document.querySelectorAll('input[name="checked_items[]"]');
            if (checklistCheckboxes.length > 0) {
                checklistCheckboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', updateChecklistStats);
                });
                updateChecklistStats();
            }
            
            // Skor events
            updateSkorSelection();
            
            // Form submission confirmation
            document.getElementById('nilaiForm')?.addEventListener('submit', function(e) {
                const selectedSkor = document.querySelector('input[name="skor"]:checked');
                if (!selectedSkor) {
                    e.preventDefault();
                    alert('Pilih skor terlebih dahulu!');
                    return false;
                }
                
                if (!confirm(`Anda akan memberikan skor ${selectedSkor.value}. Lanjutkan?`)) {
                    e.preventDefault();
                    return false;
                }
            });
        });
        
        // Auto-save checklist (opsional)
        let checklistTimeout;
        document.getElementById('checklistForm')?.addEventListener('change', function() {
            clearTimeout(checklistTimeout);
            checklistTimeout = setTimeout(() => {
                // Opsional: Auto-save checklist tanpa reload
                console.log('Checklist updated');
            }, 1000);
        });
    </script>
</body>
</html>