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

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

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

// PROSES TAMBAH PENGUJI BARU
if (isset($_POST['tambah_penguji'])) {
    $nama = trim($_POST['nama']);
    $nip = trim($_POST['nip']);
    $spesialisasi = trim($_POST['spesialisasi']);
    
    if (empty($nama) || empty($nip)) {
        $error_message = "Nama dan NIP harus diisi";
    } else {
        try {
            $checkNip = $pdo->prepare("SELECT id FROM penguji WHERE nip = ?");
            $checkNip->execute([$nip]);
            
            if ($checkNip->fetch()) {
                $error_message = "NIP $nip sudah terdaftar";
            } else {
                $stmt = $pdo->prepare("INSERT INTO penguji (nama, nip, spesialisasi) VALUES (?, ?, ?)");
                $stmt->execute([$nama, $nip, $spesialisasi]);
                $success_message = "Penguji $nama berhasil ditambahkan";
            }
        } catch (PDOException $e) {
            $error_message = "Error menambah penguji: " . $e->getMessage();
        }
    }
}

// PROSES HAPUS PENGUJI
if (isset($_GET['delete_penguji'])) {
    $penguji_id = $_GET['penguji_id'];
    
    try {
        $checkAssignment = $pdo->prepare("SELECT id FROM penguji_station WHERE penguji_id = ?");
        $checkAssignment->execute([$penguji_id]);
        
        if ($checkAssignment->fetch()) {
            $error_message = "Tidak dapat menghapus penguji yang sudah diassign ke station. Hapus assignment terlebih dahulu.";
        } else {
            $stmt = $pdo->prepare("DELETE FROM penguji WHERE id = ?");
            $stmt->execute([$penguji_id]);
            $success_message = "Penguji berhasil dihapus";
        }
    } catch (PDOException $e) {
        $error_message = "Error menghapus penguji: " . $e->getMessage();
    }
}

// PROSES EDIT PENGUJI
if (isset($_POST['edit_penguji'])) {
    $penguji_id = $_POST['penguji_id'];
    $nama = trim($_POST['nama']);
    $nip = trim($_POST['nip']);
    $spesialisasi = trim($_POST['spesialisasi']);
    
    if (empty($nama) || empty($nip)) {
        $error_message = "Nama dan NIP harus diisi";
    } else {
        try {
            $checkNip = $pdo->prepare("SELECT id FROM penguji WHERE nip = ? AND id != ?");
            $checkNip->execute([$nip, $penguji_id]);
            
            if ($checkNip->fetch()) {
                $error_message = "NIP $nip sudah terdaftar oleh penguji lain";
            } else {
                $stmt = $pdo->prepare("UPDATE penguji SET nama = ?, nip = ?, spesialisasi = ? WHERE id = ?");
                $stmt->execute([$nama, $nip, $spesialisasi, $penguji_id]);
                $success_message = "Data penguji berhasil diperbarui";
            }
        } catch (PDOException $e) {
            $error_message = "Error mengupdate penguji: " . $e->getMessage();
        }
    }
}

// ========== FUNCTION ASSIGN PENGUJI ==========

function assignPengujiToStations($pdo, $penguji_id, $ujian_id, $stations, $peran = 'penguji1') {
    $checkUjian = $pdo->prepare("SELECT id, nama_ujian FROM ujian WHERE id = ?");
    $checkUjian->execute([$ujian_id]);
    $ujian = $checkUjian->fetch();
    
    if (!$ujian) {
        return ["error" => "Ujian tidak ditemukan"];
    }
    
    $checkPenguji = $pdo->prepare("SELECT id, nama FROM penguji WHERE id = ?");
    $checkPenguji->execute([$penguji_id]);
    $penguji = $checkPenguji->fetch();
    
    if (!$penguji) {
        return ["error" => "Penguji tidak ditemukan"];
    }
    
    $placeholders = implode(',', array_fill(0, count($stations), '?'));
    $getStationsInfo = $pdo->prepare("
        SELECT us.station_id, us.urutan, s.nama_station 
        FROM ujian_stations us 
        JOIN stations s ON us.station_id = s.id 
        WHERE us.ujian_id = ? AND us.station_id IN ($placeholders)
        ORDER BY us.urutan
    ");
    $params = array_merge([$ujian_id], $stations);
    $getStationsInfo->execute($params);
    $stationsInfo = $getStationsInfo->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($stationsInfo)) {
        return ["error" => "Tidak ada station yang valid untuk ujian ini"];
    }
    
    $successCount = 0;
    $errors = [];
    
    foreach ($stationsInfo as $station) {
        try {
            $checkAssignment = $pdo->prepare("
                SELECT id FROM penguji_station 
                WHERE penguji_id = ? 
                AND station_id = ? 
                AND ujian_id = ? 
                AND peran = ?
            ");
            $checkAssignment->execute([$penguji_id, $station['station_id'], $ujian_id, $peran]);
            
            if ($checkAssignment->fetch()) {
                $errors[] = "Penguji sudah diassign ke station " . $station['nama_station'] . " sebagai " . $peran;
                continue;
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO penguji_station (penguji_id, station_id, ujian_id, urutan, peran) 
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $penguji_id, 
                $station['station_id'], 
                $ujian_id, 
                $station['urutan'], 
                $peran
            ]);
            $successCount++;
            
        } catch (PDOException $e) {
            $errors[] = "Station " . $station['nama_station'] . ": " . $e->getMessage();
        }
    }
    
    return [
        "success" => $successCount,
        "total_stations" => count($stationsInfo),
        "errors" => $errors,
        "ujian_nama" => $ujian['nama_ujian'],
        "penguji_nama" => $penguji['nama'],
        "peran" => $peran
    ];
}

function assignPengujiToAllStations($pdo, $penguji_id, $ujian_id, $peran = 'penguji1') {
    $checkUjian = $pdo->prepare("SELECT id, nama_ujian FROM ujian WHERE id = ?");
    $checkUjian->execute([$ujian_id]);
    $ujian = $checkUjian->fetch();
    
    if (!$ujian) {
        return ["error" => "Ujian tidak ditemukan"];
    }
    
    $getStations = $pdo->prepare("
        SELECT us.station_id, us.urutan, s.nama_station 
        FROM ujian_stations us 
        JOIN stations s ON us.station_id = s.id 
        WHERE us.ujian_id = ? 
        ORDER BY us.urutan
    ");
    $getStations->execute([$ujian_id]);
    $stations = $getStations->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($stations)) {
        return ["error" => "Tidak ada station yang terdaftar untuk ujian: " . $ujian['nama_ujian']];
    }
    
    $stationIds = array_column($stations, 'station_id');
    return assignPengujiToStations($pdo, $penguji_id, $ujian_id, $stationIds, $peran);
}

// ========== PROSES ASSIGN PENGUJI ==========
if (isset($_POST['assign_penguji'])) {
    $penguji_id = $_POST['penguji_id'];
    $ujian_id = $_POST['ujian_id'];
    $peran = $_POST['peran'] ?? 'penguji1';
    $assign_type = $_POST['assign_type'];
    
    if ($assign_type === 'all') {
        $result = assignPengujiToAllStations($pdo, $penguji_id, $ujian_id, $peran);
    } else {
        $selected_stations = isset($_POST['stations']) ? $_POST['stations'] : [];
        if (empty($selected_stations)) {
            $error_message = "Pilih minimal satu station";
        } else {
            $result = assignPengujiToStations($pdo, $penguji_id, $ujian_id, $selected_stations, $peran);
        }
    }
    
    if (isset($result['error'])) {
        $error_message = $result['error'];
    } elseif (isset($result)) {
        $success_message = "Berhasil menambahkan penguji " . $result['penguji_nama'] . 
                          " sebagai " . $result['peran'] . " ke " . $result['success'] . 
                          " station pada ujian: " . $result['ujian_nama'];
        if (!empty($result['errors'])) {
            $error_message = "Beberapa error terjadi: " . implode(", ", $result['errors']);
        }
    }
}

// PROSES HAPUS PENGUJI DARI STATION
if (isset($_GET['delete_assignment'])) {
    $assignment_id = $_GET['assignment_id'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM penguji_station WHERE id = ?");
        $stmt->execute([$assignment_id]);
        $success_message = "Assignment penguji berhasil dihapus";
    } catch (PDOException $e) {
        $error_message = "Error menghapus assignment: " . $e->getMessage();
    }
}

// PROSES HAPUS SEMUA ASSIGNMENT
if (isset($_GET['delete_all_assignments'])) {
    try {
        // Hapus semua data di penguji_station
        $stmt = $pdo->prepare("DELETE FROM penguji_station");
        $stmt->execute();
        $success_message = "Semua assignment penguji berhasil dihapus!";
    } catch (PDOException $e) {
        $error_message = "Error menghapus semua assignment: " . $e->getMessage();
    }
}

// PROSES UPDATE PERAN PENGUJI
if (isset($_POST['update_peran'])) {
    $assignment_id = $_POST['assignment_id'];
    $peran_baru = $_POST['peran_baru'];
    
    try {
        $stmt = $pdo->prepare("UPDATE penguji_station SET peran = ? WHERE id = ?");
        $stmt->execute([$peran_baru, $assignment_id]);
        $success_message = "Peran penguji berhasil diperbarui";
    } catch (PDOException $e) {
        $error_message = "Error mengupdate peran: " . $e->getMessage();
    }
}

// Ambil data untuk dropdown
try {
    $pengujiList = $pdo->query("SELECT id, nama, nip, spesialisasi FROM penguji ORDER BY nama")->fetchAll(PDO::FETCH_ASSOC);
    
    $ujianList = $pdo->query("
    SELECT u.id, u.nama_ujian, u.tanggal_ujian, COUNT(us.station_id) as total_station 
    FROM ujian u 
    LEFT JOIN ujian_stations us ON u.id = us.ujian_id 
    WHERE u.status = 'aktif'
    GROUP BY u.id
    ORDER BY u.tanggal_ujian DESC
")->fetchAll(PDO::FETCH_ASSOC);
    
    $assignedPenguji = $pdo->query("
        SELECT 
            ps.id as assignment_id,
            ps.penguji_id,
            p.nama as penguji_nama,
            p.nip,
            ps.station_id,
            s.nama_station,
            ps.ujian_id,
            u.nama_ujian,
            ps.urutan,
            COALESCE(ps.peran, 'tidak_diketahui') as peran
        FROM penguji_station ps
        JOIN penguji p ON ps.penguji_id = p.id
        JOIN stations s ON ps.station_id = s.id
        JOIN ujian u ON ps.ujian_id = u.id
        ORDER BY u.nama_ujian, ps.urutan, ps.peran
    ")->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 Penguji | SOCA 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;
        }

        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        .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 {
            flex: 1;
            margin-left: 280px;
            padding: 1.5rem 2rem 2rem;
        }

        .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 {
            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;
        }

        .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;
        }

        .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);
        }

        .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-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-primary {
            background: transparent;
            color: #1958e1;
            border: 2px solid #1958e1;
        }

        .btn-outline-primary:hover {
            background: #1958e1;
            color: white;
        }

        .btn-outline-danger {
            background: transparent;
            color: #ef4444;
            border: 2px solid #ef4444;
        }

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

        .station-checkbox {
            max-height: 200px;
            overflow-y: auto;
            border: 2px solid #e2e8f0;
            border-radius: 14px;
            padding: 1rem;
            background: #f8fafc;
        }

        .station-checkbox .form-check {
            padding: 0.5rem;
            border-radius: 8px;
            transition: background 0.2s;
        }

        .station-checkbox .form-check:hover {
            background: #eef2ff;
        }

        .station-checkbox .form-check-input {
            accent-color: #1958e1;
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .badge-peran {
            font-size: 0.7rem;
            padding: 0.3rem 0.8rem;
            border-radius: 30px;
            font-weight: 600;
        }

        .badge-peran.bg-primary { background: #667eea; color: white; }
        .badge-peran.bg-success { background: #10b981; color: white; }
        .badge-peran.bg-warning { background: #f59e0b; color: white; }
        .badge-peran.bg-danger { background: #ef4444; color: white; }
        .badge-peran.bg-info { background: #3b82f6; color: white; }
        .badge-peran.bg-dark { background: #1e293b; color: white; }
        .badge-peran.bg-secondary { background: #94a3b8; color: white; }

        .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: linear-gradient(135deg, #667eea, #1958e1);
        }

        .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: #ffffff;
            border-bottom: 2px solid #e2e8f0;
        }

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

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

        .penguji-item {
            padding: 0.8rem 1rem;
            border-radius: 12px;
            border: 1px solid #eef2ff;
            margin-bottom: 0.8rem;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .penguji-item:hover {
            border-color: #c7d2fe;
            background: #f8f9ff;
        }

        .penguji-item h6 {
            font-weight: 600;
            color: #0f172a;
            margin: 0;
        }

        .penguji-item small {
            color: #64748b;
        }

        .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); }
        }

        @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; }
            .penguji-item { flex-direction: column; gap: 0.5rem; align-items: stretch; }
        }

        ::-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"><i class="fas fa-users"></i> <span>Kelola Peserta</span></a>
            <a href="penguji.php" class="nav-item active"><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-chalkboard-user" style="margin-right: 10px; color: #1958e1;"></i>Kelola Penguji 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; ?>

        <div class="row">
            <!-- Assign Penguji -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-user-plus"></i> Assign Penguji ke Station</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="assignForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label><i class="fas fa-user-tie"></i> Pilih Penguji</label>
                                        <select name="penguji_id" class="form-control" required>
                                            <option value="">-- Pilih Penguji --</option>
                                            <?php foreach ($pengujiList as $penguji): ?>
                                                <option value="<?= $penguji['id'] ?>">
                                                    <?= htmlspecialchars($penguji['nama']) ?> (<?= htmlspecialchars($penguji['nip']) ?>)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label><i class="fas fa-tag"></i> Peran Penguji</label>
                                        <select name="peran" class="form-control" required>
                                            <option value="penguji1">Penguji 1</option>
                                            <option value="penguji2">Penguji 2</option>
                                            <option value="penguji3">Penguji 3</option>
                                            <option value="penguji4">Penguji 4</option>
                                            <option value="penguji5">Penguji 5</option>
                                            <option value="penguji6">Penguji 6</option>
                                            <option value="penguji7">Penguji 7</option>
                                            <option value="penguji8">Penguji 8</option>
                                            <option value="penguji9">Penguji 9</option>
                                            <option value="penguji10">Penguji 10</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label><i class="fas fa-calendar"></i> Pilih Ujian</label>
                                <select name="ujian_id" id="ujian_id" class="form-control" required onchange="loadStations()">
                                    <option value="">-- Pilih Ujian --</option>
                                    <?php foreach ($ujianList as $ujian): ?>
                                        <option value="<?= $ujian['id'] ?>">
                                            <?= htmlspecialchars($ujian['nama_ujian']) ?> 
                                            (<?= date('d/m/Y', strtotime($ujian['tanggal_ujian'])) ?>) 
                                            - <?= $ujian['total_station'] ?> station
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label><i class="fas fa-cog"></i> Tipe Assignment</label>
                                <div style="display: flex; gap: 1.5rem;">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="assign_type" id="assign_all" value="all" checked onchange="toggleStationSelection()">
                                        <label class="form-check-label" for="assign_all">Semua Station</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="assign_type" id="assign_selected" value="selected" onchange="toggleStationSelection()">
                                        <label class="form-check-label" for="assign_selected">Station Tertentu</label>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group" id="stationSelection" style="display: none;">
                                <label><i class="fas fa-geo-alt"></i> Pilih Station</label>
                                <div class="station-checkbox" id="stationsContainer">
                                    <div class="text-muted">Pilih ujian terlebih dahulu</div>
                                </div>
                            </div>
                            
                            <button type="submit" name="assign_penguji" class="btn btn-primary btn-lg">
                                <i class="fas fa-save"></i> Assign Penguji
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Daftar Penguji -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-users"></i> Daftar Penguji</h5>
                        <button type="button" class="btn btn-success btn-sm" onclick="openTambahModal()">
                            <i class="fas fa-plus"></i> Tambah
                        </button>
                    </div>
                    <div class="card-body">
                        <?php if (empty($pengujiList)): ?>
                            <p class="text-muted text-center py-3">Belum ada penguji.</p>
                        <?php else: ?>
                            <?php foreach ($pengujiList as $penguji): ?>
                                <div class="penguji-item">
                                    <div>
                                        <h6><?= htmlspecialchars($penguji['nama']) ?></h6>
                                        <small><i class="fas fa-id-card"></i> <?= htmlspecialchars($penguji['nip']) ?></small>
                                        <?php if (!empty($penguji['spesialisasi'])): ?>
                                            <br><small class="text-muted"><?= htmlspecialchars($penguji['spesialisasi']) ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <div style="display: flex; gap: 0.3rem;">
                                        <button type="button" class="btn btn-sm btn-outline-primary edit-penguji-btn" 
                                                data-id="<?= $penguji['id'] ?>"
                                                data-nama="<?= htmlspecialchars($penguji['nama']) ?>"
                                                data-nip="<?= htmlspecialchars($penguji['nip']) ?>"
                                                data-spesialisasi="<?= htmlspecialchars($penguji['spesialisasi'] ?? '') ?>">
                                            <i class="fas fa-pen"></i>
                                        </button>
                                        <a href="?delete_penguji=1&penguji_id=<?= $penguji['id'] ?>" 
                                           class="btn btn-sm btn-outline-danger"
                                           onclick="return confirm('Hapus penguji ini?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Daftar Penguji yang Sudah Diassign -->
        <div class="card">
    <div class="card-header">
        <h5><i class="fas fa-list-check"></i> Penguji yang Sudah Diassign</h5>
        <div style="display: flex; gap: 0.5rem; align-items: center;">
            <span class="badge" style="background: #10b981; color: white; padding: 0.3rem 1rem; border-radius: 30px; font-size: 0.7rem;">
                <i class="fas fa-user"></i> <?= count($assignedPenguji) ?> assignment
            </span>
            <?php if (!empty($assignedPenguji)): ?>
                <a href="?delete_all_assignments=1" 
                   class="btn btn-danger btn-sm" 
                   onclick="return confirm('⚠️ PERINGATAN!\n\nAnda akan menghapus SEMUA assignment penguji.\n\nJumlah: <?= count($assignedPenguji) ?> assignment\n\nLanjutkan?')">
                    <i class="fas fa-trash-alt"></i> Hapus Semua
                </a>
            <?php endif; ?>
        </div>
    </div>
            <div class="card-body">
                <?php if (empty($assignedPenguji)): ?>
                    <p class="text-muted text-center py-4">Belum ada penguji yang diassign ke station.</p>
                <?php else: ?>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Nama Penguji</th>
                                    <th>NIP</th>
                                    <th>Ujian</th>
                                    <th>Station</th>
                                    <th>Urutan</th>
                                    <th>Peran</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($assignedPenguji as $assign): 
                                    $peran = $assign['peran'];
                                    $peran_display = ucfirst($peran);
                                    $peran_class = 'bg-secondary';
                                    if ($peran == 'penguji1') $peran_class = 'bg-primary';
                                    elseif ($peran == 'penguji2') $peran_class = 'bg-warning';
                                    elseif ($peran == 'penguji3') $peran_class = 'bg-info';
                                    elseif ($peran == 'penguji4') $peran_class = 'bg-success';
                                    elseif ($peran == 'penguji5') $peran_class = 'bg-danger';
                                    elseif ($peran == 'penguji6') $peran_class = 'bg-dark';
                                    elseif ($peran == 'penguji7') $peran_class = 'bg-secondary';
                                    elseif ($peran == 'penguji8') $peran_class = 'bg-primary';
                                    elseif ($peran == 'penguji9') $peran_class = 'bg-info';
                                    elseif ($peran == 'penguji10') $peran_class = 'bg-warning';
                                ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($assign['penguji_nama']) ?></strong></td>
                                        <td><?= htmlspecialchars($assign['nip']) ?></td>
                                        <td><?= htmlspecialchars($assign['nama_ujian']) ?></td>
                                        <td><?= htmlspecialchars($assign['nama_station']) ?></td>
                                        <td><?= $assign['urutan'] ?></td>
                                        <td>
                                            <span class="badge-peran <?= $peran_class ?>"><?= $peran_display ?></span>
                                            <button type="button" class="btn btn-sm btn-warning" onclick="editPeran(<?= $assign['assignment_id'] ?>, '<?= $peran ?>')">
                                                <i class="fas fa-pen"></i>
                                            </button>
                                        </td>
                                        <td>
                                            <a href="?delete_assignment=1&assignment_id=<?= $assign['assignment_id'] ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('Hapus assignment ini?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Modal Tambah Penguji -->
<div id="tambahPengujiModal" class="modal-overlay-custom">
    <div class="modal-content-custom">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h4 style="font-weight: 700; color: #0f172a;"><i class="fas fa-user-plus" style="color: #667eea;"></i> Tambah Penguji</h4>
            <button type="button" class="btn btn-secondary btn-sm" onclick="closeTambahModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" action="">
            <div class="form-group">
                <label>Nama Penguji</label>
                <input type="text" class="form-control" name="nama" required>
            </div>
            <div class="form-group">
                <label>NIP</label>
                <input type="text" class="form-control" name="nip" required>
            </div>
            <div class="form-group">
                <label>Spesialisasi</label>
                <input type="text" class="form-control" name="spesialisasi">
            </div>
            <button type="submit" name="tambah_penguji" class="btn btn-success" style="width: 100%;"><i class="fas fa-save"></i> Tambah Penguji</button>
        </form>
    </div>
</div>

<!-- Modal Edit Penguji -->
<div id="editPengujiModal" class="modal-overlay-custom">
    <div class="modal-content-custom">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h4 style="font-weight: 700; color: #0f172a;"><i class="fas fa-user-edit" style="color: #667eea;"></i> Edit Penguji</h4>
            <button type="button" class="btn btn-secondary btn-sm" onclick="closeEditModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" action="" id="editPengujiForm">
            <input type="hidden" name="penguji_id" id="edit_penguji_id">
            <div class="form-group">
                <label>Nama Penguji</label>
                <input type="text" class="form-control" id="edit_nama" name="nama" required>
            </div>
            <div class="form-group">
                <label>NIP</label>
                <input type="text" class="form-control" id="edit_nip" name="nip" required>
            </div>
            <div class="form-group">
                <label>Spesialisasi</label>
                <input type="text" class="form-control" id="edit_spesialisasi" name="spesialisasi">
            </div>
            <button type="submit" name="edit_penguji" class="btn btn-primary" style="width: 100%;"><i class="fas fa-save"></i> Simpan</button>
        </form>
    </div>
</div>

<!-- Modal Edit Peran -->
<div id="editPeranModal" class="modal-overlay-custom">
    <div class="modal-content-custom">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h4 style="font-weight: 700; color: #0f172a;"><i class="fas fa-tag" style="color: #667eea;"></i> Edit Peran Penguji</h4>
            <button type="button" class="btn btn-secondary btn-sm" onclick="closeEditPeranModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" action="">
            <input type="hidden" name="assignment_id" id="edit_assignment_id">
            <div class="form-group">
                <label>Pilih Peran</label>
                <select name="peran_baru" class="form-control" required>
                    <option value="penguji1">Penguji 1</option>
                    <option value="penguji2">Penguji 2</option>
                    <option value="penguji3">Penguji 3</option>
                    <option value="penguji4">Penguji 4</option>
                    <option value="penguji5">Penguji 5</option>
                    <option value="penguji6">Penguji 6</option>
                    <option value="penguji7">Penguji 7</option>
                    <option value="penguji8">Penguji 8</option>
                    <option value="penguji9">Penguji 9</option>
                    <option value="penguji10">Penguji 10</option>
                </select>
            </div>
            <button type="submit" name="update_peran" class="btn btn-primary" style="width: 100%;"><i class="fas fa-save"></i> Simpan Peran</button>
        </form>
    </div>
</div>

<script>
    // Modal functions
    function openTambahModal() {
        document.getElementById('tambahPengujiModal').classList.add('show');
    }

    function closeTambahModal() {
        document.getElementById('tambahPengujiModal').classList.remove('show');
    }

    function openEditModal(data) {
        document.getElementById('edit_penguji_id').value = data.id;
        document.getElementById('edit_nama').value = data.nama;
        document.getElementById('edit_nip').value = data.nip;
        document.getElementById('edit_spesialisasi').value = data.spesialisasi || '';
        document.getElementById('editPengujiModal').classList.add('show');
    }

    function closeEditModal() {
        document.getElementById('editPengujiModal').classList.remove('show');
    }

    function editPeran(assignmentId, currentPeran) {
        document.getElementById('edit_assignment_id').value = assignmentId;
        const select = document.querySelector('select[name="peran_baru"]');
        if (currentPeran && currentPeran !== 'tidak_diketahui') {
            select.value = currentPeran;
        } else {
            select.value = 'penguji1';
        }
        document.getElementById('editPeranModal').classList.add('show');
    }

    function closeEditPeranModal() {
        document.getElementById('editPeranModal').classList.remove('show');
    }

    document.querySelectorAll('.edit-penguji-btn').forEach(button => {
        button.addEventListener('click', function() {
            openEditModal({
                id: this.dataset.id,
                nama: this.dataset.nama,
                nip: this.dataset.nip,
                spesialisasi: this.dataset.spesialisasi
            });
        });
    });

    function toggleStationSelection() {
        const assignSelected = document.getElementById('assign_selected').checked;
        document.getElementById('stationSelection').style.display = assignSelected ? 'block' : 'none';
        if (assignSelected) loadStations();
    }

    function loadStations() {
        const ujianId = document.getElementById('ujian_id').value;
        const container = document.getElementById('stationsContainer');
        
        if (!ujianId) {
            container.innerHTML = '<div class="text-muted">Pilih ujian terlebih dahulu</div>';
            return;
        }
        
        container.innerHTML = '<div class="text-muted">Memuat data...</div>';
        
        fetch(`get_stations.php?ujian_id=${ujianId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    container.innerHTML = `<div class="text-danger">${data.error}</div>`;
                    return;
                }
                if (!data.stations || data.stations.length === 0) {
                    container.innerHTML = '<div class="text-muted">Tidak ada station</div>';
                    return;
                }
                let html = '';
                data.stations.forEach(station => {
                    html += `
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="stations[]" value="${station.station_id}" id="station_${station.station_id}">
                            <label class="form-check-label" for="station_${station.station_id}">
                                <i class="fas fa-geo-alt" style="color: #667eea;"></i>
                                Station ${station.urutan}: ${station.nama_station}
                            </label>
                        </div>
                    `;
                });
                container.innerHTML = html;
            })
            .catch(error => {
                container.innerHTML = '<div class="text-danger">Error loading stations</div>';
            });
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            document.querySelectorAll('.modal-overlay-custom.show').forEach(modal => {
                modal.classList.remove('show');
            });
        }
    });

    document.querySelectorAll('.modal-overlay-custom').forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.remove('show');
            }
        });
    });
</script>
</body>
</html>