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

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

$penguji_id = $_SESSION['user_id'];
$ujian_id = $_GET['ujian_id'] ?? null;
$station_id = $_GET['station_id'] ?? null;

if (!$ujian_id || !$station_id) {
    redirect('dashboard_penguji.php');
}

// Validasi apakah station ini diassign ke penguji dengan peran yang benar
$stmt = $pdo->prepare("
    SELECT 
        s.*, 
        u.nama_ujian, 
        us.urutan,
        ps.peran
    FROM stations s 
    INNER JOIN ujian_stations us ON s.id = us.station_id 
    INNER JOIN ujian u ON us.ujian_id = u.id 
    INNER JOIN penguji_station ps ON s.id = ps.station_id 
    WHERE s.id = ? 
    AND us.ujian_id = ? 
    AND ps.penguji_id = ? 
    AND ps.ujian_id = ?
    AND u.status = 'aktif'
");
$stmt->execute([$station_id, $ujian_id, $penguji_id, $ujian_id]);
$station = $stmt->fetch();

// Simpan total_maksimal
$total_maksimal = $station['total_maksimal'] ?? 0;

if (!$station) {
    redirect('dashboard_penguji.php');
}

// ============================================
// [PERBAIKAN] Ambil peserta dengan status penilaian yang lebih akurat
// ============================================
$stmt = $pdo->prepare("
    SELECT 
        p.*,
        -- Hitung jumlah aspek yang sudah dinilai (nilai IS NOT NULL)
        (
            SELECT COUNT(*) 
            FROM penilaian n 
            WHERE n.peserta_id = p.id 
            AND n.station_id = ? 
            AND n.ujian_id = ? 
            AND n.penguji_id = ?
            AND n.nilai IS NOT NULL
        ) as jumlah_aspek_dinilai,
        -- Hitung total aspek untuk station ini
        (
            SELECT COUNT(*) 
            FROM aspek_penilaian ap 
            WHERE ap.station_id = ?
        ) as total_aspek,
        -- Ambil status penilaian terbaru
        (
            SELECT n.status_penilaian 
            FROM penilaian n 
            WHERE n.peserta_id = p.id 
            AND n.station_id = ? 
            AND n.ujian_id = ? 
            AND n.penguji_id = ?
            ORDER BY n.created_at DESC 
            LIMIT 1
        ) as status_penilaian
    FROM peserta p 
    INNER JOIN peserta_station ps ON p.id = ps.peserta_id 
    WHERE ps.station_id = ? AND ps.ujian_id = ?
    ORDER BY p.nama
");
$stmt->execute([
    $station_id, $ujian_id, $penguji_id,  // untuk jumlah_aspek_dinilai
    $station_id,                           // untuk total_aspek
    $station_id, $ujian_id, $penguji_id,  // untuk status_penilaian
    $station_id, $ujian_id                 // untuk WHERE
]);
$peserta_list = $stmt->fetchAll();

// Ambil penilaian terbaru untuk penguji ini di station ini
$stmt = $pdo->prepare("
    SELECT 
        p.nama as peserta_nama,
        p.nim,
        s.nama_station,
        SUM(n.nilai) as total_nilai,
        MAX(n.created_at) as terakhir_dinilai,
        pg.global_performance
    FROM penilaian n
    INNER JOIN peserta p ON n.peserta_id = p.id
    INNER JOIN stations s ON n.station_id = s.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 n.penguji_id = ? AND n.ujian_id = ? AND n.station_id = ?
    GROUP BY p.id, p.nama, p.nim, s.nama_station, pg.global_performance
    ORDER BY terakhir_dinilai DESC
    LIMIT 10
");
$stmt->execute([$penguji_id, $ujian_id, $station_id]);
$penilaian_terbaru = $stmt->fetchAll();

// Ambil data penguji dari database berdasarkan session
$stmt = $pdo->prepare("
    SELECT p.nama 
    FROM penguji p 
    WHERE p.id = ? OR p.nip IN (SELECT username FROM users WHERE id = ?)
");
$stmt->execute([$penguji_id, $penguji_id]);
$penguji_data = $stmt->fetch();

$nama_penguji = $penguji_data['nama'] ?? $_SESSION['user_name'];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Peserta - OSCE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f6fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        
        .header h1 {
            font-size: 1.8rem;
            margin-bottom: 0.5rem;
            text-align: center;
        }
        
        .penguji-info {
            text-align: center;
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }
        
        .station-info {
            background: rgba(255, 255, 255, 0.2);
            padding: 1rem;
            border-radius: 8px;
            text-align: center;
            backdrop-filter: blur(10px);
        }
        
        .station-name {
            font-size: 1.3rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .station-desc {
            font-size: 1rem;
            opacity: 0.9;
        }
        
        .content-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
        }
        
        .section-title {
            color: #2c3e50;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e9ecef;
            font-size: 1.4rem;
        }
        
        .peserta-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1rem;
            margin-top: 1.5rem;
        }
        
        .peserta-card {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 1.5rem;
            transition: all 0.3s ease;
            text-decoration: none;
            color: inherit;
            display: block;
            position: relative;
        }
        
        .peserta-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-color: #3498db;
        }
        
        /* Status-based card borders */
        .peserta-card.sudah-dinilai {
            border-color: #27ae60;
            background: #f8fff9;
        }
        
        .peserta-card.sedang-dinilai {
            border-color: #17a2b8;
            background: #f0f9ff;
        }
        
        .peserta-card.belum-dinilai {
            border-color: #e74c3c;
            background: #fff;
        }
        
        .peserta-info {
            margin-bottom: 1rem;
        }
        
        .peserta-nim {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0.25rem;
            font-family: monospace;
        }
        
        .peserta-nama {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .status-badge {
            position: absolute;
            top: 1rem;
            right: 1rem;
        }
        
        .badge {
            padding: 0.4rem 0.8rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
        }
        
        .badge-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .badge-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .badge-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .badge-info i {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .action-btn {
            display: inline-block;
            padding: 0.6rem 1.2rem;
            background: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
            text-align: center;
            width: 100%;
        }
        
        .action-btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }
        
        .action-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
        }
        
        .nav-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .btn-secondary {
            background: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .info-text {
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #bdc3c7;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header {
                padding: 1.5rem;
            }
            
            .header h1 {
                font-size: 1.4rem;
            }
            
            .peserta-grid {
                grid-template-columns: 1fr;
            }
            
            .nav-actions {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .btn {
                justify-content: center;
            }
        }

        /* Style untuk tabel penilaian terbaru */
        .table-container {
            overflow-x: auto;
            margin-top: 1rem;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .data-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            font-size: 0.9rem;
            vertical-align: middle;
        }
        
        .data-table tr:last-child td {
            border-bottom: none;
        }
        
        .data-table tr:hover {
            background: #f8f9fa;
        }
        
        .data-table code {
            background: #f8f9fa;
            padding: 0.2rem 0.4rem;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
        }
        
        .nilai-badge {
            display: inline-block;
            padding: 0.4rem 0.8rem;
            border-radius: 20px;
            font-weight: 700;
            font-size: 0.9rem;
            text-align: center;
            min-width: 50px;
        }
        
        .nilai-total {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }
        
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin: 1rem 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .alert-info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        
        .alert i {
            font-size: 1.2rem;
        }
        
        .text-muted {
            color: #6c757d !important;
        }
        
        .btn-edit-penilaian {
            display: inline-flex;
            align-items: center;
            gap: 0.4rem;
            padding: 0.4rem 0.8rem;
            background: #17a2b8;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-edit-penilaian:hover {
            background: #138496;
            transform: translateY(-1px);
            color: white;
        }
        
        .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-secondary {
            background: #e2e3e5;
            color: #383d41;
            border-color: #d6d8db;
        }
        
        /* Statistik Peserta */
        .statistik-peserta {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .stat-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            background: white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .stat-total {
            background: #3498db;
            color: white;
        }
        
        .stat-sudah {
            background: #27ae60;
            color: white;
        }
        
        .stat-sedang {
            background: #17a2b8;
            color: white;
        }
        
        .stat-belum {
            background: #e74c3c;
            color: white;
        }
        
        /* Search Box */
        .search-box {
            position: relative;
            display: inline-block;
        }
        
        .search-input {
            padding: 8px 35px 8px 35px;
            border: 1px solid #030303;
            border-radius: 30px;
            font-size: 0.85rem;
            width: 250px;
            transition: all 0.3s;
            background: white;
        }
        
        .search-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
            width: 280px;
        }
        
        .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #0e21f8;
            font-size: 0.9rem;
        }
        
        .search-clear {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #070707;
            cursor: pointer;
            font-size: 1.2rem;
            font-weight: bold;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .search-clear:hover {
            color: #e74c3c;
        }
        
        .search-highlight {
            background-color: #89df67;
            padding: 0 2px;
            border-radius: 3px;
        }
        
        .peserta-card.hidden {
            display: none;
        }
        
        .empty-search {
            text-align: center;
            padding: 2rem;
            color: #080808;
            background: #f8f9fa;
            border-radius: 10px;
            margin-top: 1rem;
        }
        
        .empty-search i {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #070707;
        }
        
        @media (max-width: 768px) {
            .section-title {
                flex-direction: column;
                align-items: stretch !important;
            }
            
            .statistik-peserta {
                justify-content: space-between;
            }
            
            .stat-badge {
                flex: 1;
                justify-content: center;
                font-size: 0.7rem;
                padding: 5px 8px;
            }
            
            .search-box {
                width: 100%;
            }
            
            .search-input {
                width: 100%;
            }
            
            .search-input:focus {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>Lembar Pengujian OSCE - FKG UMS</h1>
            <div class="penguji-info">
                <strong>Anda login sebagai:</strong>
                <div class="penguji-nama"><?php echo htmlspecialchars($nama_penguji); ?></div>
            </div>
            <div class="station-info">
                <div class="station-name"><?php echo $station['nama_station']; ?></div>
                <div class="station-desc">Station <?php echo $station['urutan']; ?> - <?php echo $station['nama_ujian']; ?></div>
            </div>
        </div>

        <!-- Navigation -->
        <div class="nav-actions">
            <a href="dashboard_penguji.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
            </a>
        </div>

        <!-- Daftar Peserta -->
        <div class="content-card">
            <div class="section-title" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                <div>
                    <i class="fas fa-users"></i> Lihat Daftar Peserta
                </div>
                
                <div style="display: flex; gap: 15px; flex-wrap: wrap; align-items: center;">
                    <!-- Statistik -->
                    <?php 
$total_peserta = count($peserta_list);
$sudah_dinilai = 0;
$sedang_dinilai = 0;
$belum_dinilai = 0;

foreach ($peserta_list as $p) {
    $jumlah_aspek_dinilai = $p['jumlah_aspek_dinilai'] ?? 0;
    $total_aspek = $p['total_aspek'] ?? 0;
    $status_penilaian = $p['status_penilaian'] ?? '';
    
    if ($total_aspek > 0 && $jumlah_aspek_dinilai >= $total_aspek) {
        $sudah_dinilai++;
    } 
    elseif ($jumlah_aspek_dinilai > 0 || $status_penilaian == 'mulai_penilaian') {
        $sedang_dinilai++;
    } 
    else {
        $belum_dinilai++;
    }
}
?>
                    <div class="statistik-peserta">
                        <span class="stat-badge stat-total">
                            <i class="fas fa-users"></i> Total: <?php echo $total_peserta; ?>
                        </span>
                        <span class="stat-badge stat-sudah">
                            <i class="fas fa-check-circle"></i> Sudah: <?php echo $sudah_dinilai; ?>
                        </span>
                        <span class="stat-badge stat-sedang">
                            <i class="fas fa-spinner fa-pulse"></i> Sedang: <?php echo $sedang_dinilai; ?>
                        </span>
                        <span class="stat-badge stat-belum">
                            <i class="fas fa-clock"></i> Belum: <?php echo $belum_dinilai; ?>
                        </span>
                    </div>
                    
                    <!-- Search Box -->
                    <div class="search-box">
                        <input type="text" id="searchPeserta" class="search-input" placeholder="Cari nama atau NIM..." onkeyup="filterPeserta()">
                        <i class="fas fa-search search-icon"></i>
                        <button type="button" class="search-clear" onclick="clearSearch()" style="display: none;">×</button>
                    </div>
                </div>
            </div>
            
            <p class="info-text">
                <strong>Klik nama peserta untuk melakukan penilaian. Pastikan nama yang dipilih sesuai dengan kandidat yang masuk ke ruang pengujian.</strong>
            </p>

            <?php if (empty($peserta_list)): ?>
                <div class="empty-state">
                    <i class="fas fa-user-friends"></i>
                    <h3>Tidak ada peserta</h3>
                    <p>Belum ada peserta yang diassign ke station ini.</p>
                </div>
            <?php else: ?>
                <div class="peserta-grid">
    <?php foreach ($peserta_list as $peserta): 
        // Tentukan status berdasarkan data
        $jumlah_aspek_dinilai = $peserta['jumlah_aspek_dinilai'] ?? 0;
        $total_aspek = $peserta['total_aspek'] ?? 0;
        $status_penilaian = $peserta['status_penilaian'] ?? '';
        
        // Logika penentuan status
        if ($total_aspek > 0 && $jumlah_aspek_dinilai >= $total_aspek) {
            // SEMUA aspek sudah dinilai (selesai)
            $card_class = 'sudah-dinilai';
            $status_text = 'Sudah Dinilai';
            $status_class = 'badge-success';
            $status_icon = 'fas fa-check-circle';
            $btn_text = '<i class="fas fa-edit"></i> Edit Penilaian';
        } 
        elseif ($jumlah_aspek_dinilai > 0 && $jumlah_aspek_dinilai < $total_aspek) {
            // Sebagian aspek sudah dinilai (belum selesai)
            $card_class = 'sedang-dinilai';
            $status_text = 'Sedang Dinilai';
            $status_class = 'badge-info';
            $status_icon = 'fas fa-spinner fa-pulse';
            $btn_text = '<i class="fas fa-play-circle"></i> Lanjutkan Penilaian';
        }
        elseif ($status_penilaian == 'mulai_penilaian' && $jumlah_aspek_dinilai == 0) {
            // Sudah klik mulai tapi belum ada nilai aspek
            $card_class = 'sedang-dinilai';
            $status_text = 'Sedang Dinilai';
            $status_class = 'badge-info';
            $status_icon = 'fas fa-spinner fa-pulse';
            $btn_text = '<i class="fas fa-play-circle"></i> Lanjutkan Penilaian';
        }
        else {
            // Belum dimulai sama sekali
            $card_class = 'belum-dinilai';
            $status_text = 'Belum Dinilai';
            $status_class = 'badge-warning';
            $status_icon = 'fas fa-clock';
            $btn_text = '<i class="fas fa-play-circle"></i> Mulai Penilaian';
        }
    ?>
        <a href="penilaian_detail.php?ujian_id=<?php echo $ujian_id; ?>&station_id=<?php echo $station_id; ?>&peserta_id=<?php echo $peserta['id']; ?>" 
           class="peserta-card <?php echo $card_class; ?>">
            
            <div class="peserta-info">
                <div class="peserta-nim"><?php echo htmlspecialchars($peserta['nim']); ?></div>
                <div class="peserta-nama"><?php echo htmlspecialchars($peserta['nama']); ?></div>
            </div>
            
            <div class="status-badge">
                <span class="badge <?php echo $status_class; ?>">
                    <i class="<?php echo $status_icon; ?>"></i> <?php echo $status_text; ?>
                </span>
            </div>
            
            <button class="action-btn">
                <?php echo $btn_text; ?>
            </button>
        </a>
    <?php endforeach; ?>
</div>
            <?php endif; ?>
        </div>

        <!-- Penilaian Terbaru -->
        <div class="content-card">
            <h2 class="section-title">
                <i class="fas fa-history"></i> Penilaian Terbaru
                <span style="float: right; font-size: 0.9rem; font-weight: normal;">
                    <?php 
                    $total_peserta = count($peserta_list);
                    $sudah_dinilai = 0;
                    $sedang_dinilai = 0;
                    $belum_dinilai = 0;
                    
                    foreach ($peserta_list as $p) {
                        if ($p['sudah_dinilai']) {
                            $sudah_dinilai++;
                        } else {
                            $status_penilaian = $p['status_penilaian'] ?? '';
                            if ($status_penilaian == 'mulai_penilaian') {
                                $sedang_dinilai++;
                            } else {
                                $belum_dinilai++;
                            }
                        }
                    }
                    ?>
                    <span class="badge" style="background: #3498db; color: white; margin-left: 10px;">
                        <i class="fas fa-users"></i> Total: <?php echo $total_peserta; ?>
                    </span>
                    <span class="badge" style="background: #27ae60; color: white; margin-left: 5px;">
                        <i class="fas fa-check-circle"></i> Sudah: <?php echo $sudah_dinilai; ?>
                    </span>
                    <span class="badge" style="background: #17a2b8; color: white; margin-left: 5px;">
                        <i class="fas fa-spinner fa-pulse"></i> Sedang: <?php echo $sedang_dinilai; ?>
                    </span>
                    <span class="badge" style="background: #e74c3c; color: white; margin-left: 5px;">
                        <i class="fas fa-clock"></i> Belum: <?php echo $belum_dinilai; ?>
                    </span>
                </span>
            </h2>
            
            <?php if (empty($penilaian_terbaru)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i>
                    Belum ada penilaian untuk station ini.
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Peserta</th>
                                <th>NIM</th>
                                <th>Nilai</th>
                                <th>Global Performance</th>
                                <th>Waktu</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($penilaian_terbaru as $index => $nilai): ?>
                                <tr>
                                    <td><?php echo $index + 1; ?></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($nilai['peserta_nama']); ?></strong>
                                    </td>
                                    <td>
                                        <code><?php echo htmlspecialchars($nilai['nim']); ?></code>
                                    </td>
                                    <td>
                                        <span class="nilai-badge nilai-total">
                                            <?php echo $nilai['total_nilai']; ?>/<?php echo $total_maksimal; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($nilai['global_performance'])): ?>
                                            <?php
                                            $global_performance_badge = '';
                                            $global_performance_text = '';
                                            
                                            switch($nilai['global_performance']) {
                                                case 'tidak_lulus':
                                                    $global_performance_badge = 'badge-danger';
                                                    $global_performance_text = 'Tidak Lulus';
                                                    break;
                                                case 'borderline':
                                                    $global_performance_badge = 'badge-warning';
                                                    $global_performance_text = 'Borderline';
                                                    break;
                                                case 'lulus':
                                                    $global_performance_badge = 'badge-success';
                                                    $global_performance_text = 'Lulus';
                                                    break;
                                                default:
                                                    $global_performance_badge = 'badge-secondary';
                                                    $global_performance_text = 'Belum Dinilai';
                                            }
                                            ?>
                                            <span class="badge <?php echo $global_performance_badge; ?> global-performance-badge">
                                                <?php echo $global_performance_text; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge badge-secondary global-performance-badge">
                                                Belum Dinilai
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($nilai['terakhir_dinilai'])); ?></td>
                                    <td>
                                        <a href="penilaian_detail.php?ujian_id=<?php echo $ujian_id; ?>&station_id=<?php echo $station_id; ?>&peserta_id=<?php 
                                            $stmt = $pdo->prepare("SELECT id FROM peserta WHERE nim = ?");
                                            $stmt->execute([$nilai['nim']]);
                                            $peserta = $stmt->fetch();
                                            echo $peserta ? $peserta['id'] : '';
                                        ?>" class="btn-edit-penilaian">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Global Performance Legend -->
                <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>
            <?php endif; ?>
        </div>

        <!-- Info Footer -->
        <div class="content-card" style="text-align: center; background: #f8f9fa;">
            <p style="color: #6c757d; margin: 0;">
                <i class="fas fa-info-circle"></i> 
                Pastikan penilaian dilakukan sesuai dengan pedoman dan waktu yang telah ditentukan.
            </p>
        </div>
    </div>

    <script>
    // Fungsi untuk menandai bahwa penilaian dimulai
    function mulaiPenilaian(ujianId, stationId, pesertaId, pesertaNama, redirectUrl) {
        // Tampilkan konfirmasi
        const userConfirmed = confirm(`Mulai penilaian untuk:\n${pesertaNama}\n\nPastikan peserta sudah siap di station?\n\nTekan OK untuk melanjutkan ke halaman penilaian.`);
        
        if (!userConfirmed) {
            return false;
        }
        
        // Simpan data ke sessionStorage sebagai fallback
        sessionStorage.setItem('pending_penilaian', JSON.stringify({
            ujian_id: ujianId,
            station_id: stationId,
            peserta_id: pesertaId,
            redirect_url: redirectUrl
        }));
        
        // Langsung redirect, biarkan halaman tujuan yang mengupdate status
        window.location.href = redirectUrl;
    }

    // Event listener untuk semua tombol
    document.addEventListener('DOMContentLoaded', function() {
        const pesertaCards = document.querySelectorAll('.peserta-card');
        
        pesertaCards.forEach(card => {
            // Hapus event listener lama dengan clone
            const newCard = card.cloneNode(true);
            card.parentNode.replaceChild(newCard, card);
            
            newCard.addEventListener('click', function(e) {
                e.preventDefault();
                
                const isSudahDinilai = this.classList.contains('sudah-dinilai');
                const pesertaNama = this.querySelector('.peserta-nama').textContent;
                const linkUrl = this.href;
                
                // Parse URL untuk mendapatkan parameter
                const urlParams = new URLSearchParams(linkUrl.split('?')[1]);
                const ujianId = urlParams.get('ujian_id');
                const stationId = urlParams.get('station_id');
                const pesertaId = urlParams.get('peserta_id');
                
                if (!ujianId || !stationId || !pesertaId) {
                    console.error('Parameter tidak lengkap');
                    window.location.href = linkUrl;
                    return;
                }
                
                // Jika sudah dinilai, langsung redirect
                if (isSudahDinilai) {
                    window.location.href = linkUrl;
                    return;
                }
                
                // Jika belum dinilai, panggil fungsi mulaiPenilaian
                mulaiPenilaian(ujianId, stationId, pesertaId, pesertaNama, linkUrl);
            });
        });
    });

    // Fungsi filter pencarian
    function filterPeserta() {
        const searchTerm = document.getElementById('searchPeserta').value.toLowerCase().trim();
        const clearBtn = document.querySelector('.search-clear');
        const pesertaCards = document.querySelectorAll('.peserta-card');
        const pesertaGrid = document.querySelector('.peserta-grid');
        
        if (clearBtn) {
            clearBtn.style.display = searchTerm.length > 0 ? 'flex' : 'none';
        }
        
        let visibleCount = 0;
        
        pesertaCards.forEach(card => {
            const nama = card.querySelector('.peserta-nama').textContent.toLowerCase();
            const nim = card.querySelector('.peserta-nim').textContent.toLowerCase();
            
            if (nama.includes(searchTerm) || nim.includes(searchTerm)) {
                card.classList.remove('hidden');
                visibleCount++;
                
                if (searchTerm.length > 0) {
                    highlightText(card, searchTerm);
                } else {
                    removeHighlight(card);
                }
            } else {
                card.classList.add('hidden');
            }
        });
        
        let emptyMsg = document.querySelector('.empty-search');
        if (visibleCount === 0 && searchTerm.length > 0) {
            if (!emptyMsg) {
                emptyMsg = document.createElement('div');
                emptyMsg.className = 'empty-search';
                emptyMsg.innerHTML = '<i class="fas fa-search"></i><p>Tidak ditemukan peserta dengan nama atau NIM: <strong>' + searchTerm + '</strong></p>';
                if (pesertaGrid) {
                    pesertaGrid.parentNode.insertBefore(emptyMsg, pesertaGrid.nextSibling);
                }
            } else {
                emptyMsg.style.display = 'block';
                emptyMsg.innerHTML = '<i class="fas fa-search"></i><p>Tidak ditemukan peserta dengan nama atau NIM: <strong>' + searchTerm + '</strong></p>';
            }
        } else {
            if (emptyMsg) {
                emptyMsg.style.display = 'none';
            }
        }
    }

    function highlightText(card, searchTerm) {
        removeHighlight(card);
        
        const namaElement = card.querySelector('.peserta-nama');
        const nimElement = card.querySelector('.peserta-nim');
        
        if (namaElement) {
            const originalNama = namaElement.textContent;
            const regex = new RegExp(`(${searchTerm})`, 'gi');
            namaElement.innerHTML = originalNama.replace(regex, '<span class="search-highlight">$1</span>');
        }
        
        if (nimElement) {
            const originalNim = nimElement.textContent;
            const regex = new RegExp(`(${searchTerm})`, 'gi');
            nimElement.innerHTML = originalNim.replace(regex, '<span class="search-highlight">$1</span>');
        }
    }

    function removeHighlight(card) {
        const namaElement = card.querySelector('.peserta-nama');
        const nimElement = card.querySelector('.peserta-nim');
        
        if (namaElement && namaElement.innerHTML.includes('search-highlight')) {
            namaElement.innerHTML = namaElement.textContent;
        }
        
        if (nimElement && nimElement.innerHTML.includes('search-highlight')) {
            nimElement.innerHTML = nimElement.textContent;
        }
    }

    function clearSearch() {
        const searchInput = document.getElementById('searchPeserta');
        if (searchInput) {
            searchInput.value = '';
            filterPeserta();
            searchInput.focus();
        }
    }
    </script>
</body>
</html>