<?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
    $stmt = $pdo->prepare("SELECT id FROM ujian WHERE status = 'aktif' ORDER BY tanggal_ujian DESC LIMIT 1");
    $stmt->execute();
    $ujian_aktif = $stmt->fetch();
    
    if ($ujian_aktif) {
        redirect("penilaian.php?ujian_id=" . $ujian_aktif['id']);
    } else {
        // Jika tidak ada ujian aktif, tetap di halaman ini dengan pesan
        $error = "Tidak ada ujian aktif yang tersedia.";
    }
}

// Ambil data ujian jika ujian_id ada
$ujian = null;
$stations = [];
if ($ujian_id) {
    $stmt = $pdo->prepare("SELECT * FROM ujian WHERE id = ? AND status = 'aktif'");
    $stmt->execute([$ujian_id]);
    $ujian = $stmt->fetch();

    if ($ujian) {
        // Ambil stations untuk ujian ini
        $stmt = $pdo->prepare("
            SELECT s.*, us.urutan 
            FROM stations s 
            INNER JOIN ujian_stations us ON s.id = us.station_id 
            WHERE us.ujian_id = ? 
            ORDER BY us.urutan
        ");
        $stmt->execute([$ujian_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
    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 * FROM ujian WHERE status = 'aktif' ORDER BY tanggal_ujian DESC");
        $stmt->execute();
        $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.
            </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)): ?>
        <!-- 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
                            $stmt = $pdo->query("SELECT * FROM peserta ORDER BY nama");
                            $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; ?>
                        </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 foreach ($stations as $station): ?>
                                <option value="<?php echo $station['id']; ?>" 
                                    <?php echo isset($_POST['station_id']) && $_POST['station_id'] == $station['id'] ? '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>
            </form>
        </div>

        <!-- Daftar Penilaian Terbaru -->
        <div class="card">
            <h3>Penilaian Terbaru Anda</h3>
            <?php
            $stmt = $pdo->prepare("
                SELECT p.nama as peserta_nama, s.nama_station, n.nilai, n.created_at
                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 = ?
                ORDER BY n.created_at 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>Nilai</th>
                                <th>Waktu</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($penilaian_terbaru as $nilai): ?>
                                <tr>
                                    <td><?php echo $nilai['peserta_nama']; ?></td>
                                    <td><?php echo $nilai['nama_station']; ?></td>
                                    <td>
                                        <span class="nilai-badge nilai-<?php echo $nilai['nilai']; ?>">
                                            <?php echo $nilai['nilai']; ?>
                                        </span>
                                    </td>
                                    <td><?php echo formatTanggal($nilai['created_at']); ?></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;
}

.nilai-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.8rem;
    display: inline-block;
}

.nilai-0 { background: #e74c3c; color: white; }
.nilai-1 { background: #f39c12; color: white; }
.nilai-2 { background: #27ae60; color: white; }

.aspek-item {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 1.5rem;
    margin-bottom: 1rem;
}

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

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

.aspek-header h4 {
    margin: 0;
    color: #2c3e50;
}

.skor-options {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 1rem;
}

.skor-option {
    cursor: pointer;
}

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

.skor-card {
    border: 2px solid #dee2e6;
    border-radius: 6px;
    padding: 1rem;
    transition: all 0.3s;
    text-align: center;
}

.skor-option input[type="radio"]:checked + .skor-card {
    border-color: #3498db;
    background: #e8f4fd;
    transform: scale(1.05);
}

.skor-card:hover {
    border-color: #adb5bd;
}

.skor-value {
    font-size: 1.5rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
}

.skor-0 .skor-value { color: #e74c3c; }
.skor-1 .skor-value { color: #f39c12; }
.skor-2 .skor-value { color: #27ae60; }

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

.catatan-group {
    margin-top: 1rem;
}

.catatan-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #495057;
}

.catatan-group textarea {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ced4da;
    border-radius: 4px;
    resize: vertical;
    font-family: inherit;
}

.submit-section {
    margin-top: 2rem;
    padding-top: 1rem;
    border-top: 1px solid #e9ecef;
    text-align: center;
}

@media (max-width: 768px) {
    .ujian-tabs {
        flex-direction: column;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .skor-options {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const stationSelect = document.getElementById('station_id');
    const pesertaSelect = document.getElementById('peserta_id');
    const aspekContainer = document.getElementById('aspekContainer');
    
    // Load aspek penilaian ketika station dipilih
    stationSelect.addEventListener('change', loadAspekPenilaian);
    pesertaSelect.addEventListener('change', loadAspekPenilaian);
    
    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">
                <i class="fas fa-spinner fa-spin"></i>
                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;
            } 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'; ?>));
    }
    
    // Auto-load jika sudah ada pilihan dari form submission
    if (stationSelect.value && pesertaSelect.value) {
        loadAspekPenilaian();
    }
});
</script>

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