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

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


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

// Function untuk assign peserta ke semua station dalam ujian
function assignPesertaToAllStations($pdo, $peserta_id, $ujian_id, $status = 'belum_mulai') {
    // 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']];
    }
    
    // Cek apakah peserta sudah terdaftar di ujian ini
    $checkPeserta = $pdo->prepare("SELECT id FROM peserta_station WHERE peserta_id = ? AND ujian_id = ?");
    $checkPeserta->execute([$peserta_id, $ujian_id]);
    
    if ($checkPeserta->fetch()) {
        return ["error" => "Peserta sudah terdaftar di ujian ini"];
    }
    
    // Insert ke semua station
    $successCount = 0;
    $errors = [];
    
    foreach ($stations as $station) {
        try {
            $stmt = $pdo->prepare("INSERT INTO peserta_station (peserta_id, station_id, ujian_id, urutan, status) 
                                  VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $peserta_id, 
                $station['station_id'], 
                $ujian_id, 
                $station['urutan'], 
                $status
            ]);
            $successCount++;
        } catch (PDOException $e) {
            $errors[] = "Station " . $station['nama_station'] . ": " . $e->getMessage();
        }
    }
    
    return [
        "success" => $successCount,
        "total_stations" => count($stations),
        "errors" => $errors,
        "ujian_nama" => $ujian['nama_ujian']
    ];
}

// Proses form assign peserta ke ujian
if (isset($_POST['assign_ujian'])) {
    $peserta_id = $_POST['peserta_id'];
    $ujian_id = $_POST['ujian_id'];
    $semester = $_POST['semester'] ?? '';
    
    $result = assignPesertaToAllStations($pdo, $peserta_id, $ujian_id, 'belum_mulai');
    
    if (isset($result['error'])) {
        $error_message = $result['error'];
    } else {
        $success_message = "Berhasil menambahkan peserta ke " . $result['success'] . " dari " . $result['total_stations'] . " station pada ujian: " . $result['ujian_nama'];
        if (!empty($result['errors'])) {
            $error_message = "Beberapa error terjadi: " . implode(", ", $result['errors']);
        }
    }
}

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

// Ambil data untuk dropdown
try {
    // Daftar semester yang tersedia
    $semesterList = $pdo->query("SELECT DISTINCT semester FROM peserta ORDER BY semester")->fetchAll(PDO::FETCH_COLUMN);
    
    // Jika belum ada data semester, set default
    if (empty($semesterList)) {
        $semesterList = [1, 3, 5, 7];
        // Insert default semester jika perlu
        // $pdo->exec("UPDATE peserta SET semester = 1 WHERE semester IS NULL");
    }
    
    // Daftar peserta (akan difilter berdasarkan semester yang dipilih)
    $selected_semester = $_POST['semester'] ?? $_GET['semester'] ?? ($semesterList[0] ?? 1);
    $pesertaList = $pdo->prepare("SELECT id, nama, nim, semester FROM peserta WHERE semester = ? ORDER BY nama");
    $pesertaList->execute([$selected_semester]);
    $pesertaList = $pesertaList->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 peserta yang sudah diassign ke ujian
    $assignedPeserta = $pdo->query("
        SELECT 
            ps.peserta_id,
            p.nama as peserta_nama,
            p.nim,
            p.semester,
            ps.ujian_id,
            u.nama_ujian,
            COUNT(ps.station_id) as total_station,
            MIN(ps.status) as status
        FROM peserta_station ps
        JOIN peserta p ON ps.peserta_id = p.id
        JOIN ujian u ON ps.ujian_id = u.id
        GROUP BY ps.peserta_id, ps.ujian_id
        ORDER BY u.nama_ujian, p.nama
    ")->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 - 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;
            --accent-color: #6c757d;
        }
        
        .sidebar { 
            width: 280px;
            background: linear-gradient(to bottom, var(--primary-color), #2d4373);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-left: 3px solid transparent;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover, 
        .sidebar .nav-link.active {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: white;
        }
        
        .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;
        }
        
        .badge-status {
            font-size: 0.8rem;
            padding: 5px 10px;
        }
        
        .semester-badge {
            font-size: 0.7rem;
            padding: 3px 8px;
            margin-left: 5px;
        }
    </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 active" href="peserta.php">
                        <i class="bi bi-people me-2"></i>Kelola Peserta
                    </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-people me-2"></i>Kelola Peserta Ujian</h2>
            <p class="text-muted mb-0">Assign peserta ke ujian OSCE berdasarkan semester</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; ?>

        <div class="row">
            <!-- Form Assign Peserta -->
            <div class="col-md-6">
                <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 Peserta ke Ujian</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="assignForm">
                            <!-- Pilih Semester -->
                            <div class="mb-3">
                                <label for="semester" class="form-label">Pilih Semester</label>
                                <select name="semester" id="semester" class="form-select" required 
                                        onchange="this.form.submit()">
                                    <option value="">-- Pilih Semester --</option>
                                    <?php foreach ($semesterList as $semester): ?>
                                        <option value="<?= $semester ?>" 
                                            <?= $selected_semester == $semester ? 'selected' : '' ?>>
                                            Semester <?= $semester ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text">Pilih semester untuk menampilkan daftar peserta</div>
                            </div>
                            
                            <!-- Pilih Peserta (akan diupdate berdasarkan semester) -->
                            <div class="mb-3">
                                <label for="peserta_id" class="form-label">Pilih Peserta</label>
                                <select name="peserta_id" id="peserta_id" class="form-select" required 
                                        <?= empty($pesertaList) ? 'disabled' : '' ?>>
                                    <option value="">-- Pilih Peserta --</option>
                                    <?php if (!empty($pesertaList)): ?>
                                        <?php foreach ($pesertaList as $peserta): ?>
                                            <option value="<?= $peserta['id'] ?>">
                                                <?= htmlspecialchars($peserta['nama']) ?> 
                                                (<?= htmlspecialchars($peserta['nim']) ?>)
                                                - Semester <?= $peserta['semester'] ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option value="">Tidak ada peserta untuk semester ini</option>
                                    <?php endif; ?>
                                </select>
                                <?php if (empty($pesertaList)): ?>
                                    <div class="form-text text-warning">
                                        <i class="bi bi-exclamation-triangle"></i>
                                        Tidak ada peserta untuk semester <?= $selected_semester ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Pilih Ujian -->
                            <div class="mb-3">
                                <label for="ujian_id" class="form-label">Pilih Ujian</label>
                                <select name="ujian_id" class="form-select" required>
                                    <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>
                            
                            <button type="submit" name="assign_ujian" class="btn btn-primary"
                                    <?= empty($pesertaList) ? 'disabled' : '' ?>>
                                <i class="bi bi-save me-2"></i>Assign ke Ujian
                            </button>
                            
                            <?php if (!empty($selected_semester)): ?>
                                <a href="tambah_peserta.php?semester=<?= $selected_semester ?>" class="btn btn-outline-primary ms-2">
                                    <i class="bi bi-person-add me-2"></i>Tambah Peserta Semester <?= $selected_semester ?>
                                </a>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Info Ujian Tersedia -->
            <div class="col-md-6">
                <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 Ujian & Semester</h5>
                    </div>
                    <div class="card-body">
                        <!-- Info Semester -->
                        <div class="mb-4">
                            <h6 class="border-bottom pb-2">Data Semester</h6>
                            <div class="row text-center">
                                <?php 
                                // Hitung jumlah peserta per semester
                                $stmt = $pdo->prepare("SELECT semester, COUNT(*) as total FROM peserta GROUP BY semester ORDER BY semester");
                                $stmt->execute();
                                $pesertaPerSemester = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                ?>
                                <?php foreach ($pesertaPerSemester as $data): ?>
                                    <div class="col-6 mb-2">
                                        <div class="p-2 border rounded">
                                            <small class="text-muted d-block">Semester <?= $data['semester'] ?></small>
                                            <strong class="text-primary"><?= $data['total'] ?> Peserta</strong>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Info Ujian -->
                        <div>
                            <h6 class="border-bottom pb-2">Ujian Tersedia</h6>
                            <?php if (empty($ujianList)): ?>
                                <p class="text-muted">Tidak ada ujian yang tersedia.</p>
                            <?php else: ?>
                                <?php foreach ($ujianList as $ujian): ?>
                                    <div class="mb-3 p-3 border rounded">
                                        <h6 class="mb-1"><?= htmlspecialchars($ujian['nama_ujian']) ?></h6>
                                        <small class="text-muted">
                                            <i class="bi bi-calendar me-1"></i><?= date('d/m/Y', strtotime($ujian['tanggal_ujian'])) ?>
                                            | <i class="bi bi-geo-alt me-1"></i><?= $ujian['total_station'] ?> Station
                                        </small>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Daftar Peserta 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>Peserta yang Sudah Diassign
                    <?php if (!empty($selected_semester)): ?>
                        <span class="badge bg-light text-dark ms-2">Semester <?= $selected_semester ?></span>
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php 
                // Filter assigned peserta berdasarkan semester yang dipilih
                $filteredAssigned = array_filter($assignedPeserta, function($item) use ($selected_semester) {
                    return $item['semester'] == $selected_semester;
                });
                ?>
                
                <?php if (empty($filteredAssigned)): ?>
                    <p class="text-muted text-center py-4">
                        <?php if (!empty($selected_semester)): ?>
                            Belum ada peserta semester <?= $selected_semester ?> yang diassign ke ujian.
                        <?php else: ?>
                            Belum ada peserta yang diassign ke ujian.
                        <?php endif; ?>
                    </p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Nama Peserta</th>
                                    <th>NIM</th>
                                    <th>Semester</th>
                                    <th>Ujian</th>
                                    <th>Jumlah Station</th>
                                    <th>Status</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($filteredAssigned as $assign): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($assign['peserta_nama']) ?></td>
                                        <td><?= htmlspecialchars($assign['nim']) ?></td>
                                        <td>
                                            <span class="badge bg-secondary semester-badge">Semester <?= $assign['semester'] ?></span>
                                        </td>
                                        <td><?= htmlspecialchars($assign['nama_ujian']) ?></td>
                                        <td>
                                            <span class="badge bg-primary"><?= $assign['total_station'] ?> Station</span>
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = 'bg-secondary';
                                            $status_text = 'Belum Mulai';
                                            if ($assign['status'] === 'sedang_berlangsung') {
                                                $status_class = 'bg-warning';
                                                $status_text = 'Sedang Berlangsung';
                                            } elseif ($assign['status'] === 'selesai') {
                                                $status_class = 'bg-success';
                                                $status_text = 'Selesai';
                                            }
                                            ?>
                                            <span class="badge <?= $status_class ?>"><?= $status_text ?></span>
                                        </td>
                                        <td>
                                            <a href="?delete_ujian=1&peserta_id=<?= $assign['peserta_id'] ?>&ujian_id=<?= $assign['ujian_id'] ?>&semester=<?= $selected_semester ?>" 
                                               class="btn btn-danger btn-sm"
                                               onclick="return confirm('Apakah Anda yakin ingin menghapus peserta dari ujian ini?')">
                                                <i class="bi bi-trash"></i> Hapus
                                            </a>
                                            <a href="detail_peserta.php?peserta_id=<?= $assign['peserta_id'] ?>&ujian_id=<?= $assign['ujian_id'] ?>" 
                                               class="btn btn-info btn-sm">
                                                <i class="bi bi-eye"></i> Detail
                                            </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>
        // Enable/disable form berdasarkan ketersediaan peserta
        document.addEventListener('DOMContentLoaded', function() {
            const pesertaSelect = document.getElementById('peserta_id');
            const assignButton = document.querySelector('button[name="assign_ujian"]');
            
            if (pesertaSelect && pesertaSelect.options.length <= 1) {
                pesertaSelect.disabled = true;
                if (assignButton) {
                    assignButton.disabled = true;
                }
            }
        });
        
        // Auto-submit form ketika semester berubah
        function filterBySemester(semester) {
            window.location.href = '?semester=' + semester;
        }
    </script>
</body>
</html>