<?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'] ?? [];
    
    // Validasi data
    $errors = [];
    
    if (empty($department)) {
        $errors[] = 'Department harus dipilih';
    }
    
    if (empty($nomor_registrasi)) {
        $errors[] = 'Nomor registrasi harus dipilih';
    }
    
    if ($jumlah_aspek < 1 || $jumlah_aspek > 15) {
        $errors[] = 'Jumlah aspek harus antara 1-15';
    }
    
    if (count($aspek_data) != $jumlah_aspek) {
        $errors[] = 'Jumlah data aspek tidak sesuai';
    }
    
    // Cek apakah nomor registrasi sudah memiliki aspek penilaian
    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';
    }
    
    // Simpan ke database jika tidak ada error
    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
                    ]);
                }
            }
            
            // Update status soal praktik menjadi digunakan
            $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!';
            
            // Reset form setelah sukses
            unset($_POST);
            
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = 'Gagal menyimpan data: ' . $e->getMessage();
        }
    }
}

// Ambil data aspek yang sudah ada (untuk edit)
$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, akan dibuat otomatis
}
?>

<!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="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/aspek_penilaian.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- TinyMCE Editor -->
    <script src="https://cdn.tiny.cloud/1/p93sjg5qtxeh4t0y8uynvaig0oo66ac2ahh35s86k31iu0yv/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>SOCA/OSCE System</h2>
                <p>Admin Panel</p>
            </div>
            <ul class="sidebar-menu">
                <li><a href="dashboard.php">
                    <i class="fas fa-tachometer-alt"></i> Dashboard
                </a></li>
                <li><a href="bank_soal_teori.php">
                    <i class="fas fa-question-circle"></i> Bank Soal Teori
                </a></li>
                <li><a href="list_soal_teori.php">
                    <i class="fas fa-eye"></i> Lihat Soal Teori
                </a></li>
                <li><a href="bank_soal_praktik.php">
                    <i class="fas fa-stethoscope"></i> Bank Soal Praktik
                </a></li>
                <li><a href="list_soal_praktik.php">
                    <i class="fas fa-eye"></i> Lihat Soal Praktik
                </a></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 Penilaian
                </a></li>
                <li><a href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a></li>
            </ul>
        </div>

        <div class="main-content">
            <div class="header">
                <h1>ASPEK PENILAIAN UJIAN PRAKTIK</h1>
                <div class="user-info">
                    <span><i class="fas fa-user"></i> Halo, <?php echo $_SESSION['user_name'] ?? 'Admin'; ?></span>
                    <a href="../logout.php" class="btn btn-danger btn-sm">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>

            <div class="content">
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <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">
                        <?php echo htmlspecialchars($success_message); ?>
                    </div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-cog"></i> KONFIGURASI ASPEK PENILAIAN</h2>
                    </div>
                    <div class="card-body">
                        <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:</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:</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_class = $soal['digunakan_di_ujian'] ? 'status-used' : 'status-available';
                                            $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']; ?>"
                                                    class="<?php echo $status_class; ?>"
                                                <?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>
                                    <small class="form-text text-muted">
                                        Pilih nomor registrasi soal yang akan dibuat aspek penilaiannya. 
                                        Soal yang sudah digunakan akan ditandai.
                                    </small>
                                </div>

                                <!-- Soal Preview -->
                                <div id="soalPreview" class="soal-preview" style="display: none;">
                                    <h4>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-15):</label>
                                    <div class="input-group">
                                        <input type="number" id="jumlah_aspek" name="jumlah_aspek" 
                                               min="1" max="15" 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>
                                </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 ke Dashboard
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Tampilkan aspek yang sudah terdaftar -->
                <?php if (!empty($aspek_terdaftar)): ?>
                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-list"></i> Aspek Penilaian Terdaftar</h2>
                    </div>
                    <div class="card-body">
                        <div class="department-filter">
                            <label for="filterDepartment">Filter by 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">
                                        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>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Data soal untuk preview
        const soalData = <?php echo json_encode($soal_praktik); ?>;

        // Initialize 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 ketika nomor registrasi dipilih
        document.getElementById('nomor_registrasi').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            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';
                    
                    // Auto-set department jika belum dipilih
                    const departmentSelect = document.getElementById('department');
                    if (!departmentSelect.value && soal.department) {
                        departmentSelect.value = soal.department;
                    }
                }
            } else {
                previewDiv.style.display = 'none';
            }
        });

        // Filter department untuk aspek terdaftar
        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';
                }
            });
        });

        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;
            }
            
            if (jumlahAspek < 1 || jumlahAspek > 15) {
                alert('Jumlah aspek harus antara 1-15');
                return;
            }

            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> ${document.getElementById('department').options[document.getElementById('department').selectedIndex].text}<br>
                        <strong>Nomor Registrasi:</strong> ${nomorRegistrasi}
                    </div>
                </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}</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:</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:</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 page load jika ada data yang sudah ada
        <?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';
            }
        });

        // Initialize TinyMCE saat pertama kali load
        initTinyMCE();
    </script>
</body>
</html>