<?php
require_once '../includes/auth.php'; // Include auth.php
require_once '../includes/functions.php'; // Include 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 {
            // Cek duplikasi NIP
            $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 {
        // Cek apakah penguji sudah diassign ke station
        $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 form assign penguji
if (isset($_POST['assign_penguji'])) {
    $penguji_id = $_POST['penguji_id'];
    $ujian_id = $_POST['ujian_id'];
    $peran = $_POST['peran'];
    $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'];
    } else {
        $success_message = "Berhasil menambahkan penguji " . $result['penguji_nama'] . 
                          " sebagai " . $peran . " ke " . $result['success'] . 
                          " station pada ujian: " . $result['ujian_nama'];
        if (!empty($result['errors'])) {
            $error_message = "Beberapa error terjadi: " . implode(", ", $result['errors']);
        }
    }
}

// Function untuk assign penguji ke station dalam ujian
function assignPengujiToStations($pdo, $penguji_id, $ujian_id, $stations, $peran = 'penguji1') {
    // Validasi ujian
    $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"];
    }
    
    // Validasi penguji
    $checkPenguji = $pdo->prepare("SELECT id, nama FROM penguji WHERE id = ?");
    $checkPenguji->execute([$penguji_id]);
    $penguji = $checkPenguji->fetch();
    
    if (!$penguji) {
        return ["error" => "Penguji tidak ditemukan"];
    }
    
    // Ambil urutan dari ujian_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 (" . implode(',', $stations) . ")
        ORDER BY us.urutan
    ");
    $getStationsInfo->execute([$ujian_id]);
    $stationsInfo = $getStationsInfo->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($stationsInfo)) {
        return ["error" => "Tidak ada station yang valid untuk ujian ini"];
    }
    
    // Insert ke station yang dipilih
    $successCount = 0;
    $errors = [];
    
   foreach ($stationsInfo as $station) {
        try {
            // Cek apakah penguji sudah diassign ke station ini dengan peran yang sama
            $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;
            }
            
            // Insert data dengan peran yang spesifik
            $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 untuk assign penguji ke SEMUA station dalam ujian
function assignPengujiToAllStations($pdo, $penguji_id, $ujian_id, $peran = 'penguji1') {
    // Validasi ujian
    $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"];
    }
    
    // Ambil semua station untuk ujian ini
    $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 form assign penguji
if (isset($_POST['assign_penguji'])) {
    $penguji_id = $_POST['penguji_id'];
    $ujian_id = $_POST['ujian_id'];
    $peran = $_POST['peran'];
    $assign_type = $_POST['assign_type'];
    
    if ($assign_type === 'all') {
        // Assign ke semua station
        $result = assignPengujiToAllStations($pdo, $penguji_id, $ujian_id, $peran);
    } else {
        // Assign ke station tertentu
        $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'];
    } else {
        $success_message = "Berhasil menambahkan penguji " . $result['penguji_nama'] . 
                          " sebagai " . $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();
    }
}

// Ambil data untuk dropdown
try {
    // Daftar penguji
    $pengujiList = $pdo->query("SELECT id, nama, nip FROM penguji ORDER BY nama")->fetchAll(PDO::FETCH_ASSOC);
    
    // Daftar ujian dengan jumlah station
    $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 
        GROUP BY u.id
        ORDER BY u.tanggal_ujian DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Data penguji yang sudah diassign
    $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,
            ps.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();
}

// Setelah proses assign penguji, tambahkan:
if (isset($result['success'])) {
    // Debug: Tampilkan data yang disimpan
    $debug_stmt = $pdo->prepare("
        SELECT ps.*, p.nama, s.nama_station, u.nama_ujian 
        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
        WHERE ps.penguji_id = ? AND ps.ujian_id = ?
    ");
    $debug_stmt->execute([$penguji_id, $ujian_id]);
    $debug_data = $debug_stmt->fetchAll();
    
    error_log("DEBUG Assign Penguji: " . print_r($debug_data, true));
}
?>

<!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://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3b5998;
            --secondary-color: #f8f9fa;
        }
        
        .sidebar {
            width: 280px;
            background: linear-gradient(to bottom, var(--primary-color), #2d4373);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
        }
        
        .content {
            margin-left: 280px;
            padding: 30px;
            background-color: #f5f7fb;
            min-height: 100vh;
        }
        
        .page-header {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
        }
        
        .card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .table th {
            background-color: var(--primary-color);
            color: white;
        }
        
        .station-checkbox {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .badge-peran {
            font-size: 0.8rem;
        }
    </style>
</head>
<body>
    <!-- Sidebar 
    <div class="sidebar">
        <div class="sidebar-header">
            <h4>SOCA OSCE System</h4>
            <small>Admin Panel</small>
        </div>
        <div class="sidebar-content py-3">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="dashboard.php">
                        <i class="bi bi-speedometer2 me-2"></i>Dashboard
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="ujian.php">
                        <i class="bi bi-journal-text me-2"></i>Kelola Ujian
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="stations.php">
                        <i class="bi bi-geo-alt me-2"></i>Kelola Stations
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="peserta.php">
                        <i class="bi bi-people me-2"></i>Kelola Peserta
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="penguji.php">
                        <i class="bi bi-person-check me-2"></i>Kelola Penguji
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="penilaian.php">
                        <i class="bi bi-clipboard-check me-2"></i>Penilaian
                    </a>
                </li>
                <li class="nav-item mt-4">
                    <a class="nav-link" href="../logout.php">
                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                    </a>
                </li>
            </ul>
        </div>
    </div> -->

    <!-- Main Content -->
    <div class="content">
        <!-- Page Header -->
        <div class="page-header">
            <h2 class="mb-0"><i class="bi bi-person-check me-2"></i>Kelola Penguji Station</h2>
            <p class="text-muted mb-0">Assign penguji ke station-station ujian OSCE</p>
        </div>

        <div class="action-buttons">
            <a href="dashboard.php" class="btn btn-primary btn-lg">
                <i class="fas fa-question-circle"></i> Dashboard
            </a>
            <a href="soal.php" class="btn btn-primary btn-lg">
                <i class="fas fa-question-circle"></i> Kelola Soal
            </a>
            <a href="ujian.php" class="btn btn-primary btn-lg">
                <i class="fas fa-clipboard-list"></i> Kelola Ujian
            </a>
            <a href="peserta.php" class="btn btn-primary btn-lg">
                <i class="fas fa-users"></i> Kelola Peserta
            </a>
            <a href="penguji.php" class="btn btn-primary btn-lg">
                <i class="fas fa-user-check"></i> Kelola Penguji
            </a>
            <a href="nilai.php" class="btn btn-primary btn-lg">
                <i class="fas fa-chart-bar"></i> Lihat Nilai
            </a>
        </div>
        &nbsp;
        &nbsp;

        <!-- Alert Messages -->
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bi bi-check-circle me-2"></i><?= $success_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bi bi-exclamation-triangle me-2"></i><?= $error_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

         <!-- Form Tambah Penguji Baru -->
        <div class="card mb-4">
            <div class="card-header bg-secondary text-white">
                <h5 class="card-title mb-0"><i class="bi bi-person-plus me-2"></i>Tambah Penguji Baru</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="nama" class="form-label">Nama Penguji</label>
                                <input type="text" class="form-control" name="nama" placeholder="Dr. Ahmad Wijaya" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="nip" class="form-label">NIP</label>
                                <input type="text" class="form-control" name="nip" placeholder="198012341234" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="spesialisasi" class="form-label">Spesialisasi</label>
                                <input type="text" class="form-control" name="spesialisasi" placeholder="Bedah, Anestesi, Kardiologi, dll">
                            </div>
                        </div>
                    </div>
                    <button type="submit" name="tambah_penguji" class="btn btn-success">
                        <i class="bi bi-plus-circle me-2"></i>Tambah Penguji
                    </button>
                </form>
            </div>
        </div>
        

        <div class="row">
            <!-- Form Assign Penguji -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0"><i class="bi bi-person-plus me-2"></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="mb-3">
                                        <label for="penguji_id" class="form-label">Pilih Penguji</label>
                                        <select name="penguji_id" class="form-select" 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="mb-3">
        <label for="peran" class="form-label">Peran Penguji</label>
        <select name="peran" class="form-select" 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="mb-3">
                                <label for="ujian_id" class="form-label">Pilih Ujian</label>
                                <select name="ujian_id" id="ujian_id" class="form-select" 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'])) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Tipe Assignment</label>
                                <div>
                                    <div class="form-check form-check-inline">
                                        <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 form-check-inline">
                                        <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="mb-3" id="stationSelection" style="display: none;">
                                <label class="form-label">Pilih Station</label>
                                <div class="station-checkbox border rounded p-3" id="stationsContainer">
                                    <div class="text-muted">Pilih ujian terlebih dahulu</div>
                                </div>
                            </div>
                            
                            <button type="submit" name="assign_penguji" class="btn btn-primary">
                                <i class="bi bi-save me-2"></i>Assign Penguji
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Info Penguji Tersedia -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h5 class="card-title mb-0"><i class="bi bi-info-circle me-2"></i>Informasi Penguji</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($pengujiList)): ?>
                            <p class="text-muted">Tidak ada penguji yang tersedia.</p>
                        <?php else: ?>
                            <?php foreach ($pengujiList as $penguji): ?>
                                <div class="mb-2 p-2 border rounded">
                                    <h6 class="mb-1"><?= htmlspecialchars($penguji['nama']) ?></h6>
                                    <small class="text-muted">NIP: <?= htmlspecialchars($penguji['nip']) ?></small>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Daftar Penguji yang Sudah Diassign -->
        <div class="card mt-4">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0"><i class="bi bi-list-check me-2"></i>Penguji yang Sudah Diassign</h5>
            </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-responsive">
                        <table class="table table-striped table-hover">
                            <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): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($assign['penguji_nama']) ?></td>
                                        <td><?= htmlspecialchars($assign['nip']) ?></td>
                                        <td><?= htmlspecialchars($assign['nama_ujian']) ?></td>
                                        <td><?= htmlspecialchars($assign['nama_station']) ?></td>
                                        <td><?= $assign['urutan'] ?></td>
                                        <td>
                                            <?php 
                                            $peran_class = 'bg-primary';
                                            if ($assign['peran'] === 'penguji2') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji3') $peran_class = 'bg-info';
                                            if ($assign['peran'] === 'penguji4') $peran_class = 'bg-info';
                                            if ($assign['peran'] === 'penguji5') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji6') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji7') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji8') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji9') $peran_class = 'bg-warning';
                                            if ($assign['peran'] === 'penguji10') $peran_class = 'bg-warning';
                                            ?>
                                            <span class="badge <?= $peran_class ?> badge-peran">
                                                <?= ucfirst($assign['peran']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="?delete_assignment=1&assignment_id=<?= $assign['assignment_id'] ?>" 
                                               class="btn btn-danger btn-sm"
                                               onclick="return confirm('Apakah Anda yakin ingin menghapus assignment ini?')">
                                                <i class="bi bi-trash"></i> Hapus
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleStationSelection() {
            const assignSelected = document.getElementById('assign_selected').checked;
            const stationSelection = document.getElementById('stationSelection');
            stationSelection.style.display = assignSelected ? 'block' : 'none';
            
            if (assignSelected) {
                loadStations();
            }
        }
        
        function loadStations() {
            const ujianId = document.getElementById('ujian_id').value;
            const stationsContainer = document.getElementById('stationsContainer');
            
            if (!ujianId) {
                stationsContainer.innerHTML = '<div class="text-muted">Pilih ujian terlebih dahulu</div>';
                return;
            }
            
            // AJAX untuk mengambil stations
            fetch(`get_stations.php?ujian_id=${ujianId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        stationsContainer.innerHTML = `<div class="text-danger">${data.error}</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}">
                                    Station ${station.urutan}: ${station.nama_station}
                                </label>
                            </div>
                        `;
                    });
                    
                    stationsContainer.innerHTML = html;
                })
                .catch(error => {
                    stationsContainer.innerHTML = '<div class="text-danger">Error loading stations</div>';
                    console.error('Error:', error);
                });
        }
    </script>
</body>
</html>