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

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

// Helper function untuk handle null values
function getSafeValue($data, $key, $default = '') {
    return isset($data[$key]) ? $data[$key] : $default;
}

// Helper function untuk memotong teks
function truncateText($text, $length = 100) {
    if (strlen($text) <= $length) {
        return $text;
    }
    return substr($text, 0, $length) . '...';
}

$success = '';
$error = '';

// Proses Tambah Ujian
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tambah_ujian'])) {
    $nama_ujian = sanitize($_POST['nama_ujian']);
    $tanggal_ujian = sanitize($_POST['tanggal_ujian']);
    $waktu_mulai = sanitize($_POST['waktu_mulai'] ?? '08:00');
    $waktu_selesai = sanitize($_POST['waktu_selesai'] ?? '16:00');
    $deskripsi = sanitize($_POST['deskripsi'] ?? '');
    $status = sanitize($_POST['status'] ?? 'aktif');
    $semester = intval($_POST['semester'] ?? 0);
    
    if (empty($nama_ujian) || empty($tanggal_ujian)) {
        $error = "Nama ujian dan tanggal ujian harus diisi!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO ujian (nama_ujian, tanggal_ujian, waktu_mulai, waktu_selesai, deskripsi, status, semester) VALUES (?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$nama_ujian, $tanggal_ujian, $waktu_mulai, $waktu_selesai, $deskripsi, $status, $semester])) {
            $success = "Ujian berhasil ditambahkan!";
            $_POST = array();
        } else {
            $error = "Gagal menambahkan ujian!";
        }
    }
}

// Proses Edit Ujian
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_ujian'])) {
    $id = intval($_POST['id']);
    $nama_ujian = sanitize($_POST['nama_ujian']);
    $tanggal_ujian = sanitize($_POST['tanggal_ujian']);
    $waktu_mulai = sanitize($_POST['waktu_mulai'] ?? '08:00');
    $waktu_selesai = sanitize($_POST['waktu_selesai'] ?? '16:00');
    $deskripsi = sanitize($_POST['deskripsi'] ?? '');
    $status = sanitize($_POST['status'] ?? 'aktif');
    $semester = intval($_POST['semester'] ?? 0);
    
    if (empty($nama_ujian) || empty($tanggal_ujian)) {
        $error = "Nama ujian dan tanggal ujian harus diisi!";
    } else {
        $stmt = $pdo->prepare("UPDATE ujian SET nama_ujian = ?, tanggal_ujian = ?, waktu_mulai = ?, waktu_selesai = ?, deskripsi = ?, status = ?, semester = ? WHERE id = ?");
        if ($stmt->execute([$nama_ujian, $tanggal_ujian, $waktu_mulai, $waktu_selesai, $deskripsi, $status, $semester, $id])) {
            $success = "Ujian berhasil diupdate!";
        } else {
            $error = "Gagal mengupdate ujian!";
        }
    }
}

// Proses Hapus Ujian
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);
    
    $stmt = $pdo->prepare("SELECT id FROM penilaian WHERE ujian_id = ? LIMIT 1");
    $stmt->execute([$id]);
    
    if ($stmt->rowCount() > 0) {
        $error = "Tidak dapat menghapus ujian yang sudah memiliki penilaian!";
    } else {
        $stmt = $pdo->prepare("DELETE FROM ujian_stations WHERE ujian_id = ?");
        $stmt->execute([$id]);
        
        $stmt = $pdo->prepare("DELETE FROM ujian WHERE id = ?");
        if ($stmt->execute([$id])) {
            $success = "Ujian berhasil dihapus!";
        } else {
            $error = "Gagal menghapus ujian!";
        }
    }
}

// Proses Kelola Stations
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['simpan_stations'])) {
    $ujian_id = intval($_POST['ujian_id']);
    $stations = $_POST['stations'] ?? [];
    
    $stmt = $pdo->prepare("DELETE FROM ujian_stations WHERE ujian_id = ?");
    $stmt->execute([$ujian_id]);
    
    $success_count = 0;
    foreach ($stations as $station_id => $data) {
        if (isset($data['include']) && $data['include'] == '1') {
            $urutan = intval($data['urutan'] ?? 1);
            $stmt = $pdo->prepare("INSERT INTO ujian_stations (ujian_id, station_id, urutan) VALUES (?, ?, ?)");
            if ($stmt->execute([$ujian_id, $station_id, $urutan])) {
                $success_count++;
            }
        }
    }
    
    $success = "Stations berhasil diupdate! (" . $success_count . " stations)";
}

// Ambil semester yang dipilih
$selected_semester = isset($_GET['semester']) ? intval($_GET['semester']) : 0;

// Ambil data ujian
if ($selected_semester > 0) {
    $stmt = $pdo->prepare("SELECT * FROM ujian WHERE semester = ? ORDER BY tanggal_ujian DESC, created_at DESC");
    $stmt->execute([$selected_semester]);
} else {
    $stmt = $pdo->query("SELECT * FROM ujian ORDER BY semester ASC, tanggal_ujian DESC, created_at DESC");
}
$ujian = $stmt->fetchAll();

// Ambil data stations untuk form kelola stations
$stmt = $pdo->query("SELECT * FROM stations ORDER BY nama_station");
$all_stations = $stmt->fetchAll();

// Data untuk form edit
$edit_data = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM ujian WHERE id = ?");
    $stmt->execute([$id]);
    $edit_data = $stmt->fetch();
}

// Data untuk kelola stations
$kelola_stations_data = null;
$selected_stations_map = [];
if (isset($_GET['kelola_stations'])) {
    $id = intval($_GET['kelola_stations']);
    $stmt = $pdo->prepare("SELECT * FROM ujian WHERE id = ?");
    $stmt->execute([$id]);
    $kelola_stations_data = $stmt->fetch();
    
    $stmt = $pdo->prepare("
        SELECT s.*, us.urutan 
        FROM stations s 
        INNER JOIN ujian_stations us ON s.id = us.station_id 
        WHERE us.ujian_id = ? 
        ORDER BY us.urutan
    ");
    $stmt->execute([$id]);
    $selected_stations = $stmt->fetchAll();
    
    foreach ($selected_stations as $station) {
        $selected_stations_map[$station['id']] = $station;
    }
}

// Proses Nonaktifkan Ujian (Massal)
if (isset($_POST['nonaktifkan_ujian']) || isset($_POST['action_type']) && $_POST['action_type'] == 'nonaktifkan') {
    $selected_semester = isset($_POST['semester_filter']) ? intval($_POST['semester_filter']) : 0;
    $confirm = isset($_POST['confirm_action']) ? true : false;
    
    if (!$confirm) {
        $error = "Anda harus mencentang konfirmasi untuk melanjutkan!";
    } else {
        try {
            if ($selected_semester > 0) {
                $stmt = $pdo->prepare("UPDATE ujian SET status = 'nonaktif' WHERE semester = ? AND status != 'selesai'");
                $stmt->execute([$selected_semester]);
                $affected = $stmt->rowCount();
                $success = "Berhasil menonaktifkan $affected ujian di Semester $selected_semester";
            } else {
                $stmt = $pdo->prepare("UPDATE ujian SET status = 'nonaktif' WHERE status != 'selesai'");
                $stmt->execute([]);
                $affected = $stmt->rowCount();
                $success = "Berhasil menonaktifkan $affected ujian";
            }
        } catch (PDOException $e) {
            $error = "Error mengubah status: " . $e->getMessage();
        }
    }
}

// Proses Aktifkan Ujian (Massal)
if (isset($_POST['aktifkan_ujian']) || isset($_POST['action_type']) && $_POST['action_type'] == 'aktifkan') {
    $selected_semester = isset($_POST['semester_filter']) ? intval($_POST['semester_filter']) : 0;
    $confirm = isset($_POST['confirm_action']) ? true : false;
    
    if (!$confirm) {
        $error = "Anda harus mencentang konfirmasi untuk melanjutkan!";
    } else {
        try {
            if ($selected_semester > 0) {
                $stmt = $pdo->prepare("UPDATE ujian SET status = 'aktif' WHERE semester = ?");
                $stmt->execute([$selected_semester]);
                $affected = $stmt->rowCount();
                $success = "Berhasil mengaktifkan $affected ujian di Semester $selected_semester";
            } else {
                $stmt = $pdo->prepare("UPDATE ujian SET status = 'aktif'");
                $stmt->execute([]);
                $affected = $stmt->rowCount();
                $success = "Berhasil mengaktifkan $affected ujian";
            }
        } catch (PDOException $e) {
            $error = "Error mengaktifkan ujian: " . $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 Ujian | 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;
        }

        .card-header .badge {
            padding: 0.3rem 1rem;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 600;
        }

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

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

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

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

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

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

        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.2rem;
        }

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

        .form-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        /* Semester Tabs */
        .semester-tabs {
            display: flex;
            gap: 0.8rem;
            flex-wrap: wrap;
            margin-bottom: 1.5rem;
        }

        .semester-tab {
            padding: 0.6rem 1.8rem;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.85rem;
            text-decoration: none;
            transition: all 0.2s;
            border: 2px solid #e2e8f0;
            color: #475569;
            background: white;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .semester-tab:hover {
            border-color: #667eea;
            color: #667eea;
        }

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

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

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

        .data-table thead tr {
            background: linear-gradient(135deg, #5c78f1, #1958e1);
            color: white;
        }

        .data-table th {
            padding: 0.9rem 0.8rem;
            text-align: center;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

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

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

        .data-table tbody tr:last-child td {
            border-bottom: none;
        }

        .semester-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 0.3rem 0.9rem;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .semester-1 { background: #d1fae5; color: #065f46; }
        .semester-3 { background: #fef3c7; color: #92400e; }
        .semester-5 { background: #dbeafe; color: #1e40af; }
        .semester-7 { background: #fee2e2; color: #991b1b; }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 0.3rem 0.9rem;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .status-aktif { background: #d1fae5; color: #065f46; }
        .status-nonaktif { background: #f1f5f9; color: #475569; }
        .status-selesai { background: #dbeafe; color: #1e40af; }

        .station-count {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 0.3rem 0.9rem;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .has-stations { background: #dbeafe; color: #1e40af; }
        .no-stations { background: #fef3c7; color: #92400e; }

        .table-actions {
            display: flex;
            gap: 0.4rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
        }

        .btn-action span { display: none; }

        .btn-edit { background: #fef3c7; color: #92400e; border: 1px solid #fde68a; }
        .btn-edit:hover { background: #f59e0b; color: white; }

        .btn-manage { background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd; }
        .btn-manage:hover { background: #3b82f6; color: white; }

        .btn-delete { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }
        .btn-delete:hover { background: #ef4444; color: white; }

        .table-footer {
            padding: 1rem;
            text-align: center;
            font-size: 0.85rem;
            color: #64748b;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
        }

        .table-footer strong { color: #0f172a; }

        /* Manage Stations Table */
        .manage-stations-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }

        .manage-stations-table thead {
            background: #f8fafc;
        }

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

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

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

        .manage-stations-table input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #667eea;
            cursor: pointer;
        }

        .manage-stations-table input[type="number"] {
            width: 70px;
            padding: 0.4rem 0.6rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.85rem;
            text-align: center;
        }

        .manage-stations-table input[type="number"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .manage-stations-table input[type="number"]:disabled {
            background: #f1f5f9;
            cursor: not-allowed;
        }

        @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; }
            .form-row { grid-template-columns: 1fr; }
            .card-header { flex-direction: column; gap: 0.5rem; align-items: flex-start; }
            .btn-action span { display: inline; }
            .data-table { font-size: 0.75rem; }
            .data-table th, .data-table td { padding: 0.5rem 0.4rem; }
        }

        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }

        .waktu-slot {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 0.8rem;
            color: #475569;
        }

        .row-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 28px;
            height: 28px;
            background: #f1f5f9;
            border-radius: 50%;
            font-weight: 700;
            font-size: 0.8rem;
            color: #475569;
        }

        .ujian-name {
            font-weight: 600;
            color: #0f172a;
        }

        /* Mass Action Styles */
.mass-actions {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
    align-items: center;
    padding: 1.2rem 1.5rem;
    background: #f8fafc;
    border-radius: 16px;
    border: 1px solid #e2e8f0;
    margin-bottom: 1.5rem;
}

.mass-actions .form-group {
    margin-bottom: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.mass-actions select {
    min-width: 160px;
    padding: 0.5rem 0.8rem;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 0.85rem;
    background: white;
}

.mass-actions select:focus {
    outline: none;
    border-color: #667eea;
}

.mass-actions .btn {
    padding: 0.5rem 1.2rem;
    font-size: 0.85rem;
}

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

.mass-actions .btn-warning:hover {
    background: #d97706;
}

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

.mass-actions .btn-success:hover {
    background: #059669;
}

.confirm-checkbox {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.85rem;
    color: #475569;
    cursor: pointer;
}

.confirm-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: #ef4444;
    cursor: pointer;
}
    </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 active"><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"><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-calendar-alt" style="margin-right: 10px; color: #667eea;"></i>Kelola Ujian OSCE</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): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?></div>
        <?php endif; ?>

        <!-- Form Tambah/Edit Ujian -->
        <div class="card" id="formUjian" style="display: <?php echo $edit_data ? 'block' : 'none'; ?>;">
            <div class="card-header">
                <h5><i class="fas fa-<?php echo $edit_data ? 'pen' : 'plus'; ?>-square"></i> <?php echo $edit_data ? 'Edit Ujian' : 'Tambah Ujian Baru'; ?></h5>
                <?php if ($edit_data): ?>
                    <span class="badge" style="background: #f59e0b; color: white;">Mode Edit</span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="POST">
                    <?php if ($edit_data): ?>
                        <input type="hidden" name="id" value="<?php echo $edit_data['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-tag"></i> Nama Ujian *</label>
                            <input type="text" class="form-control" name="nama_ujian" 
                                   value="<?php echo getSafeValue($edit_data ?? [], 'nama_ujian', $_POST['nama_ujian'] ?? ''); ?>" 
                                   required placeholder="Contoh: 1A. Anatomi">
                        </div>
                        
                        <div class="form-group">
                            <label><i class="fas fa-graduation-cap"></i> Semester *</label>
                            <select class="form-control" name="semester" required>
                                <option value="0">-- Pilih Semester --</option>
                                <?php foreach ([1, 3, 5, 7] as $sem): ?>
                                    <option value="<?php echo $sem; ?>" <?php echo (getSafeValue($edit_data ?? [], 'semester', $_POST['semester'] ?? '') == $sem) ? 'selected' : ''; ?>>
                                        Semester <?php echo $sem; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-calendar-day"></i> Tanggal Ujian *</label>
                            <input type="date" class="form-control" name="tanggal_ujian" 
                                   value="<?php echo getSafeValue($edit_data ?? [], 'tanggal_ujian', $_POST['tanggal_ujian'] ?? ''); ?>" 
                                   required>
                        </div>
                        
                        <div class="form-group">
                            <label><i class="fas fa-info-circle"></i> Status *</label>
                            <select class="form-control" name="status" required>
                                <option value="aktif" <?php echo (getSafeValue($edit_data ?? [], 'status', $_POST['status'] ?? '') == 'aktif') ? 'selected' : ''; ?>>Aktif</option>
                                <option value="nonaktif" <?php echo (getSafeValue($edit_data ?? [], 'status', $_POST['status'] ?? '') == 'nonaktif') ? 'selected' : ''; ?>>Nonaktif</option>
                                <option value="selesai" <?php echo (getSafeValue($edit_data ?? [], 'status', $_POST['status'] ?? '') == 'selesai') ? 'selected' : ''; ?>>Selesai</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-clock"></i> Waktu Mulai</label>
                            <input type="time" class="form-control" name="waktu_mulai" 
                                   value="<?php echo getSafeValue($edit_data ?? [], 'waktu_mulai', $_POST['waktu_mulai'] ?? '08:00'); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label><i class="fas fa-clock"></i> Waktu Selesai</label>
                            <input type="time" class="form-control" name="waktu_selesai" 
                                   value="<?php echo getSafeValue($edit_data ?? [], 'waktu_selesai', $_POST['waktu_selesai'] ?? '16:00'); ?>">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label><i class="fas fa-align-left"></i> Deskripsi Ujian</label>
                        <textarea class="form-control" name="deskripsi" rows="3" 
                                  placeholder="Masukkan deskripsi ujian (opsional)"><?php echo getSafeValue($edit_data ?? [], 'deskripsi', $_POST['deskripsi'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" name="<?php echo $edit_data ? 'edit_ujian' : 'tambah_ujian'; ?>" class="btn btn-primary">
                            <i class="fas fa-save"></i> <?php echo $edit_data ? 'Update Ujian' : 'Simpan Ujian'; ?>
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="resetForm()">
                            <i class="fas fa-times"></i> Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Form Kelola Stations -->
        <?php if ($kelola_stations_data): ?>
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-cogs"></i> Kelola Stations - <?php echo htmlspecialchars($kelola_stations_data['nama_ujian']); ?></h5>
                <span class="badge" style="background: #3b82f6; color: white;">Manage Stations</span>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="ujian_id" value="<?php echo $kelola_stations_data['id']; ?>">
                    
                    <?php if (empty($all_stations)): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            Belum ada stations. Silakan buat stations terlebih dahulu.
                        </div>
                    <?php else: ?>
                        <div class="table-container">
                            <table class="manage-stations-table">
                                <thead>
                                    <tr>
                                        <th width="50">Pilih</th>
                                        <th>Nama Station</th>
                                        <th width="100">Urutan</th>
                                        <th>Deskripsi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($all_stations as $station): ?>
                                        <?php 
                                        $is_selected = isset($selected_stations_map[$station['id']]);
                                        $current_urutan = $is_selected ? $selected_stations_map[$station['id']]['urutan'] : '';
                                        ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="stations[<?php echo $station['id']; ?>][include]" 
                                                       value="1" <?php echo $is_selected ? 'checked' : ''; ?> 
                                                       onchange="toggleUrutan(this, <?php echo $station['id']; ?>)">
                                            </td>
                                            <td><strong><?php echo htmlspecialchars($station['nama_station']); ?></strong></td>
                                            <td>
                                                <input type="number" name="stations[<?php echo $station['id']; ?>][urutan]" 
                                                       value="<?php echo $current_urutan; ?>" 
                                                       min="1" max="20" 
                                                       id="urutan_<?php echo $station['id']; ?>"
                                                       <?php echo !$is_selected ? 'disabled' : ''; ?>>
                                            </td>
                                            <td><small><?php echo truncateText(htmlspecialchars($station['deskripsi'] ?? ''), 100); ?></small></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" name="simpan_stations" class="btn btn-primary">
                                <i class="fas fa-save"></i> Simpan Stations
                            </button>
                            <a href="ujian.php<?php echo $selected_semester > 0 ? '?semester=' . $selected_semester : ''; ?>" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <!-- Semester Tabs dengan jumlah -->
<div class="semester-tabs">
    <a href="?semester=0" class="semester-tab <?php echo $selected_semester == 0 ? 'active' : ''; ?>">
        <i class="fas fa-th"></i> Semua Ujian
        <span class="badge" style="background: rgba(255,255,255,0.2); color: white; padding: 0.1rem 0.6rem; border-radius: 30px; font-size: 0.65rem;">
            <?php 
            $stmt = $pdo->query("SELECT COUNT(*) FROM ujian");
            echo $stmt->fetchColumn(); 
            ?>
        </span>
    </a>
    <?php foreach ([1, 3, 5, 7] as $sem): 
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM ujian WHERE semester = ?");
        $stmt->execute([$sem]);
        $count = $stmt->fetchColumn();
    ?>
        <a href="?semester=<?php echo $sem; ?>" class="semester-tab <?php echo $selected_semester == $sem ? 'active' : ''; ?>">
            <i class="fas fa-<?php echo $sem; ?>-circle"></i> Semester <?php echo $sem; ?>
            <span class="badge" style="background: rgba(255,255,255,0.2); color: white; padding: 0.1rem 0.6rem; border-radius: 30px; font-size: 0.65rem;">
                <?php echo $count; ?>
            </span>
        </a>
    <?php endforeach; ?>
</div>

        <!-- Mass Action - Nonaktifkan/Aktifkan Ujian -->
<div class="mass-actions">
    <span style="font-weight: 600; color: #0f172a; display: flex; align-items: center; gap: 8px;">
        <i class="fas fa-bolt" style="color: #f59e0b;"></i> Aksi Massal:
    </span>
    
    <form method="POST" style="display: flex; gap: 1rem; flex-wrap: wrap; align-items: center;" id="massActionForm">
        <input type="hidden" name="semester_filter" value="<?php echo $selected_semester; ?>">
        
        <div class="form-group">
            <select name="action_type" id="actionType" required>
                <option value="nonaktifkan">Nonaktifkan</option>
                <option value="aktifkan">Aktifkan</option>
            </select>
        </div>
        
        <div class="form-group">
            <label class="confirm-checkbox">
                <input type="checkbox" name="confirm_action" value="1" id="confirmAction" required>
                Saya yakin
            </label>
        </div>
        
        <button type="button" class="btn btn-warning" onclick="processMassAction()">
            <i class="fas fa-power-off"></i> 
            <?php echo $selected_semester > 0 ? 'Ubah Status Semester ' . $selected_semester : 'Ubah Status Semua'; ?>
        </button>
    </form>
</div>

        <!-- Daftar Ujian -->
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-list-check"></i> Daftar Ujian</h5>
                <button type="button" class="btn btn-primary btn-sm" onclick="toggleForm()">
                    <i class="fas fa-plus"></i> Tambah Ujian
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($ujian)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Belum ada data ujian. Klik "Tambah Ujian" untuk membuat ujian baru.
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Nama Ujian</th>
                                    <th>Semester</th>
                                    <th>Tanggal</th>
                                    <th>Waktu</th>
                                    <th>Status</th>
                                    <th>Stations</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($ujian as $index => $u): ?>
                                    <?php
                                    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM ujian_stations WHERE ujian_id = ?");
                                    $stmt->execute([$u['id']]);
                                    $station_count = $stmt->fetch()['total'];
                                    
                                    $waktu_mulai = getSafeValue($u, 'waktu_mulai') ? substr($u['waktu_mulai'], 0, 5) : '';
                                    $waktu_selesai = getSafeValue($u, 'waktu_selesai') ? substr($u['waktu_selesai'], 0, 5) : '';
                                    $semester = $u['semester'] ?? 0;
                                    
                                    $semester_class = '';
                                    $semester_text = '';
                                    if ($semester == 1) { $semester_class = 'semester-1'; $semester_text = 'Semester 1'; }
                                    elseif ($semester == 3) { $semester_class = 'semester-3'; $semester_text = 'Semester 3'; }
                                    elseif ($semester == 5) { $semester_class = 'semester-5'; $semester_text = 'Semester 5'; }
                                    elseif ($semester == 7) { $semester_class = 'semester-7'; $semester_text = 'Semester 7'; }
                                    else { $semester_class = 'semester-1'; $semester_text = '-'; }
                                    ?>
                                    <tr>
                                        <td><span class="row-number"><?php echo $index + 1; ?></span></td>
                                        <td>
                                            <div class="ujian-name"><?php echo htmlspecialchars($u['nama_ujian']); ?></div>
                                            <?php if (!empty($u['deskripsi'])): ?>
                                                <small class="text-muted"><?php echo truncateText(htmlspecialchars($u['deskripsi']), 60); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="semester-badge <?php echo $semester_class; ?>">
                                                <i class="fas fa-<?php echo $semester; ?>-circle"></i> <?php echo $semester_text; ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('d/m/Y', strtotime($u['tanggal_ujian'])); ?></td>
                                        <td>
                                            <?php if ($waktu_mulai && $waktu_selesai): ?>
                                                <span class="waktu-slot">
                                                    <i class="fas fa-clock"></i> <?php echo $waktu_mulai; ?> - <?php echo $waktu_selesai; ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo $u['status']; ?>">
                                                <i class="fas fa-circle" style="font-size: 6px;"></i>
                                                <?php echo ucfirst($u['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="station-count <?php echo $station_count > 0 ? 'has-stations' : 'no-stations'; ?>">
                                                <i class="fas fa-layer-group"></i>
                                                <?php echo $station_count; ?> station<?php echo $station_count != 1 ? 's' : ''; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="table-actions">
                                                <a href="?edit=<?php echo $u['id']; ?><?php echo $selected_semester > 0 ? '&semester=' . $selected_semester : ''; ?>" 
                                                   class="btn-action btn-edit" title="Edit Ujian">
                                                    <i class="fas fa-pen"></i>
                                                    <span>Edit</span>
                                                </a>
                                                <a href="?kelola_stations=<?php echo $u['id']; ?><?php echo $selected_semester > 0 ? '&semester=' . $selected_semester : ''; ?>" 
                                                   class="btn-action btn-manage" title="Kelola Stations">
                                                    <i class="fas fa-gear"></i>
                                                    <span>Stations</span>
                                                </a>
                                                <a href="?hapus=<?php echo $u['id']; ?><?php echo $selected_semester > 0 ? '&semester=' . $selected_semester : ''; ?>" 
                                                   class="btn-action btn-delete" title="Hapus Ujian" 
                                                   onclick="return confirm('Hapus ujian <?php echo htmlspecialchars($u['nama_ujian']); ?>?')">
                                                    <i class="fas fa-trash"></i>
                                                    <span>Hapus</span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="table-footer">
                        <i class="fas fa-database"></i>
                        Total <strong><?php echo count($ujian); ?></strong> ujian
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<script>
    function toggleForm() {
        const form = document.getElementById('formUjian');
        form.style.display = form.style.display === 'none' ? 'block' : 'none';
        if (form.style.display === 'none') {
            resetForm();
        }
    }

    function resetForm() {
        window.location.href = 'ujian.php<?php echo $selected_semester > 0 ? '?semester=' . $selected_semester : ''; ?>';
    }

    function toggleUrutan(checkbox, stationId) {
        const urutanInput = document.getElementById('urutan_' + stationId);
        urutanInput.disabled = !checkbox.checked;
        if (checkbox.checked && !urutanInput.value) {
            urutanInput.value = 1;
        }
    }

    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            alert.style.display = 'none';
        });
    }, 5000);

    document.addEventListener('DOMContentLoaded', function() {
        const today = new Date().toISOString().split('T')[0];
        const tanggalInput = document.querySelector('input[name="tanggal_ujian"]');
        if (tanggalInput && !tanggalInput.value) {
            tanggalInput.min = today;
        }
    });
</script>

<script>
    function confirmMassAction(form) {
    // Cari tahu aksi apa yang dilakukan
    const submitBtn = form.querySelector('button[type="submit"]');
    const actionText = submitBtn.textContent.trim();
    const semester = <?php echo $selected_semester > 0 ? $selected_semester : 0; ?>;
    const semesterText = semester > 0 ? ' Semester ' + semester : ' SEMUA UJIAN';
    
    // Cek checkbox konfirmasi
    const confirmCheckbox = form.querySelector('input[name="confirm_action"]');
    if (!confirmCheckbox || !confirmCheckbox.checked) {
        alert('⚠️ Anda harus mencentang "Saya yakin" terlebih dahulu!');
        return false;
    }
    
    // Tentukan jenis aksi
    let isActive = false;
    let actionDisplay = '';
    
    if (actionText.includes('Aktifkan')) {
        isActive = true;
        actionDisplay = 'MENGAKTIFKAN';
    } else if (actionText.includes('Nonaktifkan') || actionText.includes('Ubah Status')) {
        isActive = false;
        actionDisplay = 'MENONAKTIFKAN';
    } else {
        // Fallback: cek nama tombol
        if (submitBtn.name === 'aktifkan_ujian') {
            isActive = true;
            actionDisplay = 'MENGAKTIFKAN';
        } else {
            actionDisplay = 'MENGUBAH STATUS';
        }
    }
    
    // Tampilkan konfirmasi
    const confirmMsg = confirm(
        `⚠️ PERINGATAN!\n\n` +
        `Anda akan ${actionDisplay}${semesterText}.\n\n` +
        `⚠️ Ujian dengan status "Selesai" TIDAK akan diubah.\n\n` +
        `Lanjutkan?`
    );
    
    if (!confirmMsg) {
        return false;
    }
    
    // Jika user mengklik OK, form akan submit
    return true;
}
</script>

<script>
    function processMassAction() {
    const form = document.getElementById('massActionForm');
    const actionType = document.getElementById('actionType').value;
    const confirmCheckbox = document.getElementById('confirmAction');
    const semester = <?php echo $selected_semester > 0 ? $selected_semester : 0; ?>;
    const semesterText = semester > 0 ? ' Semester ' + semester : ' SEMUA UJIAN';
    
    // Validasi checkbox
    if (!confirmCheckbox.checked) {
        alert('⚠️ Anda harus mencentang "Saya yakin" terlebih dahulu!');
        confirmCheckbox.focus();
        return;
    }
    
    // Tentukan aksi
    let actionDisplay = '';
    let submitName = '';
    let btnClass = '';
    let iconClass = '';
    
    if (actionType === 'aktifkan') {
        actionDisplay = 'MENGAKTIFKAN';
        submitName = 'aktifkan_ujian';
        btnClass = 'btn-success';
        iconClass = 'fa-play';
    } else {
        actionDisplay = 'MENONAKTIFKAN';
        submitName = 'nonaktifkan_ujian';
        btnClass = 'btn-warning';
        iconClass = 'fa-power-off';
    }
    
    // Konfirmasi
    if (!confirm(
        `⚠️ PERINGATAN!\n\n` +
        `Anda akan ${actionDisplay}${semesterText}.\n\n` +
        `⚠️ Ujian dengan status "Selesai" TIDAK akan diubah.\n\n` +
        `Lanjutkan?`
    )) {
        return;
    }
    
    // Buat hidden input untuk submit name
    const hiddenInput = document.createElement('input');
    hiddenInput.type = 'hidden';
    hiddenInput.name = submitName;
    hiddenInput.value = '1';
    form.appendChild(hiddenInput);
    
    // Submit form
    form.submit();
}
</script>
</body>
</html>