<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Cek apakah user sudah login dan memiliki akses admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin_soal') {
    header('Location: ../login.php');
    exit;
}

// Daftar department kedokteran gigi
$departments = [
    'bedah_mulut' => 'Bedah Mulut',
    'konservasi' => 'Konservasi Gigi',
    'periodonsia' => 'Periodonsia',
    'orthodonti' => 'Orthodonti',
    'prostodonsia' => 'Prostodonsia',
    'pedodonsia' => 'Pedodonsia',
    'radiologi' => 'Radiologi Kedokteran Gigi',
    'ilmu_kesehatan_gigi_masyarakat' => 'Ilmu Kesehatan Gigi Masyarakat',
    'ilmu_material_kedokteran_gigi' => 'Ilmu Material Kedokteran Gigi',
    'odontologi_forensik' => 'Odontologi Forensik'
];

// Ambil data soal praktik dari database untuk dropdown
$soal_praktik = [];
try {
    $stmt = $pdo->query("SELECT id, nomor_registrasi, department, skenario_klinik, digunakan_di_ujian 
                         FROM bank_soal_praktik 
                         ORDER BY created_at DESC");
    $soal_praktik = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_soal = 'Gagal mengambil data soal praktik';
}

// Proses penyimpanan data aspek penilaian
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $department = $_POST['department'] ?? '';
    $nomor_registrasi = $_POST['nomor_registrasi'] ?? '';
    $jumlah_aspek = isset($_POST['jumlah_aspek']) ? intval($_POST['jumlah_aspek']) : 0;
    $aspek_data = $_POST['aspek'] ?? [];
    
    $errors = [];
    
    if (empty($department)) {
        $errors[] = 'Department harus dipilih';
    }
    
    if (empty($nomor_registrasi)) {
        $errors[] = 'Nomor registrasi harus dipilih';
    }
    
    // Ubah batas maksimal dari 15 menjadi 40
    if ($jumlah_aspek < 1 || $jumlah_aspek > 40) {
        $errors[] = 'Jumlah aspek harus antara 1-40';
    }
    
    if (count($aspek_data) != $jumlah_aspek) {
        $errors[] = 'Jumlah data aspek tidak sesuai';
    }
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM aspek_penilaian_praktik WHERE nomor_registrasi = ?");
        $stmt->execute([$nomor_registrasi]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result['total'] > 0) {
            $errors[] = 'Nomor registrasi ini sudah memiliki aspek penilaian. Silakan pilih nomor registrasi lain.';
        }
    } catch (PDOException $e) {
        $errors[] = 'Gagal memeriksa nomor registrasi';
    }
    
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            foreach ($aspek_data as $index => $aspek) {
                $nomor_urut = $index + 1;
                $aspek_yang_dinilai = trim($aspek['aspek_yang_dinilai']);
                $keterangan_skor = trim($aspek['keterangan_skor']);
                $skor_dinilai = implode(',', $aspek['skor_dinilai'] ?? []);
                
                if (!empty($aspek_yang_dinilai)) {
                    $stmt = $pdo->prepare("INSERT INTO aspek_penilaian_praktik 
                                          (nomor_urut, aspek_yang_dinilai, skor_dinilai, keterangan_skor, 
                                           department, nomor_registrasi, created_at) 
                                          VALUES (?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([
                        $nomor_urut, 
                        $aspek_yang_dinilai, 
                        $skor_dinilai, 
                        $keterangan_skor,
                        $department,
                        $nomor_registrasi
                    ]);
                }
            }
            
            $stmt = $pdo->prepare("UPDATE bank_soal_praktik SET digunakan_di_ujian = 1 WHERE nomor_registrasi = ?");
            $stmt->execute([$nomor_registrasi]);
            
            $pdo->commit();
            $success_message = 'Data aspek penilaian berhasil disimpan!';
            
            unset($_POST);
            
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = 'Gagal menyimpan data: ' . $e->getMessage();
        }
    }
}

// Ambil data aspek yang sudah ada
$aspek_terdaftar = [];
try {
    $stmt = $pdo->query("SELECT ap.*, bs.skenario_klinik 
                         FROM aspek_penilaian_praktik ap 
                         LEFT JOIN bank_soal_praktik bs ON ap.nomor_registrasi = bs.nomor_registrasi 
                         ORDER BY ap.department, ap.nomor_urut");
    $aspek_terdaftar = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Table mungkin belum ada
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aspek Penilaian Praktik - SOCA OSCE System</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tiny.cloud/1/p93sjg5qtxeh4t0y8uynvaig0oo66ac2ahh35s86k31iu0yv/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
    <style>
        /* ===== RESET & BASE ===== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #d4d8dc;
            display: flex;
            min-height: 100vh;
        }

        /* ===== SIDEBAR ===== */
        .sidebar {
            width: 260px;
            background: linear-gradient(180deg, #1a2332 0%, #0f1724 100%);
            color: #fff;
            padding: 0;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 100;
            transition: all 0.3s ease;
            box-shadow: 4px 0 20px rgba(0,0,0,0.1);
        }

        .sidebar::-webkit-scrollbar {
            width: 4px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
        }

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

        .sidebar-header h2 {
            font-size: 20px;
            font-weight: 700;
            letter-spacing: 1px;
            background: linear-gradient(135deg, #60a5fa, #a78bfa);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .sidebar-header p {
            font-size: 12px;
            color: rgba(255,255,255,0.5);
            margin-top: 4px;
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        .sidebar-menu {
            list-style: none;
            padding: 15px 0;
        }

        .sidebar-menu li {
            margin: 2px 12px;
        }

        .sidebar-menu li a {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 12px 16px;
            color: rgba(255,255,255,0.6);
            text-decoration: none;
            border-radius: 12px;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .sidebar-menu li a i {
            width: 20px;
            font-size: 16px;
            text-align: center;
        }

        .sidebar-menu li a:hover {
            background: rgba(255,255,255,0.08);
            color: #fff;
            transform: translateX(4px);
        }

        .sidebar-menu li a.active {
            background: linear-gradient(135deg, rgba(96,165,250,0.2), rgba(167,139,250,0.2));
            color: #60a5fa;
            box-shadow: inset 3px 0 0 #60a5fa;
        }

        .sidebar-menu .menu-divider {
            height: 1px;
            background: rgba(255,255,255,0.06);
            margin: 12px 20px;
        }

        .sidebar-menu .menu-label {
            padding: 10px 20px 6px;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            color: rgba(255,255,255,0.25);
            font-weight: 600;
        }

        /* ===== MAIN CONTENT ===== */
        .main-content {
            margin-left: 260px;
            flex: 1;
            padding: 30px 35px 40px;
            min-height: 100vh;
        }

        /* ===== HEADER ===== */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header-left h1 {
            font-size: 28px;
            font-weight: 700;
            color: #1a2332;
            letter-spacing: -0.5px;
        }

        .header-left .subtitle {
            font-size: 14px;
            color: #6b7a8f;
            margin-top: 4px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header-right .user-badge {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #fff;
            padding: 8px 16px 8px 12px;
            border-radius: 50px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
        }

        .header-right .user-badge .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: linear-gradient(135deg, #60a5fa, #a78bfa);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-weight: 600;
            font-size: 16px;
        }

        .header-right .user-badge .user-name {
            font-weight: 600;
            font-size: 14px;
            color: #1a2332;
        }

        .header-right .user-badge .user-role {
            font-size: 12px;
            color: #6b7a8f;
        }

        .btn-logout {
            background: #fee2e2;
            color: #dc2626;
            border: none;
            padding: 8px 16px;
            border-radius: 50px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-logout:hover {
            background: #fecaca;
            transform: scale(1.02);
        }

        /* ===== ALERT ===== */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }

        .alert i {
            font-size: 18px;
        }

        .alert ul {
            margin: 0;
            padding-left: 20px;
        }

        /* ===== CARDS ===== */
        .card {
            background: #fff;
            border-radius: 16px;
            padding: 28px 32px;
            margin-bottom: 30px;
            box-shadow: 0 2px 12px 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;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .card-header h2 {
            font-size: 18px;
            font-weight: 700;
            color: #1a2332;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header h2 i {
            color: #60a5fa;
        }

        .card-header .badge-count {
            padding: 4px 14px;
            background: #f1f5f9;
            border-radius: 50px;
            font-size: 13px;
            color: #475569;
        }

        /* ===== FORM ===== */
        .form-section {
            margin-bottom: 28px;
            padding-bottom: 24px;
            border-bottom: 1px solid #f1f5f9;
        }

        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .form-section h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a2332;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-section h3 i {
            color: #60a5fa;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            font-size: 14px;
            color: #1a2332;
            margin-bottom: 6px;
        }

        .form-group label .required {
            color: #dc2626;
        }

        .form-control {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: #f8fafc;
            color: #1a2332;
            font-family: inherit;
        }

        .form-control:focus {
            outline: none;
            border-color: #60a5fa;
            box-shadow: 0 0 0 4px rgba(96,165,250,0.15);
            background: #fff;
        }

        select.form-control {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7a8f' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 40px;
        }

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

        .form-text {
            display: block;
            font-size: 12px;
            color: #6b7a8f;
            margin-top: 4px;
        }

        .input-group {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }

        .input-group .form-control {
            flex: 1;
            min-width: 100px;
        }

        .form-info {
            background: #eff6ff;
            padding: 12px 16px;
            border-radius: 8px;
            border-left: 4px solid #60a5fa;
            font-size: 14px;
            color: #1a2332;
            margin-bottom: 16px;
        }

        /* ===== BUTTONS ===== */
        .btn {
            padding: 10px 24px;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2563eb, #7c3aed);
            color: #fff;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(37,99,235,0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #059669, #10b981);
            color: #fff;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(5,150,105,0.3);
        }

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

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

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

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

        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
            flex-wrap: wrap;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }

        /* ===== SOAL PREVIEW ===== */
        .soal-preview {
            background: #f8fafc;
            border-radius: 10px;
            padding: 16px 20px;
            margin-top: 12px;
            border: 1px solid #e2e8f0;
        }

        .soal-preview h4 {
            font-size: 14px;
            font-weight: 600;
            color: #1a2332;
            margin-bottom: 10px;
        }

        .preview-content {
            font-size: 14px;
            color: #475569;
            line-height: 1.6;
        }

        .preview-content strong {
            color: #1a2332;
        }

        .preview-text {
            margin-top: 6px;
            padding: 10px 12px;
            background: #fff;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
        }

        /* ===== ASPEK FORM GROUP ===== */
        .aspek-form-group {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px 24px;
            margin-bottom: 20px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .aspek-form-group:hover {
            border-color: #60a5fa;
            box-shadow: 0 2px 12px rgba(96,165,250,0.08);
        }

        .aspek-form-group .aspek-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            flex-wrap: wrap;
            gap: 8px;
        }

        .aspek-form-group .aspek-header h3 {
            font-size: 15px;
            font-weight: 600;
            color: #1a2332;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .aspek-form-group .aspek-header h3 i {
            color: #60a5fa;
        }

        .aspek-divider {
            border: none;
            height: 1px;
            background: #e2e8f0;
            margin: 16px 0 0 0;
        }

        /* ===== SKOR OPTIONS ===== */
        .skor-options {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            padding: 8px 0;
        }

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

        .checkbox-label input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #60a5fa;
        }

        /* ===== ASPEK LIST ===== */
        .department-filter {
            display: flex;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .department-filter label {
            font-weight: 600;
            font-size: 14px;
            color: #475569;
        }

        .department-filter .form-control {
            max-width: 300px;
        }

        .aspek-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .department-header {
            background: #f8fafc;
            padding: 12px 16px;
            border-radius: 8px;
            border-left: 4px solid #60a5fa;
            margin-top: 8px;
        }

        .department-header h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a2332;
        }

        .department-header h3 small {
            font-weight: 400;
            color: #6b7a8f;
            font-size: 13px;
            margin-left: 8px;
        }

        .aspek-item {
            background: #f8fafc;
            border-radius: 10px;
            padding: 16px 20px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
            margin-left: 20px;
        }

        .aspek-item:hover {
            border-color: #60a5fa;
            box-shadow: 0 2px 8px rgba(96,165,250,0.08);
        }

        .aspek-item .aspek-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            flex-wrap: wrap;
            gap: 8px;
        }

        .aspek-item .aspek-header h4 {
            font-size: 14px;
            font-weight: 600;
            color: #1a2332;
        }

        .aspek-item .aspek-content {
            font-size: 14px;
            color: #475569;
            line-height: 1.6;
        }

        .aspek-item .aspek-content strong {
            color: #1a2332;
            display: block;
            margin-top: 8px;
        }

        .aspek-item .aspek-content strong:first-child {
            margin-top: 0;
        }

        .content-preview {
            padding: 8px 12px;
            background: #fff;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
            margin: 4px 0 10px 0;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 50px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-info {
            background: #dbeafe;
            color: #2563eb;
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 992px) {
            .sidebar {
                width: 220px;
            }
            .main-content {
                margin-left: 220px;
                padding: 20px;
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 0;
                transform: translateX(-100%);
            }
            .sidebar.open {
                width: 280px;
                transform: translateX(0);
            }
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            .header {
                flex-direction: column;
                align-items: flex-start;
            }
            .card {
                padding: 16px;
            }
            .form-actions {
                flex-direction: column;
            }
            .form-actions .btn {
                width: 100%;
                justify-content: center;
            }
            .skor-options {
                gap: 12px;
            }
            .aspek-item {
                margin-left: 0;
            }
            .department-filter .form-control {
                max-width: 100%;
            }
        }

        @media (max-width: 480px) {
            .header-left h1 {
                font-size: 22px;
            }
            .input-group {
                flex-direction: column;
            }
            .input-group .form-control {
                width: 100%;
            }
            .input-group .btn {
                width: 100%;
                justify-content: center;
            }
        }

        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            color: #1a2332;
            cursor: pointer;
            padding: 8px;
            margin-bottom: 10px;
        }

        @media (max-width: 768px) {
            .hamburger {
                display: block;
            }
        }

        .sidebar-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.4);
            z-index: 99;
        }

        .sidebar-overlay.active {
            display: block;
        }

        .scroll-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #2563eb;
            color: #fff;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: none;
            cursor: pointer;
            font-size: 18px;
            box-shadow: 0 4px 16px rgba(37,99,235,0.3);
            transition: all 0.3s ease;
            opacity: 0;
            visibility: hidden;
            z-index: 50;
        }

        .scroll-top.visible {
            opacity: 1;
            visibility: visible;
        }

        .scroll-top:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 24px rgba(37,99,235,0.4);
        }

        /* ===== TINYMCE OVERRIDE ===== */
        .tox-tinymce {
            border-radius: 10px !important;
            border: 2px solid #e2e8f0 !important;
        }

        .tox-tinymce:focus-within {
            border-color: #60a5fa !important;
            box-shadow: 0 0 0 4px rgba(96,165,250,0.15) !important;
        }

        /* ===== MAX ASPEK INFO ===== */
        .max-aspek-info {
            display: inline-block;
            background: #fef3c7;
            color: #92400e;
            padding: 2px 10px;
            border-radius: 50px;
            font-size: 12px;
            font-weight: 500;
            margin-left: 8px;
        }
    </style>
</head>
<body>
    <!-- Overlay untuk mobile -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h2>SOCA/OSCE</h2>
            <p>Admin Panel</p>
        </div>
        <ul class="sidebar-menu">
            <li class="menu-label">Main Menu</li>
            <li><a href="dashboard.php"><i class="fas fa-th-large"></i> Dashboard</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Teori S1</li>
            <li><a href="bank_soal_teori_s1.php"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_teori_s1.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Teori</li>
            <li><a href="bank_soal_teori.php"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_teori.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Soal Praktik</li>
            <li><a href="bank_soal_praktik.php"><i class="fas fa-plus-circle"></i> Tambah Soal</a></li>
            <li><a href="list_soal_praktik.php"><i class="fas fa-list"></i> Daftar Soal</a></li>
            
            <li class="menu-divider"></li>
            <li class="menu-label">Lainnya</li>
            <li><a href="aspek_penilaian.php" class="active"><i class="fas fa-clipboard-check"></i> Aspek Penilaian</a></li>
            <li><a href="preview_aspek_penilaian.php"><i class="fas fa-eye"></i> Preview Aspek</a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> Kelola Users</a></li>
            <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <button class="hamburger" id="hamburgerBtn">
                    <i class="fas fa-bars"></i>
                </button>
                <h1>Aspek Penilaian Praktik</h1>
                <div class="subtitle">Kelola aspek penilaian untuk ujian praktik OSCE</div>
            </div>
            <div class="header-right">
                <div class="user-badge">
                    <div class="avatar">
                        <?php echo strtoupper(substr($_SESSION['user_name'] ?? 'A', 0, 1)); ?>
                    </div>
                    <div>
                        <div class="user-name"><?php echo $_SESSION['user_name'] ?? 'Admin'; ?></div>
                        <div class="user-role">Admin Soal</div>
                    </div>
                </div>
                <a href="../logout.php" class="btn-logout">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>

        <!-- Alert -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <ul>
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

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

        <!-- Form Card -->
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-cog"></i> Konfigurasi Aspek Penilaian</h2>
            </div>

            <form id="aspekForm" method="POST">
                <!-- Department Selection -->
                <div class="form-section">
                    <h3><i class="fas fa-building"></i> Pilih Department</h3>
                    <div class="form-group">
                        <label for="department">Department <span class="required">*</span></label>
                        <select id="department" name="department" class="form-control" required>
                            <option value="">-- Pilih Department --</option>
                            <?php foreach ($departments as $key => $value): ?>
                                <option value="<?php echo $key; ?>" 
                                    <?php echo (isset($_POST['department']) && $_POST['department'] == $key) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($value); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Nomor Registrasi Selection -->
                <div class="form-section">
                    <h3><i class="fas fa-file-medical"></i> Pilih Soal Praktik</h3>
                    <div class="form-group">
                        <label for="nomor_registrasi">Nomor Registrasi Soal <span class="required">*</span></label>
                        <select id="nomor_registrasi" name="nomor_registrasi" class="form-control" required>
                            <option value="">-- Pilih Nomor Registrasi --</option>
                            <?php foreach ($soal_praktik as $soal): ?>
                                <?php 
                                $status_text = $soal['digunakan_di_ujian'] ? ' (Sudah Digunakan)' : ' (Tersedia)';
                                ?>
                                <option value="<?php echo $soal['nomor_registrasi']; ?>" 
                                        data-department="<?php echo $soal['department']; ?>"
                                        data-status="<?php echo $soal['digunakan_di_ujian']; ?>"
                                    <?php echo (isset($_POST['nomor_registrasi']) && $_POST['nomor_registrasi'] == $soal['nomor_registrasi']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($soal['nomor_registrasi'] . ' - ' . $soal['department'] . $status_text); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span class="form-text">
                            <i class="fas fa-info-circle"></i>
                            Pilih nomor registrasi soal yang akan dibuat aspek penilaiannya. 
                            Soal yang sudah digunakan akan ditandai.
                        </span>
                    </div>

                    <!-- Soal Preview -->
                    <div id="soalPreview" class="soal-preview" style="display: none;">
                        <h4><i class="fas fa-eye"></i> Preview Soal</h4>
                        <div class="preview-content">
                            <strong>Department:</strong> <span id="previewDepartment">-</span><br>
                            <strong>Skenario Klinik:</strong>
                            <div id="previewSkenario" class="preview-text"></div>
                        </div>
                    </div>
                </div>

                <!-- Jumlah Aspek -->
                <div class="form-section">
                    <h3><i class="fas fa-list-ol"></i> Jumlah Aspek Penilaian</h3>
                    <div class="form-group">
                        <label for="jumlah_aspek">
                            Jumlah Aspek Penilaian (1-40) 
                            <span class="required">*</span>
                            <span class="max-aspek-info"><i class="fas fa-info-circle"></i> Maksimal 40</span>
                        </label>
                        <div class="input-group">
                            <input type="number" id="jumlah_aspek" name="jumlah_aspek" 
                                   min="1" max="40" value="<?php echo isset($_POST['jumlah_aspek']) ? $_POST['jumlah_aspek'] : 1; ?>" 
                                   class="form-control" required>
                            <button type="button" id="generateForm" class="btn btn-primary">
                                <i class="fas fa-sync"></i> Generate Form
                            </button>
                        </div>
                        <span class="form-text">
                            <i class="fas fa-info-circle"></i>
                            Masukkan jumlah aspek penilaian yang diinginkan (minimal 1, maksimal 40).
                        </span>
                    </div>
                </div>

                <div id="aspekContainer">
                    <!-- Dynamic form akan di-generate di sini -->
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> Simpan Semua Aspek
                    </button>
                    <button type="button" id="resetForm" class="btn btn-secondary">
                        <i class="fas fa-redo"></i> Reset
                    </button>
                    <a href="dashboard.php" class="btn btn-outline">
                        <i class="fas fa-arrow-left"></i> Kembali
                    </a>
                </div>
            </form>
        </div>

        <!-- Aspek Terdaftar -->
        <?php if (!empty($aspek_terdaftar)): ?>
            <div class="card">
                <div class="card-header">
                    <h2>
                        <i class="fas fa-list"></i> Aspek Penilaian Terdaftar
                        <span class="badge-count"><?php echo count($aspek_terdaftar); ?> aspek</span>
                    </h2>
                </div>

                <div class="department-filter">
                    <label for="filterDepartment"><i class="fas fa-filter"></i> Filter Department:</label>
                    <select id="filterDepartment" class="form-control">
                        <option value="">Semua Department</option>
                        <?php foreach ($departments as $key => $value): ?>
                            <option value="<?php echo $key; ?>"><?php echo htmlspecialchars($value); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="aspek-list">
                    <?php 
                    $current_department = '';
                    foreach ($aspek_terdaftar as $aspek): 
                        if ($current_department != $aspek['department']): 
                            $current_department = $aspek['department'];
                    ?>
                        <div class="department-header" data-department="<?php echo $aspek['department']; ?>">
                            <h3>
                                <i class="fas fa-building"></i> 
                                <?php echo $departments[$aspek['department']] ?? $aspek['department']; ?>
                                <small>(<?php echo $aspek['nomor_registrasi']; ?>)</small>
                            </h3>
                        </div>
                    <?php endif; ?>
                    
                    <div class="aspek-item" data-department="<?php echo $aspek['department']; ?>">
                        <div class="aspek-header">
                            <h4>Aspek <?php echo $aspek['nomor_urut']; ?></h4>
                            <span class="badge badge-info">
                                <i class="fas fa-star"></i> Skor: <?php echo $aspek['skor_dinilai']; ?>
                            </span>
                        </div>
                        <div class="aspek-content">
                            <strong>Aspek yang dinilai:</strong>
                            <div class="content-preview">
                                <?php echo $aspek['aspek_yang_dinilai']; ?>
                            </div>
                            <strong>Keterangan Skor:</strong>
                            <div class="content-preview">
                                <?php echo $aspek['keterangan_skor']; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Scroll to Top -->
    <button class="scroll-top" id="scrollTopBtn" title="Kembali ke atas">
        <i class="fas fa-arrow-up"></i>
    </button>

    <script>
        // ===== SIDEBAR TOGGLE =====
        const hamburger = document.getElementById('hamburgerBtn');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');

        function toggleSidebar() {
            sidebar.classList.toggle('open');
            overlay.classList.toggle('active');
        }

        hamburger.addEventListener('click', toggleSidebar);
        overlay.addEventListener('click', toggleSidebar);

        // ===== CLOSE SIDEBAR ON RESIZE =====
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                sidebar.classList.remove('open');
                overlay.classList.remove('active');
            }
        });

        // ===== SCROLL TO TOP =====
        const scrollBtn = document.getElementById('scrollTopBtn');
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                scrollBtn.classList.add('visible');
            } else {
                scrollBtn.classList.remove('visible');
            }
        });

        scrollBtn.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });

        // ===== DATA SOAL =====
        const soalData = <?php echo json_encode($soal_praktik); ?>;

        // ===== INIT TINYMCE =====
        function initTinyMCE() {
            tinymce.init({
                selector: '.tinymce-editor',
                plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table help wordcount',
                toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table media | code',
                menubar: 'file edit view insert format tools table help',
                height: 200,
                content_style: 'body { font-family: Arial, sans-serif; font-size: 14px; }',
                license_key: 'gpl',
                promotion: false,
                branding: false
            });
        }

        // ===== UPDATE SOAL PREVIEW =====
        document.getElementById('nomor_registrasi').addEventListener('change', function() {
            const nomorRegistrasi = this.value;
            const previewDiv = document.getElementById('soalPreview');
            
            if (nomorRegistrasi) {
                const soal = soalData.find(s => s.nomor_registrasi === nomorRegistrasi);
                if (soal) {
                    document.getElementById('previewDepartment').textContent = soal.department;
                    document.getElementById('previewSkenario').innerHTML = soal.skenario_klinik;
                    previewDiv.style.display = 'block';
                    
                    const departmentSelect = document.getElementById('department');
                    if (!departmentSelect.value && soal.department) {
                        departmentSelect.value = soal.department;
                    }
                }
            } else {
                previewDiv.style.display = 'none';
            }
        });

        // ===== FILTER DEPARTMENT =====
        document.getElementById('filterDepartment').addEventListener('change', function() {
            const selectedDepartment = this.value;
            const aspekItems = document.querySelectorAll('.aspek-item, .department-header');
            
            aspekItems.forEach(item => {
                if (!selectedDepartment || item.dataset.department === selectedDepartment) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });

        // ===== GENERATE ASPEK FORMS =====
        document.getElementById('generateForm').addEventListener('click', function() {
            generateAspekForms();
        });

        function generateAspekForms() {
            const jumlahAspek = parseInt(document.getElementById('jumlah_aspek').value);
            const container = document.getElementById('aspekContainer');
            const department = document.getElementById('department').value;
            const nomorRegistrasi = document.getElementById('nomor_registrasi').value;
            
            if (!department) {
                alert('Silakan pilih department terlebih dahulu');
                return;
            }
            
            if (!nomorRegistrasi) {
                alert('Silakan pilih nomor registrasi terlebih dahulu');
                return;
            }
            
            // Ubah batas validasi dari 15 menjadi 40
            if (jumlahAspek < 1 || jumlahAspek > 40) {
                alert('Jumlah aspek harus antara 1-40');
                return;
            }

            const departmentText = document.getElementById('department').options[document.getElementById('department').selectedIndex].text;

            let html = `
                <div class="form-section">
                    <h3><i class="fas fa-clipboard-list"></i> Form Aspek Penilaian</h3>
                    <div class="form-info">
                        <strong>Department:</strong> ${departmentText}<br>
                        <strong>Nomor Registrasi:</strong> ${nomorRegistrasi}
                    </div>
                    <span class="form-text" style="margin-top: 8px;">
                        <i class="fas fa-info-circle"></i>
                        Total aspek yang akan dibuat: <strong>${jumlahAspek}</strong> aspek
                    </span>
                </div>
            `;
            
            for (let i = 1; i <= jumlahAspek; i++) {
                html += `
                <div class="aspek-form-group">
                    <div class="aspek-header">
                        <h3><i class="fas fa-clipboard-list"></i> Aspek Penilaian ${i} dari ${jumlahAspek}</h3>
                    </div>
                    
                    <div class="form-group">
                        <label for="nomor_urut_${i}">Nomor Urut Aspek:</label>
                        <input type="number" id="nomor_urut_${i}" name="aspek[${i}][nomor_urut]" 
                               value="${i}" class="form-control" readonly>
                    </div>

                    <div class="form-group">
                        <label for="aspek_yang_dinilai_${i}">Aspek Yang Dinilai <span class="required">*</span></label>
                        <textarea id="aspek_yang_dinilai_${i}" name="aspek[${i}][aspek_yang_dinilai]" 
                                  class="tinymce-editor form-control" rows="4" placeholder="Masukkan deskripsi aspek yang akan dinilai..."></textarea>
                    </div>

                    <div class="form-group">
                        <label>Skor Yang Dinilai:</label>
                        <div class="skor-options">
                            <label class="checkbox-label">
                                <input type="checkbox" name="aspek[${i}][skor_dinilai][]" value="0" checked> Skor 0
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="aspek[${i}][skor_dinilai][]" value="1" checked> Skor 1
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="aspek[${i}][skor_dinilai][]" value="2" checked> Skor 2
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="keterangan_skor_${i}">Keterangan Skor <span class="required">*</span></label>
                        <textarea id="keterangan_skor_${i}" name="aspek[${i}][keterangan_skor]" 
                                  class="tinymce-editor form-control" rows="4" placeholder="Masukkan keterangan untuk setiap skor..."></textarea>
                    </div>
                    
                    <hr class="aspek-divider">
                </div>
                `;
            }
            
            container.innerHTML = html;
            
            // Re-initialize TinyMCE untuk textarea baru
            initTinyMCE();
        }

        // ===== GENERATE FORM ON LOAD =====
        <?php if (!empty($_POST)): ?>
        document.addEventListener('DOMContentLoaded', function() {
            generateAspekForms();
        });
        <?php endif; ?>

        // ===== RESET FORM =====
        document.getElementById('resetForm').addEventListener('click', function() {
            if (confirm('Apakah Anda yakin ingin mereset semua data?')) {
                document.getElementById('aspekForm').reset();
                document.getElementById('aspekContainer').innerHTML = '';
                document.getElementById('jumlah_aspek').value = 1;
                document.getElementById('soalPreview').style.display = 'none';
            }
        });

        // ===== INIT TINYMCE =====
        initTinyMCE();
    </script>
</body>
</html>