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

// API endpoint untuk AJAX edit
if (isset($_GET['edit']) && $_SERVER['REQUEST_METHOD'] == 'GET') {
    $id = $_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian_praktik WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'id' => $data['id'],
                'nomor_urut' => $data['nomor_urut'],
                'aspek_yang_dinilai' => $data['aspek_yang_dinilai'],
                'skor_dinilai' => $data['skor_dinilai'],
                'keterangan_skor' => $data['keterangan_skor']
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
        }
        exit;
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Gagal mengambil data']);
        exit;
    }
}

// Proses edit aspek penilaian
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_aspek'])) {
    $id = $_POST['id'];
    $nomor_urut = $_POST['nomor_urut'];
    $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()
                              WHERE id = ?");
        $stmt->execute([$aspek_yang_dinilai, $skor_dinilai, $keterangan_skor, $id]);
        
        $success_message = 'Aspek penilaian berhasil diperbarui!';
    } catch (PDOException $e) {
        $error = 'Gagal memperbarui data: ' . $e->getMessage();
    }
}

// Proses hapus aspek penilaian
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM aspek_penilaian_praktik WHERE id = ?");
        $stmt->execute([$id]);
        
        // Update nomor urut yang tersisa
        $stmt = $pdo->query("SET @count = 0");
        $stmt = $pdo->query("UPDATE aspek_penilaian_praktik SET nomor_urut = @count:= @count + 1 ORDER BY nomor_urut");
        
        $success_message = 'Aspek penilaian berhasil dihapus!';
        header('Location: preview_aspek_penilaian.php?success=1');
        exit;
    } catch (PDOException $e) {
        $error = 'Gagal menghapus data: ' . $e->getMessage();
    }
}

// Ambil data aspek penilaian dari database
$aspek_penilaian = [];
try {
    $stmt = $pdo->query("SELECT * FROM aspek_penilaian_praktik ORDER BY nomor_urut");
    $aspek_penilaian = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = 'Gagal mengambil data aspek penilaian';
}

// Ambil data spesifik untuk edit modal
$edit_data = [];
if (isset($_GET['edit'])) {
    $id = $_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian_praktik WHERE id = ?");
        $stmt->execute([$id]);
        $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $error = 'Gagal mengambil data untuk edit';
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview Aspek Penilaian - SOCA OSCE System</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/preview_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" class="active">
                    <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>Preview Aspek Penilaian Ujian Praktik</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="aspek_penilaian.php" class="btn btn-primary btn-sm">
                            <i class="fas fa-plus"></i> Tambah Aspek
                        </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_penilaian)): ?>
                    <div class="empty-state">
                        <i class="fas fa-clipboard-list"></i>
                        <h3>Belum Ada Aspek Penilaian</h3>
                        <p>Silakan tambahkan aspek penilaian terlebih dahulu</p>
                        <a href="aspek_penilaian.php" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Tambah Aspek Penilaian
                        </a>
                    </div>
                <?php else: ?>
                    <div class="preview-card">
                        <div class="preview-header">
                            <h2><i class="fas fa-table"></i> Tabel Aspek Penilaian</h2>
                            <div class="preview-actions">
                                <button onclick="window.print()" class="btn btn-outline btn-sm">
                                    <i class="fas fa-print"></i> Print
                                </button>
                                <button onclick="exportToPDF()" class="btn btn-outline btn-sm">
                                    <i class="fas fa-file-pdf"></i> Export PDF
                                </button>
                                <a href="aspek_penilaian.php" class="btn btn-primary btn-sm">
                                    <i class="fas fa-edit"></i> Edit Semua
                                </a>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="preview-table">
                                <thead>
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="30%">Aspek yang Dinilai</th>
                                        <th width="8%">Skor 0</th>
                                        <th width="8%">Skor 1</th>
                                        <th width="8%">Skor 2</th>
                                        <th width="30%">Keterangan Skor</th>
                                        <th width="11%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($aspek_penilaian as $aspek): ?>
                                        <?php
                                        $skor_dinilai = explode(',', $aspek['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);
                                        ?>
                                        <tr>
                                            <td class="text-center"><?php echo $aspek['nomor_urut']; ?></td>
                                            <td class="aspek-content">
                                                <div class="aspek-text">
                                                    <?php echo $aspek['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['keterangan_skor']; ?>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="action-buttons">
                                                    <button class="btn btn-warning btn-sm btn-edit" 
                                                            onclick="openEditModal(<?php echo $aspek['id']; ?>)"
                                                            data-toggle="tooltip" title="Edit Aspek">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <a href="preview_aspek_penilaian.php?delete=<?php echo $aspek['id']; ?>" 
                                                       class="btn btn-danger btn-sm"
                                                       onclick="return confirm('Apakah Anda yakin ingin menghapus aspek ini?')"
                                                       data-toggle="tooltip" title="Hapus Aspek">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="preview-footer">
                            <div class="total-aspek">
                                <strong>Total Aspek: <?php echo count($aspek_penilaian); ?></strong>
                            </div>
                            <div class="preview-info">
                                <small>Terakhir update: <?php echo date('d/m/Y H:i'); ?></small>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="summary-cards">
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-list-ol"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo count($aspek_penilaian); ?></h3>
                                <p>Total Aspek</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="summary-content">
                                <h3>
                                    <?php
                                    $total_skor = 0;
                                    foreach ($aspek_penilaian as $aspek) {
                                        $skor_dinilai = explode(',', $aspek['skor_dinilai']);
                                        $total_skor += count($skor_dinilai);
                                    }
                                    echo $total_skor;
                                    ?>
                                </h3>
                                <p>Total Opsi Skor</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-edit"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo count($aspek_penilaian); ?></h3>
                                <p>Aspek Siap Edit</p>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-edit"></i> Edit Aspek Penilaian</h3>
                <span class="close" onclick="closeEditModal()">&times;</span>
            </div>
            <form id="editForm" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_id">
                    <input type="hidden" name="edit_aspek" value="1">
                    
                    <div class="form-group">
                        <label for="edit_nomor_urut">Nomor Urut Aspek:</label>
                        <input type="number" id="edit_nomor_urut" name="nomor_urut" class="form-control" readonly>
                    </div>

                    <div class="form-group">
                        <label for="edit_aspek_yang_dinilai">Aspek Yang Dinilai:</label>
                        <textarea id="edit_aspek_yang_dinilai" name="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="skor_dinilai[]" value="0" id="edit_skor_0"> Skor 0
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="skor_dinilai[]" value="1" id="edit_skor_1"> Skor 1
                            </label>
                            <label class="checkbox-label">
                                <input type="checkbox" name="skor_dinilai[]" value="2" id="edit_skor_2"> Skor 2
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="edit_keterangan_skor">Keterangan Skor:</label>
                        <textarea id="edit_keterangan_skor" name="keterangan_skor" class="tinymce-editor form-control" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeEditModal()">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>

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

        // Modal functions
        function openEditModal(id) {
            // Load data via AJAX
            fetch(`preview_aspek_penilaian.php?edit=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('edit_id').value = data.id;
                        document.getElementById('edit_nomor_urut').value = data.nomor_urut;
                        
                        // Set skor checkboxes
                        const skorDinilai = data.skor_dinilai.split(',');
                        document.getElementById('edit_skor_0').checked = skorDinilai.includes('0');
                        document.getElementById('edit_skor_1').checked = skorDinilai.includes('1');
                        document.getElementById('edit_skor_2').checked = skorDinilai.includes('2');
                        
                        // Set TinyMCE content after initialization
                        setTimeout(() => {
                            if (tinymce.get('edit_aspek_yang_dinilai')) {
                                tinymce.get('edit_aspek_yang_dinilai').setContent(data.aspek_yang_dinilai);
                            }
                            if (tinymce.get('edit_keterangan_skor')) {
                                tinymce.get('edit_keterangan_skor').setContent(data.keterangan_skor);
                            }
                        }, 500);
                        
                        document.getElementById('editModal').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Gagal memuat data untuk edit');
                });
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
            // Reset form
            document.getElementById('editForm').reset();
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('editModal');
            if (event.target == modal) {
                closeEditModal();
            }
        }

        function exportToPDF() {
            alert('Fitur export PDF akan segera tersedia!');
        }

        // Initialize TinyMCE when page loads
        document.addEventListener('DOMContentLoaded', function() {
            initTinyMCE();
            
            // Auto-adjust row height
            const rows = document.querySelectorAll('.preview-table tbody tr');
            rows.forEach(row => {
                const aspekCell = row.querySelector('.aspek-content');
                const keteranganCell = row.querySelector('.keterangan-content');
                
                const aspekHeight = aspekCell.scrollHeight;
                const keteranganHeight = keteranganCell.scrollHeight;
                
                const maxHeight = Math.max(aspekHeight, keteranganHeight);
                
                aspekCell.style.height = maxHeight + 'px';
                keteranganCell.style.height = maxHeight + 'px';
            });
        });
    </script>
</body>
</html>