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

if (!isPenguji()) {
    header('HTTP/1.1 403 Forbidden');
    exit('Unauthorized access');
}

header('Content-Type: text/html; charset=utf-8');

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

if (!$station_id || !$peserta_id || !$ujian_id) {
    echo '<div class="alert alert-error">Data tidak lengkap!</div>';
    exit;
}

try {
    // AMBIL DATA STATION TERLEBIH DAHULU - INI YANG DITAMBAHKAN
    $stmt = $pdo->prepare("
        SELECT s.*, u.nama_ujian 
        FROM stations s 
        LEFT JOIN ujian u ON s.id = ? 
        WHERE s.id = ?
    ");
    $stmt->execute([$station_id, $station_id]);
    $station = $stmt->fetch();

    if (!$station) {
        // Fallback: cari station tanpa join
        $stmt = $pdo->prepare("SELECT * FROM stations WHERE id = ?");
        $stmt->execute([$station_id]);
        $station = $stmt->fetch();
        
        if (!$station) {
            echo '<div class="alert alert-error">Station tidak ditemukan!</div>';
            exit;
        }
    }

    // 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();

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

    // Function untuk render HTML content dengan gambar
    function renderHTMLContent($content) {
        if (empty($content)) return '';
        
        // Decode HTML entities
        $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
        
        // Security: Remove potentially dangerous tags and attributes
        $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
        $content = preg_replace('/on\w+=\s*"[^"]*"\s*/i', '', $content);
        $content = preg_replace('/on\w+=\s*\'[^\']*\'\s*/i', '', $content);
        
        return $content;
    }

    // HITUNG TOTAL MAKSIMAL JIKA TIDAK ADA DI DATABASE
    if (!isset($station['total_maksimal']) || $station['total_maksimal'] === null) {
        $total_maksimal = 0;
        foreach ($aspeks as $aspek) {
            if ($aspek['skor_2']) $total_maksimal += 2;
            else if ($aspek['skor_1']) $total_maksimal += 1;
            else if ($aspek['skor_0']) $total_maksimal += 0;
        }
        $station['total_maksimal'] = $total_maksimal;
    }

    echo '<div class="aspek-container">';
    
    // TAMPILKAN TOTAL MAKSIMAL 
    echo '<div class="total-maksimal-info" style="background: #e8f5e8; padding: 15px; border-radius: 5px; margin: 15px 0; text-align: center;">';
    echo '<h4 style="margin: 0; color: #28a745;">';
    echo 'Total Nilai Maksimal: <strong>' . $station['total_maksimal'] . '</strong>';
    echo '</h4>';
    echo '</div>';
    
    foreach ($aspeks as $index => $aspek) {
        // Cek apakah sudah ada penilaian sebelumnya
        $stmt = $pdo->prepare("
            SELECT nilai 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, $_SESSION['user_id'], $aspek['id']]);
        $penilaian_sebelumnya = $stmt->fetch();
        
        $nilai_sebelumnya = $penilaian_sebelumnya ? $penilaian_sebelumnya['nilai'] : '';
        
        // Render nama aspek dengan HTML (termasuk gambar)
        $nama_aspek_html = renderHTMLContent($aspek['nama_aspek']);
        
        echo '
        <div class="aspek-item">
            <div class="aspek-header">
                <div class="aspek-number">' . ($index + 1) . '</div>
                <div class="aspek-title">
                    <h4>Aspek Penilaian</h4>
                    <div class="aspek-nama">' . $nama_aspek_html . '</div>
                </div>
            </div>
            
            <!-- Garis Pemisah antara Header dan Skor Options -->
            <div class="aspek-divider"></div>
            
            <div class="skor-options">';
        
        // Skor 0
        if ($aspek['skor_0']) {
            $deskripsi_0_html = renderHTMLContent($aspek['deskripsi_0']);
            $checked_0 = ($nilai_sebelumnya === '0' || $nilai_sebelumnya === 0) ? 'checked' : '';
            echo '
            <label class="skor-option">
                <input type="radio" name="skor_' . $aspek['id'] . '" value="0" ' . $checked_0 . ' required>
                <div class="skor-card skor-0">
                    <div class="skor-value">0</div>
                    <div class="skor-description">' . $deskripsi_0_html . '</div>
                    <div class="skor-badge">Tidak Dilakukan</div>
                </div>
            </label>';
        }
        
        // Skor 1
        if ($aspek['skor_1']) {
            $deskripsi_1_html = renderHTMLContent($aspek['deskripsi_1']);
            $checked_1 = ($nilai_sebelumnya === '1' || $nilai_sebelumnya === 1) ? 'checked' : '';
            echo '
            <label class="skor-option">
                <input type="radio" name="skor_' . $aspek['id'] . '" value="1" ' . $checked_1 . ' required>
                <div class="skor-card skor-1">
                    <div class="skor-value">1</div>
                    <div class="skor-description">' . $deskripsi_1_html . '</div>
                    <div class="skor-badge">Perlu Perbaikan</div>
                </div>
            </label>';
        }
        
        // Skor 2
        if ($aspek['skor_2']) {
            $deskripsi_2_html = renderHTMLContent($aspek['deskripsi_2']);
            $checked_2 = ($nilai_sebelumnya === '2' || $nilai_sebelumnya === 2) ? 'checked' : '';
            echo '
            <label class="skor-option">
                <input type="radio" name="skor_' . $aspek['id'] . '" value="2" ' . $checked_2 . ' required>
                <div class="skor-card skor-2">
                    <div class="skor-value">2</div>
                    <div class="skor-description">' . $deskripsi_2_html . '</div>
                    <div class="skor-badge">Dilakukan dengan Baik</div>
                </div>
            </label>';
        }
        
        echo '
            </div>
        </div>'; // Tutup div.aspek-item
    }
    
    echo '</div>';

} catch (Exception $e) {
    echo '<div class="alert alert-error">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>