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

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

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

// Filter parameters
$ujian_id = $_GET['ujian_id'] ?? '';
$peserta_id = $_GET['peserta_id'] ?? '';
$station_id = $_GET['station_id'] ?? '';

// Ambil data untuk filter
$stmt = $pdo->query("SELECT * FROM ujian WHERE status = 'aktif' OR status = 'selesai' ORDER BY tanggal_ujian DESC");
$ujian_list = $stmt->fetchAll();

$stmt = $pdo->query("SELECT * FROM peserta ORDER BY nama");
$peserta_list = $stmt->fetchAll();

$stmt = $pdo->query("SELECT * FROM stations ORDER BY nama_station");
$stations_list = $stmt->fetchAll();

// Query untuk hasil penilaian
$where_conditions = [];
$params = [];

if (!empty($ujian_id)) {
    $where_conditions[] = "n.ujian_id = ?";
    $params[] = $ujian_id;
}

if (!empty($peserta_id)) {
    $where_conditions[] = "p.id = ?";
    $params[] = $peserta_id;
}

if (!empty($station_id)) {
    $where_conditions[] = "s.id = ?";
    $params[] = $station_id;
}

$where_sql = '';
if (!empty($where_conditions)) {
    $where_sql = "WHERE " . implode(" AND ", $where_conditions);
}

// Query utama untuk hasil penilaian - PERBAIKAN QUERY
$query = "
    SELECT 
        u.nama_ujian,
        u.id as ujian_id,
        p.nim,
        p.nama as peserta_nama,
        p.id as peserta_id,
        p.program_studi,
        s.nama_station,
        s.id as station_id,
        s.deskripsi as station_deskripsi,
        s.total_maksimal,  -- TAMBAH INI
        COUNT(DISTINCT n.aspek_id) as total_aspek,
        SUM(n.nilai) as total_nilai,
        MAX(n.created_at) as waktu_penilaian,
        us.username as penguji_username,
        us.id as penguji_id,
        pg.global_performance
    FROM penilaian n
    INNER JOIN ujian u ON n.ujian_id = u.id
    INNER JOIN peserta p ON n.peserta_id = p.id
    INNER JOIN stations s ON n.station_id = s.id
    INNER JOIN users us ON n.penguji_id = us.id
    LEFT JOIN penilaian_global pg ON (
        n.ujian_id = pg.ujian_id 
        AND n.peserta_id = pg.peserta_id 
        AND n.station_id = pg.station_id 
        AND n.penguji_id = pg.penguji_id
    )
    $where_sql
    GROUP BY n.ujian_id, n.peserta_id, n.station_id, n.penguji_id
    ORDER BY u.tanggal_ujian DESC, p.nama, s.nama_station
";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$hasil_penilaian = $stmt->fetchAll();

// Query untuk statistik - DIPERBAIKI
$stat_query = "
    SELECT 
        COUNT(DISTINCT n.peserta_id) as total_peserta,
        COUNT(DISTINCT n.station_id) as total_station,
        COUNT(DISTINCT n.penguji_id) as total_penguji,
        AVG(total_nilai) as rata_rata_nilai
    FROM (
        SELECT 
            peserta_id,
            station_id,
            penguji_id,
            SUM(nilai) as total_nilai
        FROM penilaian
        GROUP BY peserta_id, station_id, penguji_id
    ) as subquery
";

try {
    $stmt = $pdo->query($stat_query);
    $statistik = $stmt->fetch();
} catch (PDOException $e) {
    // Jika masih error, gunakan query yang lebih sederhana
    $statistik = [
        'total_peserta' => 0,
        'total_station' => 0,
        'total_penguji' => 0,
        'rata_rata_nilai' => 0
    ];
}

// Query untuk detail penilaian per aspek - PERBAIKAN KOLOM DESKRIPSI
if (isset($_GET['detail'])) {
    $detail_peserta_id = $_GET['detail_peserta'] ?? '';
    $detail_station_id = $_GET['detail_station'] ?? '';
    $detail_ujian_id = $_GET['detail_ujian'] ?? '';
    
    // Ambil penguji_id terlebih dahulu
    $penguji_query = "
        SELECT DISTINCT n.penguji_id, us.username
        FROM penilaian n
        INNER JOIN users us ON n.penguji_id = us.id
        WHERE n.peserta_id = ? AND n.station_id = ? AND n.ujian_id = ?
        LIMIT 1
    ";
    
    try {
        $stmt = $pdo->prepare($penguji_query);
        $stmt->execute([$detail_peserta_id, $detail_station_id, $detail_ujian_id]);
        $penguji_data = $stmt->fetch();
        $penguji_id = $penguji_data['penguji_id'] ?? null;
        
        // Query alternatif dengan deskripsi skor
$detail_query = "
    SELECT 
        ap.nama_aspek,
        ap.nomor_urut,
        n.nilai,
        n.catatan,
        us.username as penguji_username,
        n.created_at,
        CASE 
            WHEN n.nilai = 0 THEN ap.deskripsi_0
            WHEN n.nilai = 1 THEN ap.deskripsi_1  
            WHEN n.nilai = 2 THEN ap.deskripsi_2
            ELSE ''
        END as deskripsi_skor
    FROM penilaian n
    INNER JOIN aspek_penilaian ap ON n.aspek_id = ap.id
    INNER JOIN users us ON n.penguji_id = us.id
    WHERE n.peserta_id = ? AND n.station_id = ? AND n.ujian_id = ?
    ORDER BY ap.nomor_urut
";
        
        $stmt = $pdo->prepare($detail_query);
        $stmt->execute([$detail_peserta_id, $detail_station_id, $detail_ujian_id]);
        $detail_penilaian = $stmt->fetchAll();
        
        // Ambil global performance
        $global_performance = null;
        if ($penguji_id) {
            $global_query = "
                SELECT global_performance 
                FROM penilaian_global 
                WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? AND penguji_id = ?
            ";
            $stmt = $pdo->prepare($global_query);
            $stmt->execute([$detail_ujian_id, $detail_peserta_id, $detail_station_id, $penguji_id]);
            $global_data = $stmt->fetch();
            $global_performance = $global_data['global_performance'] ?? null;
        }
        
    } catch (PDOException $e) {
        $detail_penilaian = [];
        $global_performance = null;
        $error = "Gagal memuat detail penilaian: " . $e->getMessage();
    }
}

// Helper function untuk memotong teks
function truncateText($text, $length = 100) {
    if (strlen($text) <= $length) {
        return $text;
    }
    return substr($text, 0, $length) . '...';
}
?>

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

<div class="content">
    <div class="page-header">
        <h2><i class="fas fa-chart-bar"></i> Hasil Penilaian</h2>
    </div>
    
    <?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; ?>

    <!-- Statistik -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $statistik['total_peserta'] ?? 0; ?></h3>
                <p>Total Peserta</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-clipboard-list"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $statistik['total_station'] ?? 0; ?></h3>
                <p>Total Station</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-user-check"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $statistik['total_penguji'] ?? 0; ?></h3>
                <p>Total Penguji</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo number_format($statistik['rata_rata_nilai'] ?? 0, 2); ?></h3>
                <p>Rata-rata Nilai</p>
            </div>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="card">
        <h3>Filter Hasil Penilaian</h3>
        
        <form method="GET" class="filter-form">
            <div class="form-row">
                <div class="form-group">
                    <label for="ujian_id">Ujian</label>
                    <select id="ujian_id" name="ujian_id">
                        <option value="">Semua Ujian</option>
                        <?php foreach ($ujian_list as $ujian): ?>
                            <option value="<?php echo $ujian['id']; ?>" 
                                <?php echo $ujian_id == $ujian['id'] ? 'selected' : ''; ?>>
                                <?php echo $ujian['nama_ujian']; ?> (<?php echo formatTanggal($ujian['tanggal_ujian']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="peserta_id">Peserta</label>
                    <select id="peserta_id" name="peserta_id">
                        <option value="">Semua Peserta</option>
                        <?php foreach ($peserta_list as $peserta): ?>
                            <option value="<?php echo $peserta['id']; ?>" 
                                <?php echo $peserta_id == $peserta['id'] ? 'selected' : ''; ?>>
                                <?php echo $peserta['nim'] . ' - ' . $peserta['nama']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="station_id">Station</label>
                    <select id="station_id" name="station_id">
                        <option value="">Semua Station</option>
                        <?php foreach ($stations_list as $station): ?>
                            <option value="<?php echo $station['id']; ?>" 
                                <?php echo $station_id == $station['id'] ? 'selected' : ''; ?>>
                                <?php echo $station['nama_station']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-filter"></i> Terapkan Filter
                </button>
                <a href="nilai.php" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Reset Filter
                </a>
            </div>
        </form>
    </div>

    <!-- Tombol Export -->
<div class="export-actions" style="margin: 1rem 0; text-align: right;">
    <form method="POST" action="export_nilai_csv.php" style="display: inline;">
        <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
        <input type="hidden" name="peserta_id" value="<?php echo $peserta_id; ?>">
        <input type="hidden" name="station_id" value="<?php echo $station_id; ?>">
        <input type="hidden" name="export_type" value="summary">
        <input type="hidden" name="include_notes" value="1"> <!-- Tambahkan ini -->
        <button type="submit" name="export_excel" class="btn btn-success">
            <i class="fas fa-file-excel"></i> Export Summary
        </button>
        <button type="button" class="btn btn-danger" onclick="showDeleteConfirmation()" 
            <?php echo empty($hasil_penilaian) ? 'disabled' : ''; ?>>
        <i class="fas fa-trash-alt"></i> Hapus Semua Data
    </button>
    </form>
    
    <form method="POST" action="export_nilai_csv.php" style="display: inline; margin-left: 10px;">
        <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
        <input type="hidden" name="peserta_id" value="<?php echo $peserta_id; ?>">
        <input type="hidden" name="station_id" value="<?php echo $station_id; ?>">
        <input type="hidden" name="export_type" value="detail">
        <input type="hidden" name="include_notes" value="1"> <!-- Tambahkan ini -->
        <button type="submit" name="export_excel" class="btn btn-info">
            <i class="fas fa-file-excel"></i> Export Detail
        </button>
    </form>
</div>

<!-- Modal Konfirmasi Hapus Semua -->
<div class="modal-overlay" id="deleteConfirmationModal" style="display: none;">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3><i class="fas fa-exclamation-triangle text-danger"></i> Konfirmasi Hapus Data</h3>
            <button type="button" class="close-btn" onclick="closeDeleteModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="alert alert-danger">
                <h4><i class="fas fa-warning"></i> PERINGATAN!</h4>
                <p>Anda akan menghapus <strong>SEMUA DATA PENILAIAN</strong> yang ditampilkan.</p>
                <p><strong>Jumlah data yang akan dihapus: <?php echo count($hasil_penilaian); ?> record</strong></p>
                
                <?php if (!empty($where_conditions)): ?>
                    <div class="filter-info" style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin: 10px 0;">
                        <strong>Filter yang aktif:</strong>
                        <ul style="margin: 5px 0 0 20px;">
                            <?php if (!empty($ujian_id)): ?>
                                <li>Ujian: <?php 
                                    foreach ($ujian_list as $ujian) {
                                        if ($ujian['id'] == $ujian_id) {
                                            echo $ujian['nama_ujian'];
                                            break;
                                        }
                                    }
                                ?></li>
                            <?php endif; ?>
                            <?php if (!empty($peserta_id)): ?>
                                <li>Peserta: <?php 
                                    foreach ($peserta_list as $peserta) {
                                        if ($peserta['id'] == $peserta_id) {
                                            echo $peserta['nama'];
                                            break;
                                        }
                                    }
                                ?></li>
                            <?php endif; ?>
                            <?php if (!empty($station_id)): ?>
                                <li>Station: <?php 
                                    foreach ($stations_list as $station) {
                                        if ($station['id'] == $station_id) {
                                            echo $station['nama_station'];
                                            break;
                                        }
                                    }
                                ?></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                <?php else: ?>
                    <p class="text-danger"><strong>Semua data penilaian akan dihapus tanpa filter!</strong></p>
                <?php endif; ?>
                
                <p class="text-danger"><i class="fas fa-exclamation-circle"></i> 
                    Tindakan ini <strong>TIDAK DAPAT DIBATALKAN</strong>. Pastikan Anda telah membuat backup data.
                </p>
            </div>
            
            <form method="POST" action="delete_all_nilai.php" id="deleteForm">
                <input type="hidden" name="ujian_id" value="<?php echo $ujian_id; ?>">
                <input type="hidden" name="peserta_id" value="<?php echo $peserta_id; ?>">
                <input type="hidden" name="station_id" value="<?php echo $station_id; ?>">
                <input type="hidden" name="delete_type" value="all">
                <input type="hidden" name="confirm_delete" value="1">
                
                <div class="form-group">
                    <label for="confirm_text">Ketik "HAPUS" untuk konfirmasi:</label>
                    <input type="text" id="confirm_text" name="confirm_text" 
                           class="form-control" 
                           placeholder="Ketik HAPUS disini..." 
                           onkeyup="checkDeleteConfirmation()">
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">
                <i class="fas fa-times"></i> Batal
            </button>
            <button type="button" class="btn btn-danger" id="confirmDeleteBtn" disabled 
                    onclick="document.getElementById('deleteForm').submit()">
                <i class="fas fa-trash-alt"></i> Hapus Data
            </button>
        </div>
    </div>
</div>

    <!-- Detail Penilaian Modal -->
<?php if (isset($_GET['detail']) && !empty($detail_penilaian)): ?>
<div class="modal-overlay" id="detailModal" style="display: block;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Detail Penilaian</h3>
            <button type="button" class="close-btn" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <?php 
            // Cari data peserta, station, dan ujian
            $peserta_detail = null;
            foreach ($peserta_list as $p) {
                if ($p['id'] == $detail_peserta_id) {
                    $peserta_detail = $p;
                    break;
                }
            }
            
            $station_detail = null;
            foreach ($stations_list as $s) {
                if ($s['id'] == $detail_station_id) {
                    $station_detail = $s;
                    break;
                }
            }
            
            $ujian_detail = null;
            foreach ($ujian_list as $u) {
                if ($u['id'] == $detail_ujian_id) {
                    $ujian_detail = $u;
                    break;
                }
            }
            
            // Tentukan badge untuk global performance di modal
            $global_badge_modal = '';
            $global_text_modal = '';
            $global_icon_modal = '';
            
            if (!empty($global_performance) && $global_performance !== '') {
                switch($global_performance) {
                    case 'tidak_lulus':
                        $global_badge_modal = 'badge-danger';
                        $global_text_modal = 'Tidak Lulus';
                        $global_icon_modal = 'fas fa-times-circle';
                        break;
                    case 'borderline':
                        $global_badge_modal = 'badge-warning';
                        $global_text_modal = 'Borderline';
                        $global_icon_modal = 'fas fa-exclamation-triangle';
                        break;
                    case 'lulus':
                        $global_badge_modal = 'badge-success';
                        $global_text_modal = 'Lulus';
                        $global_icon_modal = 'fas fa-check-circle';
                        break;
                    default:
                        $global_badge_modal = 'badge-secondary';
                        $global_text_modal = 'Belum Dinilai';
                        $global_icon_modal = 'fas fa-clock';
                }
            } else {
                $global_badge_modal = 'badge-secondary';
                $global_text_modal = 'Belum Dinilai';
                $global_icon_modal = 'fas fa-clock';
            }
            ?>
            
            <div class="detail-header">
                <h4>
                    <?php echo $peserta_detail ? $peserta_detail['nama'] : 'Peserta Tidak Ditemukan'; ?> 
                    (<?php echo $peserta_detail ? $peserta_detail['nim'] : 'N/A'; ?>)
                </h4>
                <p>
                    <strong>Station:</strong> <?php echo $station_detail ? $station_detail['nama_station'] : 'Station Tidak Ditemukan'; ?> | 
                    <strong>Ujian:</strong> <?php echo $ujian_detail ? $ujian_detail['nama_ujian'] : 'Ujian Tidak Ditemukan'; ?> |
                    <strong>Global Performance:</strong> 
                    <span class="badge <?php echo $global_badge_modal; ?> global-performance-badge">
                        <i class="<?php echo $global_icon_modal; ?>"></i>
                        <?php echo $global_text_modal; ?>
                    </span>
                </p>
            </div>
            
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Aspek Penilaian</th>
                            <th>Nilai</th>
                            <th>Catatan</th>
                            <th>Penguji</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $total_nilai = 0;
                        $max_nilai = 0;
                        ?>
                        <?php foreach ($detail_penilaian as $index => $detail): ?>
                            <?php 
                            $total_nilai += $detail['nilai'];
                            $max_nilai += 2; // Asumsi maksimal nilai per aspek adalah 2
                            ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td>
                                    <strong><?php echo $detail['nama_aspek']; ?></strong>
                                    <?php if ($detail['nomor_urut']): ?>
                                        <br><small class="text-muted">Urutan: <?php echo $detail['nomor_urut']; ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="nilai-badge nilai-<?php echo $detail['nilai']; ?>">
                                        <?php echo $detail['nilai']; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($detail['catatan']): ?>
                                        <small><?php echo nl2br(htmlspecialchars($detail['catatan'])); ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td><small><?php echo $detail['penguji_username']; ?></small></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
    <tr>
        <td colspan="2"><strong>Total</strong></td>
        <td>
            <strong>
                <?php echo $total_nilai; ?>/<?php 
                // Ambil total_maksimal dari station
                $stmt = $pdo->prepare("SELECT total_maksimal FROM stations WHERE id = ?");
                $stmt->execute([$detail_station_id]);
                $station_maksimal = $stmt->fetch();
                echo $station_maksimal ? $station_maksimal['total_maksimal'] : $max_nilai; 
                ?>
            </strong>
        </td>
        <td colspan="2">
            <?php 
            $total_maksimal_value = $station_maksimal ? $station_maksimal['total_maksimal'] : $max_nilai;
            $persentase = $total_maksimal_value > 0 ? ($total_nilai / $total_maksimal_value) * 100 : 0;
            ?>
            <strong>Persentase: <?php echo number_format($persentase, 1); ?>%</strong>
        </td>
    </tr>
</tfoot>
                </table>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeModal()">Tutup</button>
        </div>
    </div>
</div>
<?php endif; ?>

   <!-- Hasil Penilaian -->
<div class="card">
    <h3>Hasil Penilaian</h3>
    
    <?php if (empty($hasil_penilaian)): ?>
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i>
            <?php echo empty($where_conditions) ? 'Belum ada data penilaian.' : 'Tidak ada data penilaian dengan filter yang dipilih.'; ?>
        </div>
    <?php else: ?>
        <div class="table-container">
    <table class="data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Peserta</th>
                <th>Ujian</th>
                <th>Station</th>
                <th>Aspek</th>
                <th>Total Nilai</th>
                <th>Global Performance</th>
                <th>Catatan</th>
                <th>Penguji</th>
                <th>Waktu</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            // Preload semua penguji ID sekaligus untuk optimasi 
            $penguji_map = [];
            if (!empty($hasil_penilaian)) {
                $penguji_usernames = array_unique(array_column($hasil_penilaian, 'penguji_username'));
                
                // Filter out null/empty values
                $penguji_usernames = array_filter($penguji_usernames, function($username) {
                    return !empty($username) && $username !== null;
                });
                
                if (!empty($penguji_usernames)) {
                    $placeholders = str_repeat('?,', count($penguji_usernames) - 1) . '?';
                    $penguji_stmt = $pdo->prepare("SELECT id, username FROM users WHERE username IN ($placeholders)");
                    $penguji_stmt->execute(array_values($penguji_usernames)); // Gunakan array_values untuk memastikan urutan
                    
                    foreach ($penguji_stmt->fetchAll() as $p) {
                        $penguji_map[$p['username']] = $p['id'];
                    }
                }
            }
            
            // Preload catatan untuk semua hasil penilaian sekaligus 
            $catatan_data_map = [];
            if (!empty($hasil_penilaian)) {
                $catatan_conditions = []; 
                $catatan_params = []; 
                
                foreach ($hasil_penilaian as $hasil) {
                    $penguji_id = $penguji_map[$hasil['penguji_username']] ?? null;
                    if ($penguji_id) {
                        $catatan_conditions[] = "(n.ujian_id = ? AND n.peserta_id = ? AND n.station_id = ? AND n.penguji_id = ?)";
                        $catatan_params[] = $hasil['ujian_id'];
                        $catatan_params[] = $hasil['peserta_id'];
                        $catatan_params[] = $hasil['station_id'];
                        $catatan_params[] = $penguji_id;
                    }
                }
                
                if (!empty($catatan_conditions)) {
                    $catatan_query = "
                        SELECT n.ujian_id, n.peserta_id, n.station_id, n.penguji_id, n.catatan, ap.nama_aspek
                        FROM penilaian n
                        INNER JOIN aspek_penilaian ap ON n.aspek_id = ap.id
                        WHERE (" . implode(" OR ", $catatan_conditions) . ")
                        AND n.catatan IS NOT NULL AND n.catatan != ''
                        ORDER BY n.ujian_id, n.peserta_id, n.station_id, n.penguji_id, ap.nomor_urut
                    ";
                    
                    try {
                        $catatan_stmt = $pdo->prepare($catatan_query);
                        $catatan_stmt->execute($catatan_params);
                        $all_catatan = $catatan_stmt->fetchAll();
                        
                        // Group catatan by composite key
                        foreach ($all_catatan as $catatan) {
                            $key = $catatan['ujian_id'] . '_' . $catatan['peserta_id'] . '_' . $catatan['station_id'] . '_' . $catatan['penguji_id'];
                            if (!isset($catatan_data_map[$key])) {
                                $catatan_data_map[$key] = [];
                            }
                            $catatan_data_map[$key][] = $catatan;
                        }
                    } catch (PDOException $e) {
                        
                        error_log("Error loading catatan: " . $e->getMessage());
                    }
                }
            }
            ?>
            
            <?php foreach ($hasil_penilaian as $index => $hasil): ?>
                <?php
                // Ambil catatan dari preloaded data
                $penguji_id = $penguji_map[$hasil['penguji_username']] ?? null;
                $catatan_data = [];
                if ($penguji_id) {
                    $key = $hasil['ujian_id'] . '_' . $hasil['peserta_id'] . '_' . $hasil['station_id'] . '_' . $penguji_id;
                    $catatan_data = $catatan_data_map[$key] ?? [];
                }
                
                // Tentukan badge untuk global performance
                $global_badge = '';
                $global_text = '';
                $global_icon = '';
                
                if (!empty($hasil['global_performance'])) {
                    switch($hasil['global_performance']) {
                        case 'tidak_lulus':
                            $global_badge = 'badge-danger';
                            $global_text = 'Tidak Lulus';
                            $global_icon = 'fas fa-times-circle';
                            break;
                        case 'borderline':
                            $global_badge = 'badge-warning';
                            $global_text = 'Borderline';
                            $global_icon = 'fas fa-exclamation-triangle';
                            break;
                        case 'lulus':
                            $global_badge = 'badge-success';
                            $global_text = 'Lulus';
                            $global_icon = 'fas fa-check-circle';
                            break;
                        default:
                            $global_badge = 'badge-secondary';
                            $global_text = 'Belum Dinilai';
                            $global_icon = 'fas fa-clock';
                    }
                } else {
                    $global_badge = 'badge-secondary';
                    $global_text = 'Belum Dinilai';
                    $global_icon = 'fas fa-clock';
                }
                ?>
                <tr>
                    <td><?php echo $index + 1; ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($hasil['peserta_nama']); ?></strong>
                        <br>
                        <small class="text-muted">
                            <?php echo htmlspecialchars($hasil['nim']); ?> | <?php echo htmlspecialchars($hasil['program_studi']); ?>
                        </small>
                    </td>
                    <td>
                        <?php echo htmlspecialchars($hasil['nama_ujian']); ?>
                    </td>
                    <td>
                        <?php echo htmlspecialchars($hasil['nama_station']); ?>
                        <?php if ($hasil['station_deskripsi']): ?>
                            <br>
                            <small class="text-muted"><?php echo truncateText(htmlspecialchars($hasil['station_deskripsi']), 50); ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge badge-info"><?php echo $hasil['total_aspek']; ?> aspek</span>
                    </td>
                    <td>
                        
                        <span class="nilai-badge nilai-<?php echo $hasil['total_nilai']; ?>">
                            <?php echo $hasil['total_nilai']; ?>/<?php echo $hasil['total_maksimal']; ?>
                        </span>
                        <?php if ($hasil['total_maksimal'] > 0): ?>
                            <br>
                            <small class="text-muted">
                                (<?php echo number_format(($hasil['total_nilai'] / $hasil['total_maksimal']) * 100, 1); ?>%)
                            </small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge <?php echo $global_badge; ?> global-performance-badge">
                            <i class="<?php echo $global_icon; ?>"></i>
                            <?php echo $global_text; ?>
                        </span>
                    </td>
                    <td>
                        <div class="catatan-preview">
                            <?php if (!empty($catatan_data)): ?>
                                <?php 
                                $valid_catatan_count = 0;
                                foreach ($catatan_data as $catatan_item): 
                                    if (!empty(trim($catatan_item['catatan']))):
                                        $valid_catatan_count++;
                                        if ($valid_catatan_count <= 2): // Tampilkan maksimal 2 catatan preview ?>
                                            <div class="catatan-preview-item">
                                                <strong><?php echo htmlspecialchars($catatan_item['nama_aspek']); ?>:</strong>
                                                <span class="catatan-text"><?php echo truncateText(htmlspecialchars($catatan_item['catatan']), 30); ?></span>
                                            </div>
                                        <?php endif;
                                    endif;
                                endforeach; 
                                
                                if ($valid_catatan_count > 2): ?>
                                    <div class="catatan-more">
                                        <small class="text-muted">+<?php echo $valid_catatan_count - 2; ?> catatan lainnya</small>
                                    </div>
                                <?php endif;
                                
                                if ($valid_catatan_count === 0): ?>
                                    <span class="text-muted"><em>Tidak ada catatan</em></span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="text-muted"><em>Tidak ada catatan</em></span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td>
                        <small><?php echo htmlspecialchars($hasil['penguji_username']); ?></small>
                    </td>
                    <td>
                        <small><?php echo formatTanggal($hasil['waktu_penilaian']); ?></small>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <a href="?detail=1&detail_peserta=<?php echo $hasil['peserta_id']; ?>&detail_station=<?php echo $hasil['station_id']; ?>&detail_ujian=<?php echo $hasil['ujian_id']; ?>&<?php echo http_build_query($_GET); ?>" 
                               class="btn btn-sm btn-info" title="Lihat Detail">
                                <i class="fas fa-eye"></i>
                            </a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
        
        <div class="table-info">
            Total: <strong><?php echo count($hasil_penilaian); ?></strong> hasil penilaian
        </div>
    <?php endif; ?>
</div>

<!-- Global Performance -->
<div style="margin-top: 1rem; padding: 1rem; background: #f8f9fa; border-radius: 8px; font-size: 0.85rem;">
    <strong>Global Performance:</strong>
    <div style="display: flex; gap: 1rem; margin-top: 0.5rem; flex-wrap: wrap;">
        <span class="badge badge-success global-performance-badge">
            <i class="fas fa-check-circle"></i> Lulus
        </span>
        <span class="badge badge-warning global-performance-badge">
            <i class="fas fa-exclamation-triangle"></i> Borderline
        </span>
        <span class="badge badge-danger global-performance-badge">
            <i class="fas fa-times-circle"></i> Tidak Lulus
        </span>
        <span class="badge badge-secondary global-performance-badge">
            <i class="fas fa-clock"></i> Belum Dinilai
        </span>
    </div>
</div>

<style>
    /* Export Modal Styles */
.export-actions {
    margin: 1rem 0;
    text-align: right;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #218838;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
}

.form-control {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 4px;
    font-size: 0.9rem;
}

    /* Global Performance Badge Styles */
.global-performance-badge {
    padding: 0.5rem 0.8rem;
    border-radius: 15px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    border: 1px solid transparent;
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
}

.badge-danger {
    background: #f8d7da;
    color: #721c24;
    border-color: #f5c6cb;
}

.badge-warning {
    background: #fff3cd;
    color: #856404;
    border-color: #ffeaa7;
}

.badge-success {
    background: #d4edda;
    color: #155724;
    border-color: #c3e6cb;
}

.badge-secondary {
    background: #e2e3e5;
    color: #383d41;
    border-color: #d6d8db;
}
  /* Catatan Preview Styles */
.catatan-preview {
    max-width: 200px;
    max-height: 80px;
    overflow-y: auto;
    font-size: 0.8rem;
}

.catatan-preview-item {
    margin-bottom: 0.25rem;
    padding-bottom: 0.25rem;
    border-bottom: 1px solid #f0f0f0;
}

.catatan-preview-item:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.catatan-preview-item strong {
    display: block;
    font-size: 0.75rem;
    color: #495057;
    margin-bottom: 0.1rem;
}

.catatan-text {
    color: #6c757d;
    line-height: 1.3;
    word-wrap: break-word;
}

.catatan-more {
    margin-top: 0.25rem;
    text-align: center;
}

/* Scrollbar untuk catatan preview */
.catatan-preview::-webkit-scrollbar {
    width: 4px;
}

.catatan-preview::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

.catatan-preview::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
}

.catatan-preview::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Badge styles */
.badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
    font-weight: 500;
}

.badge-info {
    background: #3498db;
    color: white;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    border-radius: 8px;
    padding: 1.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: #3498db;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.5rem;
}

.stat-info h3 {
    margin: 0;
    font-size: 1.8rem;
    color: #2c3e50;
}

.stat-info p {
    margin: 0.25rem 0 0 0;
    color: #7f8c8d;
    font-size: 0.9rem;
}

.filter-form {
    margin-top: 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: #e74c3c; color: white; }
.nilai-2 { background: #f39c12; color: white; }
.nilai-3 { background: #f39c12; color: white; }
.nilai-4 { background: #27ae60; color: white; }
.nilai-5 { background: #27ae60; color: white; }
.nilai-6 { background: #27ae60; color: white; }

/* Modal Styles */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    border-radius: 8px;
    width: 90%;
    max-width: 800px;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    padding: 1.5rem;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
}

.close-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #6c757d;
}

.modal-body {
    padding: 1.5rem;
}

.modal-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid #e9ecef;
    text-align: right;
}

.detail-header {
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #e9ecef;
}

.detail-header h4 {
    margin: 0 0 0.5rem 0;
    color: #2c3e50;
}

.detail-header p {
    margin: 0;
    color: #6c757d;
}

/* Responsive */
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr 1fr;
    }
    
    .stat-card {
        flex-direction: column;
        text-align: center;
    }
    
    .filter-form .form-row {
        grid-template-columns: 1fr;
    }
    
    .modal-content {
        width: 95%;
        margin: 1rem;
    }
}

.nilai-badge.nilai-total {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
    font-size: 0.85rem;
    padding: 0.4rem 0.8rem;
}

.text-muted small {
    font-size: 0.75rem;
    color: #0b76d3ff;
}

/* Style untuk tabel hasil penilaian */
.table-container {
    overflow-x: auto;
    margin-top: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    background: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    font-size: 0.9rem;
}

.data-table th {
    background: linear-gradient(135deg, #4b92ddff 0%, #3039b8ff 110%);
    color: white;
    padding: 1rem 0.5rem;
    text-align: center;
    font-weight: 600;
    border: 1px solid #3039b8ff;
    vertical-align: middle;
}

.data-table td {
    padding: 0.75rem 0.5rem;
    border: 1px solid #2c7fd2ff;
    vertical-align: middle;
    text-align: center;
}

.data-table tr:nth-child(even) {
    background: #f8f9fa;
}

.data-table tr:hover {
    background: #e9ecef;
}

/* Style khusus untuk konten dalam sel */
.data-table strong {
    display: block;
    margin-bottom: 0.25rem;
}

.data-table small {
    font-size: 0.8rem;
}

.data-table .text-muted {
    color: #6c757d !important;
}

/* Style untuk badge */
.badge {
    padding: 0.4rem 0.8rem;
    border-radius: 15px;
    font-size: 0.8rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid transparent;
}

.badge-info {
    background: #3498db;
    color: white;
}

/* Style untuk nilai badge */
.nilai-badge {
    display: inline-block;
    padding: 0.5rem 0.8rem;
    border-radius: 20px;
    font-weight: 700;
    font-size: 0.85rem;
    text-align: center;
    min-width: 70px;
    border: 1px solid transparent;
    background: #27ae60;
    color: white;
}

/* Style untuk Global Performance Badge */
.global-performance-badge {
    padding: 0.5rem 0.8rem;
    border-radius: 15px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    border: 1px solid transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.3rem;
    min-width: 100px;
}

.badge-danger {
    background: #f8d7da;
    color: #721c24;
    border-color: #f5c6cb;
}

.badge-warning {
    background: #fff3cd;
    color: #856404;
    border-color: #ffeaa7;
}

.badge-success {
    background: #d4edda;
    color: #155724;
    border-color: #c3e6cb;
}

.badge-secondary {
    background: #e2e3e5;
    color: #383d41;
    border-color: #d6d8db;
}

/* Style untuk catatan preview */
.catatan-preview {
    max-width: 200px;
    max-height: 80px;
    overflow-y: auto;
    font-size: 0.8rem;
    text-align: left;
    margin: 0 auto;
    padding: 0.5rem;
    background: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e9ecef;
}

.catatan-preview-item {
    margin-bottom: 0.5rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #dee2e6;
}

.catatan-preview-item:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.catatan-preview-item strong {
    display: block;
    font-size: 0.75rem;
    color: #495057;
    margin-bottom: 0.25rem;
}

.catatan-text {
    color: #6c757d;
    line-height: 1.3;
    word-wrap: break-word;
}

.catatan-more {
    margin-top: 0.5rem;
    text-align: center;
    padding-top: 0.5rem;
    border-top: 1px dashed #dee2e6;
}

/* Style untuk tombol aksi */
.action-buttons {
    display: flex;
    justify-content: center;
    gap: 0.5rem;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.5rem 0.8rem;
    border: none;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.3s;
    min-width: 60px;
}

.btn-sm {
    padding: 0.4rem 0.7rem;
    font-size: 0.75rem;
    min-width: 50px;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
    transform: translateY(-1px);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

/* Scrollbar untuk catatan preview */
.catatan-preview::-webkit-scrollbar {
    width: 4px;
}

.catatan-preview::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

.catatan-preview::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
}

.catatan-preview::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Responsive design untuk tabel */
@media (max-width: 1200px) {
    .data-table {
        font-size: 0.85rem;
    }
    
    .data-table th,
    .data-table td {
        padding: 0.6rem 0.4rem;
    }
}

@media (max-width: 992px) {
    .table-container {
        font-size: 0.8rem;
    }
    
    .data-table th:nth-child(3),
    .data-table td:nth-child(3),
    .data-table th:nth-child(9),
    .data-table td:nth-child(9) {
        display: none;
    }
}

@media (max-width: 768px) {
    .data-table {
        font-size: 0.75rem;
    }
    
    .data-table th,
    .data-table td {
        padding: 0.5rem 0.3rem;
    }
    
    .data-table th:nth-child(4),
    .data-table td:nth-child(4),
    .data-table th:nth-child(5),
    .data-table td:nth-child(5),
    .data-table th:nth-child(10),
    .data-table td:nth-child(10) {
        display: none;
    }
    
    .nilai-badge {
        padding: 0.4rem 0.6rem;
        font-size: 0.75rem;
        min-width: 60px;
    }
    
    .global-performance-badge {
        padding: 0.4rem 0.6rem;
        font-size: 0.7rem;
        min-width: 80px;
    }
    
    .btn-sm {
        padding: 0.3rem 0.5rem;
        font-size: 0.7rem;
        min-width: 45px;
    }
    
    .catatan-preview {
        max-width: 150px;
        font-size: 0.75rem;
    }
}

/* Style untuk info footer tabel */
.table-info {
    padding: 1rem;
    background: #f8f9fa;
    border-top: 1px solid #dee2e6;
    text-align: center;
    font-size: 0.9rem;
    color: #6c757d;
    border-radius: 0 0 8px 8px;
}

/* Tombol Hapus Semua */
.btn-danger {
    background: #dc3545;
    color: white;
    border: 1px solid #dc3545;
    margin-left: 10px;
}

.btn-danger:hover:not(:disabled) {
    background: #c82333;
    border-color: #bd2130;
}

.btn-danger:disabled {
    background: #e9ecef;
    color: #6c757d;
    border-color: #dee2e6;
    cursor: not-allowed;
}

/* Modal hapus khusus */
#deleteConfirmationModal .modal-content {
    max-width: 500px;
}

.filter-info {
    background: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
    margin: 10px 0;
    border-left: 4px solid #dc3545;
}

.filter-info ul {
    margin: 5px 0 0 20px;
    padding: 0;
}

.filter-info li {
    margin-bottom: 3px;
}

.text-danger strong {
    color: #dc3545;
}
</style>


<script>
// Export Modal Functions
function showExportOptions() {
    document.getElementById('exportModal').style.display = 'flex';
}

function closeExportModal() {
    document.getElementById('exportModal').style.display = 'none';
}

function toggleExportOptions() {
    const exportType = document.getElementById('export_type').value;
    const stationSelect = document.getElementById('station_select_group');
    
    if (exportType === 'per_station') {
        stationSelect.style.display = 'block';
    } else {
        stationSelect.style.display = 'none';
    }
}

function submitExport() {
    document.getElementById('exportForm').submit();
}

// Close modal when clicking outside
document.addEventListener('click', function(e) {
    if (e.target.id === 'exportModal') {
        closeExportModal();
    }
});

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeExportModal();
    }
});
</script>

<script>
function closeModal() {
    // Remove detail parameters from URL
    const url = new URL(window.location);
    url.searchParams.delete('detail');
    url.searchParams.delete('detail_peserta');
    url.searchParams.delete('detail_station');
    url.searchParams.delete('detail_ujian');
    window.location.href = url.toString();
}

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});

// Close modal when clicking outside
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        closeModal();
    }
});


</script>

<script>
// Fungsi untuk modal hapus semua
function showDeleteConfirmation() {
    document.getElementById('deleteConfirmationModal').style.display = 'flex';
}

function closeDeleteModal() {
    document.getElementById('deleteConfirmationModal').style.display = 'none';
    document.getElementById('confirm_text').value = '';
    document.getElementById('confirmDeleteBtn').disabled = true;
}

function checkDeleteConfirmation() {
    const confirmText = document.getElementById('confirm_text').value;
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    
    if (confirmText.toUpperCase() === 'HAPUS') {
        confirmBtn.disabled = false;
    } else {
        confirmBtn.disabled = true;
    }
}

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && document.getElementById('deleteConfirmationModal').style.display === 'flex') {
        closeDeleteModal();
    }
});

// Close modal when clicking outside
document.addEventListener('click', function(e) {
    if (e.target.id === 'deleteConfirmationModal') {
        closeDeleteModal();
    }
});
</script>

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