<?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',
    'oral_biologi' => 'Oral Biologi'
];

// Ambil parameter
$aspek_id = $_GET['id'] ?? 0;
$filter_department = $_GET['department'] ?? '';
$filter_nomor_registrasi = $_GET['nomor_registrasi'] ?? '';

// Ambil data aspek yang akan di-review
$aspek_data = [];
$soal_data = [];
try {
    $stmt = $pdo->prepare("SELECT ap.*, bs.* 
                          FROM aspek_penilaian_praktik ap 
                          LEFT JOIN bank_soal_praktik bs ON ap.nomor_registrasi = bs.nomor_registrasi 
                          WHERE ap.id = ?");
    $stmt->execute([$aspek_id]);
    $aspek_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$aspek_data) {
        throw new Exception('Data aspek tidak ditemukan');
    }
    
} catch (Exception $e) {
    $error = $e->getMessage();
}

// Proses update data aspek
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_aspek'])) {
    $aspek_yang_dinilai = $_POST['aspek_yang_dinilai'];
    $keterangan_skor = $_POST['keterangan_skor'];
    $skor_dinilai = implode(',', $_POST['skor_dinilai'] ?? []);
    
    try {
        $stmt = $pdo->prepare("UPDATE aspek_penilaian_praktik 
                              SET aspek_yang_dinilai = ?, skor_dinilai = ?, keterangan_skor = ?, 
                                  updated_at = NOW(), reviewer = ?, reviewed_at = NOW()
                              WHERE id = ?");
        $stmt->execute([
            $aspek_yang_dinilai, 
            $skor_dinilai, 
            $keterangan_skor,
            $_SESSION['user_name'],
            $aspek_id
        ]);
        
        $success_message = 'Aspek penilaian berhasil diperbarui dan direview!';
        
        // Refresh data
        $stmt = $pdo->prepare("SELECT ap.*, bs.* FROM aspek_penilaian_praktik ap 
                              LEFT JOIN bank_soal_praktik bs ON ap.nomor_registrasi = bs.nomor_registrasi 
                              WHERE ap.id = ?");
        $stmt->execute([$aspek_id]);
        $aspek_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        $error = 'Gagal memperbarui data: ' . $e->getMessage();
    }
}

// Build URL kembali dengan filter
$back_url = "preview_aspek_penilaian.php";
if (!empty($filter_department)) {
    $back_url .= "?department=" . urlencode($filter_department);
    if (!empty($filter_nomor_registrasi)) {
        $back_url .= "&nomor_registrasi=" . urlencode($filter_nomor_registrasi);
    }
} elseif (!empty($filter_nomor_registrasi)) {
    $back_url .= "?nomor_registrasi=" . urlencode($filter_nomor_registrasi);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Review Aspek Penilaian - SOCA OSCE System</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/review_aspek.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">
                    <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="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a></li>
            </ul>
        </div>

        <div class="main-content">
            <div class="header">
                <h1>Review Aspek Penilaian</h1>
                <div class="user-info">
                    <span><i class="fas fa-user"></i> Halo, <?php echo $_SESSION['user_name'] ?? 'Admin'; ?></span>
                    <div class="header-actions">
                        <a href="<?php echo $back_url; ?>" class="btn btn-outline btn-sm">
                            <i class="fas fa-arrow-left"></i> Kembali
                        </a>
                        <a href="../logout.php" class="btn btn-danger btn-sm">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </div>

            <div class="content">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>

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

                <?php if (!empty($aspek_data)): ?>
                <!-- Info Soal -->
                <div class="info-card">
                    <div class="info-header">
                        <h3><i class="fas fa-info-circle"></i> Informasi Soal</h3>
                    </div>
                    <div class="info-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <strong>Department:</strong>
                                <span><?php echo $departments[$aspek_data['department']] ?? $aspek_data['department']; ?></span>
                            </div>
                            <div class="info-item">
                                <strong>Nomor Registrasi:</strong>
                                <span><?php echo htmlspecialchars($aspek_data['nomor_registrasi']); ?></span>
                            </div>
                            <div class="info-item">
                                <strong>Nomor Urut Aspek:</strong>
                                <span><?php echo $aspek_data['nomor_urut']; ?></span>
                            </div>
                            <div class="info-item">
                                <strong>Dibuat:</strong>
                                <span><?php echo date('d/m/Y H:i', strtotime($aspek_data['created_at'])); ?></span>
                            </div>
                            <?php if (!empty($aspek_data['reviewer'])): ?>
                            <div class="info-item">
                                <strong>Direview oleh:</strong>
                                <span><?php echo htmlspecialchars($aspek_data['reviewer']); ?></span>
                            </div>
                            <div class="info-item">
                                <strong>Tanggal Review:</strong>
                                <span><?php echo date('d/m/Y H:i', strtotime($aspek_data['reviewed_at'])); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($aspek_data['skenario_klinik'])): ?>
                        <div class="soal-preview">
                            <h4><i class="fas fa-file-medical"></i> Skenario Klinik:</h4>
                            <div class="preview-content">
                                <?php echo $aspek_data['skenario_klinik']; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Form Review -->
                <div class="review-card">
                    <div class="review-header">
                        <h3><i class="fas fa-edit"></i> Review & Edit Aspek Penilaian</h3>
                    </div>
                    <form method="POST" class="review-form">
                        <input type="hidden" name="update_aspek" value="1">
                        
                        <div class="form-section">
                            <h4>Aspek Yang Dinilai</h4>
                            <div class="form-group">
                                <textarea id="aspek_yang_dinilai" name="aspek_yang_dinilai" 
                                          class="tinymce-editor form-control" rows="6"><?php echo htmlspecialchars($aspek_data['aspek_yang_dinilai']); ?></textarea>
                            </div>
                        </div>

                        <div class="form-section">
                            <h4>Skor Yang Dinilai</h4>
                            <div class="form-group">
                                <div class="skor-options">
                                    <?php
                                    $skor_dinilai = explode(',', $aspek_data['skor_dinilai']);
                                    $has_skor_0 = in_array('0', $skor_dinilai);
                                    $has_skor_1 = in_array('1', $skor_dinilai);
                                    $has_skor_2 = in_array('2', $skor_dinilai);
                                    ?>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_dinilai[]" value="0" <?php echo $has_skor_0 ? 'checked' : ''; ?>> 
                                        Skor 0
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_dinilai[]" value="1" <?php echo $has_skor_1 ? 'checked' : ''; ?>> 
                                        Skor 1
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_dinilai[]" value="2" <?php echo $has_skor_2 ? 'checked' : ''; ?>> 
                                        Skor 2
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-section">
                            <h4>Keterangan Skor</h4>
                            <div class="form-group">
                                <textarea id="keterangan_skor" name="keterangan_skor" 
                                          class="tinymce-editor form-control" rows="6"><?php echo htmlspecialchars($aspek_data['keterangan_skor']); ?></textarea>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save"></i> Simpan Perubahan & Tandai Sudah Direview
                            </button>
                            <a href="preview_aspek_penilaian.php" class="btn btn-secondary">
                                <i class="fas fa-arrow"></i> Kembali
                            </a>
                            <a href="<?php echo $back_url; ?>" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Batal
                            </a>
                            <button type="button" onclick="resetForm()" class="btn btn-outline">
                                <i class="fas fa-redo"></i> Reset
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Preview Card -->
                <div class="preview-card">
                    <div class="preview-header">
                        <h3><i class="fas fa-eye"></i> Preview Hasil</h3>
                    </div>
                    <div class="preview-body">
                        <table class="preview-table">
                            <thead>
                                <tr>
                                    <th width="5%">No</th>
                                    <th width="35%">Aspek yang Dinilai</th>
                                    <th width="10%">Skor 0</th>
                                    <th width="10%">Skor 1</th>
                                    <th width="10%">Skor 2</th>
                                    <th width="30%">Keterangan Skor</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="text-center"><?php echo $aspek_data['nomor_urut']; ?></td>
                                    <td class="aspek-content">
                                        <div class="aspek-text">
                                            <?php echo $aspek_data['aspek_yang_dinilai']; ?>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($has_skor_0): ?>
                                            <span class="skor-check"><i class="fas fa-check"></i></span>
                                        <?php else: ?>
                                            <span class="skor-empty">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($has_skor_1): ?>
                                            <span class="skor-check"><i class="fas fa-check"></i></span>
                                        <?php else: ?>
                                            <span class="skor-empty">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($has_skor_2): ?>
                                            <span class="skor-check"><i class="fas fa-check"></i></span>
                                        <?php else: ?>
                                            <span class="skor-empty">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="keterangan-content">
                                        <div class="keterangan-text">
                                            <?php echo $aspek_data['keterangan_skor']; ?>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <h3>Data Aspek Tidak Ditemukan</h3>
                    <p>Aspek penilaian yang diminta tidak ditemukan dalam database.</p>
                    <a href="preview_aspek_penilaian.php" class="btn btn-primary">
                        <i class="fas fa-arrow-left"></i> Kembali ke Preview
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Initialize TinyMCE
        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
        });

        function resetForm() {
            if (confirm('Apakah Anda yakin ingin mengembalikan data ke keadaan semula?')) {
                document.querySelector('.review-form').reset();
                
                // Reset TinyMCE content
                setTimeout(() => {
                    if (tinymce.get('aspek_yang_dinilai')) {
                        tinymce.get('aspek_yang_dinilai').setContent(`<?php echo addslashes($aspek_data['aspek_yang_dinilai']); ?>`);
                    }
                    if (tinymce.get('keterangan_skor')) {
                        tinymce.get('keterangan_skor').setContent(`<?php echo addslashes($aspek_data['keterangan_skor']); ?>`);
                    }
                }, 100);
            }
        }

        // Auto-update preview ketika form berubah
        document.querySelector('.review-form').addEventListener('input', function() {
            // Preview akan otomatis terupdate karena menggunakan data yang sama
        });
    </script>
</body>
</html>