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

// Proses penyimpanan data aspek penilaian
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $jumlah_aspek = isset($_POST['jumlah_aspek']) ? intval($_POST['jumlah_aspek']) : 0;
    $aspek_data = $_POST['aspek'] ?? [];
    
    // Validasi data
    $errors = [];
    
    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';
    }
    
    // Simpan ke database jika tidak ada error
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            // Hapus data lama jika ada (optional, sesuaikan dengan kebutuhan)
            // $pdo->query("DELETE FROM aspek_penilaian_praktik");
            
            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, created_at) 
                                          VALUES (?, ?, ?, ?, NOW())");
                    $stmt->execute([$nomor_urut, $aspek_yang_dinilai, $skor_dinilai, $keterangan_skor]);
                }
            }
            
            $pdo->commit();
            $success_message = 'Data aspek penilaian berhasil disimpan!';
            
        } 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 * FROM aspek_penilaian_praktik ORDER BY 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="../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">
                            <div class="form-group">
                                <label for="jumlah_aspek">Jumlah Aspek Penilaian (1-15):</label>
                                <input type="number" id="jumlah_aspek" name="jumlah_aspek" 
                                       min="1" max="15" value="<?php echo count($aspek_terdaftar) ?: 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 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="aspek-list">
                            <?php foreach ($aspek_terdaftar as $aspek): ?>
                            <div class="aspek-item">
                                <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>
        // Initialize TinyMCE
        tinymce.init({
            selector: '.tinymce-editor',
            plugins: 'advlist autolink lists link image charmap preview anchor table',
            toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table',
            menubar: 'file edit insert view format table tools',
            height: 200,
            content_style: 'body { font-family: Arial, sans-serif; font-size: 14px; }'
        });

        document.getElementById('generateForm').addEventListener('click', function() {
            generateAspekForms();
        });

        function generateAspekForms() {
            const jumlahAspek = parseInt(document.getElementById('jumlah_aspek').value);
            const container = document.getElementById('aspekContainer');
            
            if (jumlahAspek < 1 || jumlahAspek > 15) {
                alert('Jumlah aspek harus antara 1-15');
                return;
            }

            let html = '';
            
            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"></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"> Skor 0
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="aspek[${i}][skor_dinilai][]" value="1"> Skor 1
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="aspek[${i}][skor_dinilai][]" value="2"> 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"></textarea>
                    </div>
                    
                    <hr class="aspek-divider">
                </div>
                `;
            }
            
            container.innerHTML = html;
            
            // Re-initialize TinyMCE for new textareas
            tinymce.init({
                selector: '.tinymce-editor',
                plugins: 'advlist autolink lists link image charmap preview anchor table',
                toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table',
                menubar: 'file edit insert view format table tools',
                height: 200
            });
        }

        // Generate form on page load if there are existing data
        <?php if (!empty($aspek_terdaftar)): ?>
        document.addEventListener('DOMContentLoaded', function() {
            generateAspekForms();
            
            // Isi data yang sudah ada (untuk edit)
            <?php foreach ($aspek_terdaftar as $aspek): ?>
            const index = <?php echo $aspek['nomor_urut']; ?>;
            
            // Set aspek yang dinilai
            if (tinymce.get('aspek_yang_dinilai_' + index)) {
                tinymce.get('aspek_yang_dinilai_' + index).setContent(`<?php echo addslashes($aspek['aspek_yang_dinilai']); ?>`);
            }
            
            // Set skor dinilai
            const skorDinilai = '<?php echo $aspek['skor_dinilai']; ?>'.split(',');
            skorDinilai.forEach(skor => {
                const checkbox = document.querySelector(`input[name="aspek[${index}][skor_dinilai][]"][value="${skor}"]`);
                if (checkbox) checkbox.checked = true;
            });
            
            // Set keterangan skor
            if (tinymce.get('keterangan_skor_' + index)) {
                tinymce.get('keterangan_skor_' + index).setContent(`<?php echo addslashes($aspek['keterangan_skor']); ?>`);
            }
            <?php endforeach; ?>
        });
        <?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;
            }
        });
    </script>
</body>
</html>