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

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

$success_message = "";
$error_message = "";

// Function untuk assign peserta ke station-ujian tertentu
function assignPesertaToStationUjian($pdo, $peserta_id, $ujian_id, $station_id, $status = 'belum_mulai') {
    $check = $pdo->prepare("
        SELECT u.nama_ujian, s.nama_station, us.urutan 
        FROM ujian_stations us
        JOIN ujian u ON us.ujian_id = u.id
        JOIN stations s ON us.station_id = s.id
        WHERE us.ujian_id = ? AND us.station_id = ?
    ");
    $check->execute([$ujian_id, $station_id]);
    $data = $check->fetch();
    
    if (!$data) {
        return ["error" => "Kombinasi ujian-station tidak valid"];
    }
    
    $checkExisting = $pdo->prepare("
        SELECT COUNT(*) FROM peserta_station 
        WHERE peserta_id = ? AND ujian_id = ? AND station_id = ?
    ");
    $checkExisting->execute([$peserta_id, $ujian_id, $station_id]);
    
    if ($checkExisting->fetchColumn() > 0) {
        return ["error" => "Peserta sudah terdaftar di " . $data['nama_station']];
    }
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO peserta_station (peserta_id, station_id, ujian_id, urutan, status) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $peserta_id, 
            $station_id, 
            $ujian_id, 
            $data['urutan'], 
            $status
        ]);
        
        return [
            "success" => true,
            "ujian_nama" => $data['nama_ujian'],
            "station_nama" => $data['nama_station'],
            "urutan" => $data['urutan']
        ];
    } catch (PDOException $e) {
        return ["error" => "Database error: " . $e->getMessage()];
    }
}

// ========== BULK ASSIGN CUSTOM (Multiple Ujian & Multiple Station) ==========
function bulkAssignMultipleUjian($pdo, $peserta_ids, $ujian_station_pairs, $status = 'belum_mulai') {
    $total_success = 0;
    $total_errors = [];
    $assigned_peserta = [];
    $details = [];
    
    foreach ($peserta_ids as $peserta_id) {
        $getPeserta = $pdo->prepare("SELECT nama FROM peserta WHERE id = ?");
        $getPeserta->execute([$peserta_id]);
        $peserta_nama = $getPeserta->fetchColumn();
        
        $peserta_success = 0;
        
        foreach ($ujian_station_pairs as $pair) {
            $ujian_id = $pair['ujian_id'];
            $station_id = $pair['station_id'];
            
            $result = assignPesertaToStationUjian($pdo, $peserta_id, $ujian_id, $station_id, $status);
            
            if (isset($result['error'])) {
                $total_errors[] = "{$peserta_nama}: " . $result['error'];
            } else {
                $peserta_success++;
                $total_success++;
                $details[] = "{$peserta_nama} → {$result['station_nama']} ({$result['ujian_nama']})";
            }
        }
        
        if ($peserta_success > 0) {
            $assigned_peserta[] = $peserta_nama;
        }
    }
    
    return [
        "success" => $total_success,
        "total_peserta" => count($peserta_ids),
        "total_assignments" => count($peserta_ids) * count($ujian_station_pairs),
        "assigned_peserta" => $assigned_peserta,
        "errors" => $total_errors,
        "details" => $details
    ];
}

// Proses bulk assign custom
if (isset($_POST['bulk_assign_custom'])) {
    $peserta_ids = $_POST['bulk_peserta_ids'] ?? [];
    $ujian_ids = $_POST['bulk_ujian_ids'] ?? [];
    $station_ids = $_POST['bulk_station_ids'] ?? [];
    $semester = $_POST['semester'] ?? '';
    
    if (empty($peserta_ids)) {
        $error_message = "Pilih minimal 1 peserta";
    } elseif (empty($ujian_ids) || empty($station_ids)) {
        $error_message = "Pilih minimal 1 ujian dan 1 station";
    } elseif (count($ujian_ids) != count($station_ids)) {
        $error_message = "Jumlah ujian dan station harus sama";
    } else {
        $ujian_station_pairs = [];
        for ($i = 0; $i < count($ujian_ids); $i++) {
            $ujian_station_pairs[] = [
                'ujian_id' => $ujian_ids[$i],
                'station_id' => $station_ids[$i]
            ];
        }
        
        $result = bulkAssignMultipleUjian($pdo, $peserta_ids, $ujian_station_pairs, 'belum_mulai');
        
        if ($result['success'] > 0) {
            $success_message = "Berhasil assign " . count($result['assigned_peserta']) . " peserta";
            $success_message .= "<br><small>Total " . $result['success'] . " assignment dibuat</small>";
            
            if (!empty($result['errors'])) {
                $error_message = "Beberapa error: <br>" . implode("<br>", array_slice($result['errors'], 0, 10));
            }
        } else {
            $error_message = "Tidak ada assignment yang berhasil. " . implode("<br>", $result['errors']);
        }
    }
}

// Proses single assign
if (isset($_POST['assign_station_ujian'])) {
    $peserta_id = $_POST['peserta_id'];
    $semester = $_POST['semester'] ?? '';
    
    $assignments = [];
    if (isset($_POST['assignments']) && is_array($_POST['assignments'])) {
        foreach ($_POST['assignments'] as $assignment_str) {
            list($ujian_id, $station_id) = explode('-', $assignment_str);
            $assignments[] = [
                'ujian_id' => $ujian_id,
                'station_id' => $station_id
            ];
        }
    }
    
    if (empty($assignments)) {
        $error_message = "Pilih setidaknya 1 kombinasi ujian-station";
    } else {
        $result = assignPesertaToMultipleStationUjian($pdo, $peserta_id, $assignments);
        
        if ($result['success'] > 0) {
            $success_message = "Berhasil assign peserta ke " . $result['success'] . " ujian-station";
            $details = [];
            foreach ($result['results'] as $r) {
                $details[] = $r['station_nama'];
            }
            $success_message .= "<br><small>Detail: " . implode(", ", $details) . "</small>";
        }
        if (!empty($result['errors'])) {
            $error_message = implode("<br>", $result['errors']);
        }
    }
}

function assignPesertaToMultipleStationUjian($pdo, $peserta_id, $assignments) {
    $results = [];
    $errors = [];
    $successCount = 0;
    
    foreach ($assignments as $assignment) {
        $ujian_id = $assignment['ujian_id'];
        $station_id = $assignment['station_id'];
        
        $result = assignPesertaToStationUjian($pdo, $peserta_id, $ujian_id, $station_id);
        
        if (isset($result['error'])) {
            $errors[] = $result['error'];
        } else {
            $successCount++;
            $results[] = $result;
        }
    }
    
    return [
        "success" => $successCount,
        "total" => count($assignments),
        "results" => $results,
        "errors" => $errors
    ];
}

// Fungsi untuk menghapus semua assignment berdasarkan semester
function deleteAllAssignmentsBySemester($pdo, $semester) {
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("
            DELETE ps FROM peserta_station ps
            INNER JOIN peserta p ON ps.peserta_id = p.id
            WHERE p.semester = ?
        ");
        $stmt->execute([$semester]);
        $deletedCount = $stmt->rowCount();
        
        $pdo->commit();
        
        return [
            'success' => true,
            'deleted_count' => $deletedCount,
            'message' => "Berhasil menghapus $deletedCount assignment untuk Semester $semester"
        ];
    } catch (PDOException $e) {
        $pdo->rollBack();
        return [
            'success' => false,
            'message' => "Error: " . $e->getMessage()
        ];
    }
}

// Proses hapus semua assignment
if (isset($_POST['delete_all_assignments'])) {
    $semester = $_POST['semester'] ?? $selected_semester;
    $confirm = $_POST['confirm_delete_all'] ?? '';
    
    if ($confirm === 'HAPUS') {
        $result = deleteAllAssignmentsBySemester($pdo, $semester);
        
        if ($result['success']) {
            $success_message = $result['message'];
            $assignedPeserta = $pdo->query("
                SELECT 
                    ps.peserta_id,
                    p.nama as peserta_nama,
                    p.nim,
                    p.semester,
                    ps.ujian_id,
                    u.nama_ujian,
                    ps.station_id,
                    s.nama_station,
                    ps.urutan,
                    ps.status,
                    ps.created_at
                FROM peserta_station ps
                JOIN peserta p ON ps.peserta_id = p.id
                JOIN ujian u ON ps.ujian_id = u.id
                JOIN stations s ON ps.station_id = s.id
                ORDER BY ps.created_at DESC, p.nama
            ")->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $error_message = $result['message'];
        }
    } else {
        $error_message = "Konfirmasi tidak sesuai. Ketik 'HAPUS' untuk menghapus semua assignment.";
    }
}

// Proses hapus assignment
if (isset($_GET['delete_assignment'])) {
    $peserta_id = $_GET['peserta_id'];
    $ujian_id = $_GET['ujian_id'];
    $station_id = $_GET['station_id'];
    
    try {
        $stmt = $pdo->prepare("
            DELETE FROM peserta_station 
            WHERE peserta_id = ? AND ujian_id = ? AND station_id = ?
        ");
        $stmt->execute([$peserta_id, $ujian_id, $station_id]);
        $success_message = "Assignment berhasil dihapus";
    } catch (PDOException $e) {
        $error_message = "Error menghapus assignment: " . $e->getMessage();
    }
}

// Ambil data
try {
    $semesterList = $pdo->query("SELECT DISTINCT semester FROM peserta ORDER BY semester")->fetchAll(PDO::FETCH_COLUMN);
    $selected_semester = $_POST['semester'] ?? $_GET['semester'] ?? ($semesterList[0] ?? 1);
    
    $pesertaList = $pdo->prepare("
        SELECT id, nama, nim, semester 
        FROM peserta 
        WHERE semester = ? 
        ORDER BY CAST(nim AS UNSIGNED) ASC, nim ASC
    ");
    $pesertaList->execute([$selected_semester]);
    $pesertaList = $pesertaList->fetchAll(PDO::FETCH_ASSOC);
    
    $ujianStationList = $pdo->query("
        SELECT 
            u.id as ujian_id,
            u.nama_ujian,
            u.tanggal_ujian,
            s.id as station_id,
            s.nama_station,
            s.deskripsi as station_deskripsi,
            us.urutan
        FROM ujian_stations us
        JOIN ujian u ON us.ujian_id = u.id
        JOIN stations s ON us.station_id = s.id
        WHERE (u.status = 'aktif' OR u.status = 'selesai')
        ORDER BY u.nama_ujian, us.urutan
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $stationsWithUjian = [];
    foreach ($ujianStationList as $item) {
        $station_id = $item['station_id'];
        if (!isset($stationsWithUjian[$station_id])) {
            $stationsWithUjian[$station_id] = [
                'nama_station' => $item['nama_station'],
                'deskripsi' => $item['station_deskripsi'],
                'ujian_options' => []
            ];
        }
        $stationsWithUjian[$station_id]['ujian_options'][] = [
            'ujian_id' => $item['ujian_id'],
            'nama_ujian' => $item['nama_ujian'],
            'tanggal_ujian' => $item['tanggal_ujian'],
            'urutan' => $item['urutan']
        ];
    }
    
    $assignedPeserta = $pdo->query("
        SELECT 
            ps.peserta_id,
            p.nama as peserta_nama,
            p.nim,
            p.semester,
            ps.ujian_id,
            u.nama_ujian,
            ps.station_id,
            s.nama_station,
            ps.urutan,
            ps.status,
            ps.created_at
        FROM peserta_station ps
        JOIN peserta p ON ps.peserta_id = p.id
        JOIN ujian u ON ps.ujian_id = u.id
        JOIN stations s ON ps.station_id = s.id
        ORDER BY ps.created_at DESC, p.nama
    ")->fetchAll(PDO::FETCH_ASSOC);

    $filteredAssigned = [];
    $groupedByPeserta = [];

    if (!empty($assignedPeserta)) {
        $filteredAssigned = array_filter($assignedPeserta, function($item) use ($selected_semester) {
            return isset($item['semester']) && $item['semester'] == $selected_semester;
        });
        
        $groupedByPeserta = [];
        foreach ($filteredAssigned as $assign) {
            $peserta_id = $assign['peserta_id'];
            if (!isset($groupedByPeserta[$peserta_id])) {
                $groupedByPeserta[$peserta_id] = [
                    'peserta_nama' => $assign['peserta_nama'],
                    'nim' => $assign['nim'],
                    'assignments' => []
                ];
            }
            $groupedByPeserta[$peserta_id]['assignments'][] = $assign;
        }
        
        if (!empty($groupedByPeserta)) {
            uasort($groupedByPeserta, function($a, $b) {
                return strcmp($a['nim'], $b['nim']);
            });
        }
    }
    
    $allStations = $pdo->query("SELECT id, nama_station FROM stations ORDER BY nama_station")->fetchAll(PDO::FETCH_ASSOC);
    
    $allUjian = $pdo->query("
        SELECT id, nama_ujian, tanggal_ujian 
        FROM ujian 
        WHERE status = 'aktif' OR status = 'selesai'
        ORDER BY nama_ujian ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error_message = "Error mengambil data: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Peserta | OSCE System</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap" rel="stylesheet">
    <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: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #eef2f6 100%);
            min-height: 100vh;
        }

        /* Main Container Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar Modern */
        .sidebar {
            width: 280px;
            background: linear-gradient(180deg, #1a1f2e 0%, #0f1119 100%);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 100;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.08);
        }

        .sidebar-header {
            padding: 1.8rem 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            text-align: center;
        }

        .logo-area {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin-bottom: 0.5rem;
        }

        .logo-icon {
            width: 45px;
            height: 45px;
            background: linear-gradient(135deg, #667eea, #1958e1);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .logo-text h3 {
            font-size: 1.2rem;
            font-weight: 700;
            letter-spacing: -0.3px;
            background: linear-gradient(135deg, #fff, #1958e1);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }

        .logo-text p {
            font-size: 0.7rem;
            opacity: 0.7;
            margin-top: 2px;
        }

        .user-info-sidebar {
            padding: 1.2rem;
            background: rgba(255, 255, 255, 0.05);
            margin: 1rem;
            border-radius: 16px;
            text-align: center;
        }

        .user-avatar {
            width: 55px;
            height: 55px;
            background: linear-gradient(135deg, #667eea, #1958e1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-size: 1.5rem;
        }

        .nav-menu {
            padding: 1rem 0;
        }

        .nav-item {
            padding: 0.75rem 1.5rem;
            margin: 0.25rem 0.75rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            color: rgba(255, 255, 255, 0.7);
            transition: all 0.2s;
            text-decoration: none;
        }

        .nav-item:hover, .nav-item.active {
            background: rgba(102, 126, 234, 0.2);
            color: white;
        }

        .nav-item i {
            width: 24px;
            font-size: 1.1rem;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            padding: 1.5rem 2rem 2rem;
        }

        /* Top Navbar */
        .top-navbar {
            background: white;
            border-radius: 20px;
            padding: 1rem 1.8rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .page-title h2 {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, #1e293b, #334155);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }

        .user-dropdown {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-name {
            font-weight: 600;
            color: #1e293b;
        }

        /* Card Styles */
        .card {
            background: white;
            border-radius: 24px;
            padding: 1.8rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 14px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 0, 0, 0.04);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 0 1.2rem 0;
            border-bottom: 2px solid #f1f5f9;
            margin-bottom: 1.5rem;
        }

        .card-header h5 {
            font-size: 1.1rem;
            font-weight: 700;
            color: #0f172a;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header h5 i {
            color: #1958e1;
        }

        /* Semester Buttons */
        .semester-group {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .semester-btn {
            padding: 0.6rem 1.8rem;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.85rem;
            text-decoration: none;
            transition: all 0.2s;
            border: 2px solid #e2e8f0;
            color: #475569;
            background: white;
        }

        .semester-btn:hover {
            border-color: #1958e1;
            color: #1958e1;
        }

        .semester-btn.active {
            background: linear-gradient(135deg, #667eea, #1958e1);
            color: white;
            border-color: transparent;
        }

        /* Alert Styles */
        .alert {
            padding: 1rem 1.2rem;
            border-radius: 16px;
            margin-bottom: 1.5rem;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        .alert-warning {
            background: #fef3c7;
            color: #92400e;
            border-left: 4px solid #f59e0b;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: 1.2rem;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #334155;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
        }

        .form-control, .form-select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 14px;
            font-size: 0.9rem;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s;
            background: #f8fafc;
        }

        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: #1958e1;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* Button Styles */
        .btn {
            padding: 0.7rem 1.5rem;
            border-radius: 14px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            font-family: 'Inter', sans-serif;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #1958e1);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-success {
            background: #10b981;
            color: white;
        }

        .btn-success:hover {
            background: #059669;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #ef4444;
            color: white;
        }

        .btn-danger:hover:not(:disabled) {
            background: #dc2626;
            transform: translateY(-2px);
        }

        .btn-danger:disabled {
            background: #cbd5e1;
            cursor: not-allowed;
        }

        .btn-warning {
            background: #f59e0b;
            color: white;
        }

        .btn-warning:hover {
            background: #d97706;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #f1f5f9;
            color: #475569;
        }

        .btn-secondary:hover {
            background: #e2e8f0;
        }

        .btn-sm {
            padding: 0.4rem 1rem;
            font-size: 0.75rem;
        }

        .btn-lg {
            padding: 0.9rem 2rem;
            font-size: 1rem;
        }

        .btn-outline-secondary {
            background: transparent;
            color: #64748b;
            border: 2px solid #e2e8f0;
        }

        .btn-outline-secondary:hover {
            background: #f1f5f9;
            border-color: #cbd5e1;
        }

        /* Template Buttons */
        .template-btn {
            padding: 0.5rem 1.2rem;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.75rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }

        .template-btn:hover {
            transform: translateY(-2px);
        }

        .template-A {
            background: #10b981;
            color: white;
        }

        .template-B {
            background: #3b82f6;
            color: white;
        }

        .template-C {
            background: #ef4444;
            color: white;
        }

        /* Bulk Participant List */
        .bulk-peserta-checkbox {
            max-height: 300px;
            overflow-y: auto;
            border: 2px solid #e2e8f0;
            border-radius: 14px;
            padding: 0.5rem;
            background: #f8fafc;
        }

        .bulk-peserta-item {
            padding: 0.6rem 0.8rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 10px;
            border-radius: 8px;
            transition: background 0.2s;
        }

        .bulk-peserta-item:hover {
            background: #f1f5f9;
        }

        .bulk-peserta-item:last-child {
            border-bottom: none;
        }

        .bulk-peserta-item input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #1958e1;
            cursor: pointer;
        }

        .bulk-peserta-item label {
            font-size: 0.9rem;
            cursor: pointer;
        }

        .bulk-peserta-item .nim-badge {
            font-size: 0.7rem;
            background: #e2e8f0;
            padding: 2px 10px;
            border-radius: 30px;
            color: #475569;
            margin-left: 8px;
        }

        /* Selection Row */
        .selection-row {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 14px;
            margin-bottom: 1rem;
            border-left: 4px solid #1958e1;
        }

        .remove-selection {
            cursor: pointer;
            color: #ef4444;
            font-size: 1rem;
        }

        .remove-selection:hover {
            color: #dc2626;
        }

        /* Station-Ujian Card */
        .station-ujian-card {
            border: 2px solid #eef2ff;
            border-radius: 16px;
            padding: 1.2rem;
            margin-bottom: 1rem;
            transition: all 0.2s;
            background: #fafbff;
        }

        .station-ujian-card:hover {
            border-color: #c7d2fe;
            background: #f8f9ff;
        }

        .station-header {
            font-weight: 700;
            color: #1958e1;
            margin-bottom: 0.8rem;
            font-size: 1rem;
        }

        .ujian-option {
            padding: 0.6rem 1rem;
            margin: 0.3rem 0;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .ujian-option:hover {
            background: #eef2ff;
            border-color: #c7d2fe;
        }

        .ujian-option.selected {
            background: linear-gradient(135deg, #667eea, #1958e1);
            color: white;
            border-color: #1958e1;
        }

        .ujian-option.selected .text-muted {
            color: rgba(255, 255, 255, 0.7) !important;
        }

        /* Assignment Items */
        .assignment-item {
            display: inline-block;
            background: #10b981;
            color: white;
            padding: 0.3rem 0.8rem;
            border-radius: 30px;
            margin: 0.2rem;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-station {
            background: #3b82f6;
            color: white;
            padding: 0.3rem 0.8rem;
            border-radius: 30px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge-status {
            padding: 0.3rem 0.8rem;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 600;
            background: #e2e8f0;
            color: #475569;
        }

        /* Table Styles */
        .table-container {
            overflow-x: auto;
            border-radius: 16px;
            border: 1px solid #eef2ff;
        }

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

        .data-table thead tr {
            background: #f8fafc;
        }

        .data-table th {
            padding: 0.8rem 0.8rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #475569;
            border-bottom: 2px solid #e2e8f0;
        }

        .data-table td {
            padding: 0.8rem 0.8rem;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
        }

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

        /* Selected Preview */
        .selected-assignments {
            background: #f0fdf4;
            border: 2px solid #86efac;
            border-radius: 14px;
            padding: 1rem;
            margin-top: 1rem;
        }

        /* Modal */
        .modal-overlay-custom {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .modal-overlay-custom.show {
            display: flex !important;
        }

        .modal-content-custom {
            background: white;
            border-radius: 28px;
            max-width: 500px;
            width: 90%;
            padding: 2rem;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .sidebar { width: 250px; }
            .main-content { margin-left: 250px; }
        }

        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); position: fixed; }
            .main-content { margin-left: 0; padding: 1rem; }
            .top-navbar { flex-direction: column; gap: 0.5rem; text-align: center; }
            .card-header { flex-direction: column; gap: 0.5rem; }
        }

        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    </style>
</head>
<body>
<div class="dashboard-wrapper">
    <!-- Sidebar -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo-area">
                <div class="logo-icon"><i class="fas fa-tooth"></i></div>
                <div class="logo-text"><h3>OSCE</h3><p>Admin Center</p></div>
            </div>
        </div>
        <div class="user-info-sidebar">
            <div class="user-avatar"><i class="fas fa-user-cog"></i></div>
            <div style="font-weight: 600;"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Administrator'); ?></div>
            <div style="font-size: 0.7rem; opacity: 0.7;">Administrator</div>
        </div>
        <div class="nav-menu">
            <a href="dashboard.php" class="nav-item"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a href="soal.php" class="nav-item"><i class="fas fa-question-circle"></i> <span>Kelola Soal</span></a>
            <a href="ujian.php" class="nav-item"><i class="fas fa-calendar-alt"></i> <span>Kelola Ujian</span></a>
            <a href="peserta.php" class="nav-item active"><i class="fas fa-users"></i> <span>Kelola Peserta</span></a>
            <a href="penguji.php" class="nav-item"><i class="fas fa-chalkboard-user"></i> <span>Kelola Penguji</span></a>
            <a href="nilai.php" class="nav-item"><i class="fas fa-chart-line"></i> <span>Hasil Penilaian</span></a>
            <a href="../logout.php" class="nav-item" style="margin-top: 2rem;"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </div>
    </aside>

    <!-- Main Content -->
    <main class="main-content">
        <div class="top-navbar">
            <div class="page-title">
                <h2><i class="fas fa-users" style="margin-right: 10px; color: #667eea;"></i>Kelola Peserta Station</h2>
            </div>
            <div class="user-dropdown">
                <span class="user-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Admin'); ?></span>
                <i class="fas fa-bell" style="color: #94a3b8;"></i>
            </div>
        </div>

        <?php if ($success_message): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success_message; ?></div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Semester Selection -->
        <div class="semester-group">
            <?php foreach ([1, 3, 5, 7] as $sem): ?>
                <a href="?semester=<?= $sem ?>" class="semester-btn <?= $selected_semester == $sem ? 'active' : '' ?>">
                    Semester <?= $sem ?>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- ========== BULK ASSIGN ========== -->
        <div class="card" style="border-left: 4px solid #10b981;">
            <div class="card-header">
                <h5><i class="fas fa-users"></i> Bulk Assign Masal</h5>
                <span class="badge" style="background: #10b981; color: white; padding: 0.3rem 1rem; border-radius: 30px; font-size: 0.7rem;">
                    <i class="fas fa-sort-numeric-down"></i> Urut NIM
                </span>
            </div>
            <div class="card-body">
                <form method="POST" action="" id="bulkAssignForm">
                    <input type="hidden" name="semester" value="<?= $selected_semester ?>">
                    
                    <div class="row">
                        <!-- Pilih Peserta -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label><i class="fas fa-user-check"></i> Pilih Peserta (multiple):</label>
                                <div class="bulk-peserta-checkbox">
                                    <?php if (!empty($pesertaList)): ?>
                                        <?php foreach ($pesertaList as $peserta): ?>
                                            <div class="bulk-peserta-item">
                                                <input type="checkbox" name="bulk_peserta_ids[]" value="<?= $peserta['id'] ?>" id="bulk_<?= $peserta['id'] ?>">
                                                <label for="bulk_<?= $peserta['id'] ?>">
                                                    <strong><?= htmlspecialchars($peserta['nama']) ?></strong>
                                                    <span class="nim-badge"><i class="fas fa-id-card"></i> <?= htmlspecialchars($peserta['nim']) ?></span>
                                                </label>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-muted text-center py-3">Tidak ada peserta untuk semester <?= $selected_semester ?></p>
                                    <?php endif; ?>
                                </div>
                                <div class="mt-2" style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                                    <button type="button" class="btn btn-sm btn-secondary" onclick="selectAllBulk()"><i class="fas fa-check-double"></i> Pilih Semua</button>
                                    <button type="button" class="btn btn-sm btn-secondary" onclick="deselectAllBulk()"><i class="fas fa-times"></i> Hapus Semua</button>
                                    <span class="text-muted" style="font-size: 0.85rem; align-self: center;" id="selectedCount">0 peserta dipilih</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Pilihan Ujian dan Station -->
                        <div class="col-md-8">
                            <label class="form-group"><i class="fas fa-geo-alt"></i> Pilih Pasangan Ujian & Station:</label>
                            
                            <div style="display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1rem;">
                                <span class="text-muted" style="font-size: 0.8rem; align-self: center;">Shortcut:</span>
                                <button type="button" class="template-btn template-A" onclick="selectTripleA()"><i class="fas fa-1"></i> 1A+2A+3A</button>
                                <button type="button" class="template-btn template-B" onclick="selectTripleB()"><i class="fas fa-2"></i> 1B+2B+3B</button>
                                <button type="button" class="template-btn template-C" onclick="selectTripleC()"><i class="fas fa-3"></i> 1C+2C+3C</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllSelections()"><i class="fas fa-trash"></i> Kosongkan</button>
                            </div>
                            
                            <div id="selections-container">
                                <div class="selection-row" id="selection-0">
                                    <div class="row align-items-center">
                                        <div class="col-md-5">
                                            <select name="bulk_ujian_ids[]" class="form-control ujian-select" data-index="0" required style="border-radius: 12px;">
                                                <option value="">-- Pilih Ujian --</option>
                                                <?php foreach ($allUjian as $ujian): ?>
                                                    <option value="<?= $ujian['id'] ?>"><?= htmlspecialchars($ujian['nama_ujian']) ?> (<?= date('d/m/Y', strtotime($ujian['tanggal_ujian'])) ?>)</option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-5">
                                            <select name="bulk_station_ids[]" class="form-control station-select" data-index="0" required style="border-radius: 12px;">
                                                <option value="">-- Pilih Station --</option>
                                                <?php foreach ($allStations as $station): ?>
                                                    <option value="<?= $station['id'] ?>"><?= htmlspecialchars($station['nama_station']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="button" class="btn btn-danger btn-sm remove-selection" onclick="removeSelection(0)" style="display:none;">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-2">
                                <button type="button" class="btn btn-sm btn-primary" onclick="addSelection()" style="background: #667eea;">
                                    <i class="fas fa-plus-circle"></i> Tambah Pasangan
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <button type="submit" name="bulk_assign_custom" class="btn btn-success btn-lg" onclick="return confirmBulkSubmit()">
                            <i class="fas fa-save"></i> Assign Semua Peserta ke Semua Pasangan
                        </button>
                    </div>
                </form>
                
                <div class="alert alert-info mt-3">
                    <i class="fas fa-info-circle"></i>
                    <strong>Cara Penggunaan:</strong> Pilih peserta (bisa 15-20 sekaligus) → Pilih pasangan Ujian-Station (bisa 1, 2, 3 pasangan) → Klik Assign. Setiap peserta akan diassign ke SEMUA pasangan yang dipilih.
                </div>
            </div>
        </div>

        <!-- ========== SINGLE ASSIGN ========== -->
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-user-plus"></i> Single Assign (1 Peserta)</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="assignForm">
                            <input type="hidden" name="semester" value="<?= $selected_semester ?>">
                            
                            <div class="form-group">
                                <label for="peserta_id">Pilih Peserta (Urut NIM):</label>
                                <select name="peserta_id" id="peserta_id" class="form-control" required>
                                    <option value="">-- Pilih Peserta --</option>
                                    <?php if (!empty($pesertaList)): ?>
                                        <?php foreach ($pesertaList as $peserta): ?>
                                            <option value="<?= $peserta['id'] ?>">
                                                <?= htmlspecialchars($peserta['nama']) ?> (NIM: <?= htmlspecialchars($peserta['nim']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option value="">Tidak ada peserta untuk semester <?= $selected_semester ?></option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            
                            <div id="station-ujian-container">
                                <?php if (empty($stationsWithUjian)): ?>
                                    <div class="alert alert-warning">Tidak ada station dengan ujian tersedia.</div>
                                <?php else: ?>
                                    <?php foreach ($stationsWithUjian as $station_id => $station): ?>
                                        <div class="station-ujian-card" id="station-<?= $station_id ?>">
                                            <div class="station-header"><i class="fas fa-geo-alt me-2"></i> <?= htmlspecialchars($station['nama_station']) ?></div>
                                            <div class="ujian-options">
                                                <?php foreach ($station['ujian_options'] as $ujian): ?>
                                                    <div class="ujian-option" data-station-id="<?= $station_id ?>" data-ujian-id="<?= $ujian['ujian_id'] ?>" onclick="selectUjian(this, <?= $station_id ?>, <?= $ujian['ujian_id'] ?>)">
                                                        <div class="form-check">
                                                            <input type="checkbox" class="assignment-checkbox" name="assignments[]" value="<?= $ujian['ujian_id'] ?>-<?= $station_id ?>" id="assign_<?= $ujian['ujian_id'] ?>_<?= $station_id ?>" style="display: none;">
                                                            <label class="form-check-label" for="assign_<?= $ujian['ujian_id'] ?>_<?= $station_id ?>">
                                                                <strong><?= htmlspecialchars($ujian['nama_ujian']) ?></strong>
                                                                <small class="text-muted d-block"><?= date('d/m/Y', strtotime($ujian['tanggal_ujian'])) ?></small>
                                                            </label>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <div id="selected-preview" class="selected-assignments" style="display: none;">
                                <h6 style="margin-bottom: 0.5rem;"><i class="fas fa-check-circle" style="color: #10b981;"></i> Ujian yang Dipilih:</h6>
                                <div id="selected-list"></div>
                            </div>
                            
                            <div class="mt-4">
                                <button type="submit" name="assign_station_ujian" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Assign Peserta
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-info-circle" style="color: #3b82f6;"></i> Panduan</h5>
                    </div>
                    <div class="card-body">
                        <div style="background: #eef2ff; padding: 1rem; border-radius: 14px; margin-bottom: 1rem;">
                            <h6 style="font-weight: 700; color: #4338ca;"><i class="fas fa-lightbulb"></i> Bulk Assign (Multiple):</h6>
                            <ol style="padding-left: 1.2rem; font-size: 0.85rem; color: #334155;">
                                <li>Pilih peserta (bisa 15-20 sekaligus)</li>
                                <li>Pilih pasangan ujian & station (bisa 1, 2, 3 pasangan)</li>
                                <li>Klik Assign → semua peserta ke semua pasangan</li>
                            </ol>
                        </div>
                        
                        <div style="margin-bottom: 1rem;">
                            <h6 style="font-weight: 700; color: #1e293b;">Shortcut Tersedia:</h6>
                            <ul style="font-size: 0.85rem; color: #475569;">
                                <li><span class="template-btn template-A" style="display: inline-block; padding: 0.2rem 0.8rem; font-size: 0.7rem;">A</span> 1A.Anatomi + 2A.Anamnesis + 3A.Odontogram</li>
                                <li><span class="template-btn template-B" style="display: inline-block; padding: 0.2rem 0.8rem; font-size: 0.7rem;">B</span> 1B.Anatomi + 2B.Anamnesis + 3B.Odontogram</li>
                                <li><span class="template-btn template-C" style="display: inline-block; padding: 0.2rem 0.8rem; font-size: 0.7rem;">C</span> 1C.Anatomi + 2C.Anamnesis + 3C.Odontogram</li>
                            </ul>
                        </div>
                        
                        <div>
                            <h6 style="font-weight: 700; color: #1e293b;"><i class="fas fa-sort-numeric-down"></i> Urutan Peserta:</h6>
                            <p class="text-muted" style="font-size: 0.85rem;">Peserta ditampilkan berdasarkan <strong>NIM terkecil ke terbesar</strong>.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Daftar Assignments -->
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-list-check"></i> Daftar Assignments</h5>
                <button type="button" class="btn btn-danger btn-sm" onclick="showDeleteAllModal()" <?php echo empty($groupedByPeserta) ? 'disabled' : ''; ?>>
                    <i class="fas fa-trash-alt"></i> Hapus Semua Semester <?= $selected_semester ?>
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($groupedByPeserta)): ?>
                    <p class="text-muted text-center py-4">Belum ada assignments untuk semester <?= $selected_semester ?>.</p>
                <?php else: ?>
                    <?php foreach ($groupedByPeserta as $peserta_id => $data): ?>
                        <div style="margin-bottom: 1.5rem; padding: 1.2rem; background: #fafbff; border-radius: 16px; border: 1px solid #eef2ff;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                                <h6 style="margin: 0; font-weight: 700; color: #0f172a;">
                                    <?= htmlspecialchars($data['peserta_nama']) ?>
                                    <span class="nim-badge" style="background: #e2e8f0; padding: 2px 10px; border-radius: 30px; font-size: 0.7rem; font-weight: 500; margin-left: 8px;">
                                        <i class="fas fa-id-card"></i> <?= htmlspecialchars($data['nim']) ?>
                                    </span>
                                </h6>
                                <span class="badge" style="background: #667eea; color: white; padding: 0.3rem 1rem; border-radius: 30px; font-size: 0.7rem;">
                                    <?= count($data['assignments']) ?> Station
                                </span>
                            </div>
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr><th>Station</th><th>Ujian</th><th>Status</th><th>Aksi</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($data['assignments'] as $assign): ?>
                                            <tr>
                                                <td><span class="badge-station"><?= htmlspecialchars($assign['nama_station']) ?></span></td>
                                                <td><?= htmlspecialchars($assign['nama_ujian']) ?></td>
                                                <td><span class="badge-status"><?= $assign['status'] ?></span></td>
                                                <td>
                                                    <a href="?delete_assignment=1&peserta_id=<?= $assign['peserta_id'] ?>&ujian_id=<?= $assign['ujian_id'] ?>&station_id=<?= $assign['station_id'] ?>&semester=<?= $selected_semester ?>" 
                                                       class="btn btn-danger btn-sm" onclick="return confirm('Hapus assignment ini?')">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Modal Konfirmasi Hapus Semua -->
<div id="deleteAllModal" class="modal-overlay-custom">
    <div class="modal-content-custom">
        <div style="margin-bottom: 1rem;">
            <h4 style="color: #dc2626; font-weight: 700; display: flex; align-items: center; gap: 10px;">
                <i class="fas fa-exclamation-triangle"></i> PERINGATAN!
            </h4>
        </div>
        <div style="background: #fee2e2; padding: 1rem; border-radius: 14px; border-left: 4px solid #ef4444; margin-bottom: 1.5rem;">
            <p><strong>Anda akan menghapus SEMUA assignment peserta untuk Semester <?= $selected_semester ?>!</strong></p>
            <p>Jumlah assignment: <strong><?php 
                $totalAssignments = 0;
                if (!empty($groupedByPeserta)) {
                    foreach ($groupedByPeserta as $data) {
                        $totalAssignments += count($data['assignments']);
                    }
                }
                echo $totalAssignments;
            ?></strong> record</p>
            <p class="mb-0"><i class="fas fa-info-circle"></i> Tindakan ini <strong>TIDAK DAPAT DIBATALKAN</strong>.</p>
        </div>
        
        <form method="POST" action="" id="deleteAllForm" onsubmit="return validateDeleteForm()">
            <input type="hidden" name="semester" value="<?= $selected_semester ?>">
            <input type="hidden" name="delete_all_assignments" value="1">
            
            <div class="form-group">
                <label>Ketik <strong class="text-danger">HAPUS</strong> untuk konfirmasi:</label>
                <input type="text" class="form-control" id="confirm_delete_all" name="confirm_delete_all" placeholder="Ketik HAPUS disini..." autocomplete="off">
            </div>
            
            <div style="display: flex; justify-content: flex-end; gap: 0.8rem;">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteAllModal()"><i class="fas fa-times"></i> Batal</button>
                <button type="submit" class="btn btn-danger" id="confirmDeleteBtn"><i class="fas fa-trash-alt"></i> Hapus Semua</button>
            </div>
        </form>
    </div>
</div>

<script>
    let selectedAssignments = {};
    let selectionCount = 1;
    
    function selectUjian(element, stationId, ujianId) {
        const card = element.closest('.station-ujian-card');
        const checkbox = element.querySelector('.assignment-checkbox');
        const ujianNama = element.querySelector('strong').textContent;
        const stationNama = card.querySelector('.station-header').textContent.trim();
        
        card.querySelectorAll('.ujian-option').forEach(opt => {
            opt.classList.remove('selected');
            opt.querySelector('.assignment-checkbox').checked = false;
        });
        
        element.classList.add('selected');
        checkbox.checked = true;
        
        selectedAssignments[stationId] = {
            ujian_id: ujianId,
            ujian_nama: ujianNama,
            station_nama: stationNama
        };
        
        updateSelectedPreview();
    }
    
    function updateSelectedPreview() {
        const container = document.getElementById('selected-list');
        const previewDiv = document.getElementById('selected-preview');
        
        if (Object.keys(selectedAssignments).length === 0) {
            previewDiv.style.display = 'none';
            return;
        }
        
        let html = '';
        for (const [stationId, data] of Object.entries(selectedAssignments)) {
            html += `<span class="assignment-item">${data.station_nama}: ${data.ujian_nama}</span>`;
        }
        container.innerHTML = html;
        previewDiv.style.display = 'block';
    }
    
    function selectAllBulk() {
        document.querySelectorAll('.bulk-peserta-item input[type="checkbox"]').forEach(cb => cb.checked = true);
        updateSelectedCount();
    }
    
    function deselectAllBulk() {
        document.querySelectorAll('.bulk-peserta-item input[type="checkbox"]').forEach(cb => cb.checked = false);
        updateSelectedCount();
    }
    
    function updateSelectedCount() {
        const count = document.querySelectorAll('.bulk-peserta-item input[type="checkbox"]:checked').length;
        document.getElementById('selectedCount').innerText = count + ' peserta dipilih';
    }
    
    function addSelection() {
        const container = document.getElementById('selections-container');
        const newIndex = selectionCount;
        
        const ujianOptions = `<?php 
            $options = '';
            foreach ($allUjian as $ujian) {
                $options .= '<option value="' . $ujian['id'] . '">' . htmlspecialchars($ujian['nama_ujian']) . ' (' . date('d/m/Y', strtotime($ujian['tanggal_ujian'])) . ')</option>';
            }
            echo $options;
        ?>`;
        
        const stationOptions = `<?php 
            $options = '';
            foreach ($allStations as $station) {
                $options .= '<option value="' . $station['id'] . '">' . htmlspecialchars($station['nama_station']) . '</option>';
            }
            echo $options;
        ?>`;
        
        const newDiv = document.createElement('div');
        newDiv.className = 'selection-row';
        newDiv.id = `selection-${newIndex}`;
        newDiv.innerHTML = `
            <div class="row align-items-center">
                <div class="col-md-5">
                    <select name="bulk_ujian_ids[]" class="form-control ujian-select" data-index="${newIndex}" required style="border-radius: 12px;">
                        <option value="">-- Pilih Ujian --</option>
                        ${ujianOptions}
                    </select>
                </div>
                <div class="col-md-5">
                    <select name="bulk_station_ids[]" class="form-control station-select" data-index="${newIndex}" required style="border-radius: 12px;">
                        <option value="">-- Pilih Station --</option>
                        ${stationOptions}
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger btn-sm remove-selection" onclick="removeSelection(${newIndex})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(newDiv);
        selectionCount++;
        updateRemoveButtons();
    }
    
    function removeSelection(index) {
        const element = document.getElementById(`selection-${index}`);
        if (element && document.querySelectorAll('.selection-row').length > 1) {
            element.remove();
        } else {
            alert('Minimal harus ada 1 pasangan ujian-station');
        }
    }
    
    function updateRemoveButtons() {
        const rows = document.querySelectorAll('.selection-row');
        rows.forEach((row, idx) => {
            const removeBtn = row.querySelector('.remove-selection');
            if (removeBtn) {
                removeBtn.style.display = rows.length > 1 ? 'inline-block' : 'none';
            }
        });
    }
    
    function selectTripleA() {
        clearAllSelections();
        const ujianSelects = document.querySelectorAll('.ujian-select');
        const stationSelects = document.querySelectorAll('.station-select');
        const pairs = ['1A. Anatomi', '2A. Anamnesis', '3A. Odontogram'];
        
        for (let i = 0; i < pairs.length; i++) {
            if (i > 0 && i >= ujianSelects.length) addSelection();
            const ujianSelect = ujianSelects[i];
            const stationSelect = stationSelects[i];
            for (let opt of ujianSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
            for (let opt of stationSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
        }
    }
    
    function selectTripleB() {
        clearAllSelections();
        const ujianSelects = document.querySelectorAll('.ujian-select');
        const stationSelects = document.querySelectorAll('.station-select');
        const pairs = ['1B. Anatomi', '2B. Anamnesis', '3B. Odontogram'];
        
        for (let i = 0; i < pairs.length; i++) {
            if (i > 0 && i >= ujianSelects.length) addSelection();
            const ujianSelect = ujianSelects[i];
            const stationSelect = stationSelects[i];
            for (let opt of ujianSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
            for (let opt of stationSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
        }
    }
    
    function selectTripleC() {
        clearAllSelections();
        const ujianSelects = document.querySelectorAll('.ujian-select');
        const stationSelects = document.querySelectorAll('.station-select');
        const pairs = ['1C. Anatomi', '2C. Anamnesis', '3C. Odontogram'];
        
        for (let i = 0; i < pairs.length; i++) {
            if (i > 0 && i >= ujianSelects.length) addSelection();
            const ujianSelect = ujianSelects[i];
            const stationSelect = stationSelects[i];
            for (let opt of ujianSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
            for (let opt of stationSelect.options) {
                if (opt.text.includes(pairs[i])) { opt.selected = true; break; }
            }
        }
    }
    
    function clearAllSelections() {
        const container = document.getElementById('selections-container');
        const firstRow = container.querySelector('.selection-row');
        container.innerHTML = '';
        container.appendChild(firstRow);
        const firstUjianSelect = firstRow.querySelector('.ujian-select');
        const firstStationSelect = firstRow.querySelector('.station-select');
        if (firstUjianSelect) firstUjianSelect.selectedIndex = 0;
        if (firstStationSelect) firstStationSelect.selectedIndex = 0;
        selectionCount = 1;
        updateRemoveButtons();
    }
    
    function confirmBulkSubmit() {
        const selectedPeserta = document.querySelectorAll('.bulk-peserta-item input[type="checkbox"]:checked').length;
        const selectedPairs = document.querySelectorAll('.selection-row').length;
        
        if (selectedPeserta === 0) {
            alert('Pilih minimal 1 peserta!');
            return false;
        }
        
        const ujianSelects = document.querySelectorAll('.ujian-select');
        const stationSelects = document.querySelectorAll('.station-select');
        
        for (let i = 0; i < ujianSelects.length; i++) {
            if (!ujianSelects[i].value) {
                alert(`Pasangan ke-${i+1}: Pilih ujian terlebih dahulu!`);
                return false;
            }
            if (!stationSelects[i].value) {
                alert(`Pasangan ke-${i+1}: Pilih station terlebih dahulu!`);
                return false;
            }
        }
        
        const totalAssignments = selectedPeserta * selectedPairs;
        return confirm(`Assign ${selectedPeserta} peserta ke ${selectedPairs} pasangan ujian-station?\n\nTotal ${totalAssignments} assignment akan dibuat.\n\nLanjutkan?`);
    }
    
    document.querySelectorAll('.bulk-peserta-item input[type="checkbox"]').forEach(cb => {
        cb.addEventListener('change', updateSelectedCount);
    });
    
    document.getElementById('peserta_id').addEventListener('change', function() {
        selectedAssignments = {};
        updateSelectedPreview();
        document.querySelectorAll('.ujian-option').forEach(opt => {
            opt.classList.remove('selected');
            opt.querySelector('.assignment-checkbox').checked = false;
        });
    });
    
    updateSelectedCount();
    updateRemoveButtons();

    // Modal functions
    function showDeleteAllModal() {
        document.getElementById('deleteAllModal').classList.add('show');
        document.getElementById('confirm_delete_all').value = '';
    }

    function closeDeleteAllModal() {
        document.getElementById('deleteAllModal').classList.remove('show');
    }

    function validateDeleteForm() {
        var confirmText = document.getElementById('confirm_delete_all');
        if (confirmText && confirmText.value.toUpperCase() === 'HAPUS') {
            return confirm('Yakin ingin menghapus semua assignment? Tindakan ini tidak dapat dibatalkan!');
        } else {
            alert('Anda harus mengetik "HAPUS" untuk konfirmasi penghapusan!');
            return false;
        }
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            var modal = document.getElementById('deleteAllModal');
            if (modal && modal.classList.contains('show')) {
                closeDeleteAllModal();
            }
        }
    });
</script>
</body>
</html>