
<?php $__env->startSection('title', 'Peraturan Admin'); ?>

<?php $__env->startSection('styles'); ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <style>
        body {
            background: #f4f4f4;
        }

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }


        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }
        
        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .main-header .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .main-header .header-actions button {
            background: #d72660;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
        }

        .main-header .header-actions button:hover {
            background: #b61f50;
        }

        .main-header .header-actions i {
            font-size: 1.3rem;
            color: #535963;
            background: #f4f4f4;
            border-radius: 50%;
            padding: 6px;
            margin-right: 2px;
            cursor: pointer;
        }

        .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .main-content {
            padding: 32px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #22c1b6 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 28px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: #1da89c;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(34, 193, 182, 0.3);
        }

        .btn-secondary {
            background: #6b7280;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 22px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
            margin-right: 12px;
        }

        .btn-secondary:hover {
            background: #4b5563;
        }

        .btn-danger {
            background: #ef4444;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 22px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-danger:hover {
            background: #dc2626;
            transform: translateY(-1px);
        }

        .content-section {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            padding: 32px;
            margin-top: 2rem;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #23272b;
            margin-bottom: 1.5rem;
        }

        .badge {
            display: inline-block;
            padding: 6px 16px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.95rem;
        }

        .alert {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-weight: 600;
            animation: alertSlideIn 0.3s ease;
        }

        @keyframes alertSlideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #22c1b6;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        /* Tab Styles */
        .tab-container {
            margin-bottom: 2rem;
        }

        .tab-buttons {
            display: flex;
            border-bottom: 2px solid #e5e7eb;
            margin-bottom: 2rem;
        }

        .tab-button {
            padding: 12px 24px;
            background: none;
            border: none;
            color: #6b7280;
            font-weight: 600;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
        }

        .tab-button.active {
            color: #22c1b6;
            border-bottom-color: #22c1b6;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* DataTables Styling */
        .dataTables_wrapper {
            padding: 1.5rem;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .dataTables_filter input {
            border: 2px solid #e5e7eb !important;
            border-radius: 8px !important;
            padding: 8px 16px !important;
            font-size: 14px !important;
            width: 250px !important;
            transition: all 0.3s ease !important;
        }

        .dataTables_filter input:focus {
            border-color: #22c1b6 !important;
            outline: none !important;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1) !important;
        }

        #regulationTable thead th,
        #regulationTypeTable thead th {
            background: #f2f2f2 !important;
            color: black !important;
            font-weight: 600 !important;
            padding: 12px 8px !important;
            border: none !important;
            text-align: center !important;
            font-size: 14px !important;
        }

        #regulationTable tbody td,
        #regulationTypeTable tbody td {
            padding: 12px 8px !important;
            vertical-align: middle !important;
            border-bottom: 1px solid #f3f4f6 !important;
            font-size: 13px !important;
            text-align: center !important;
        }

        #regulationTable tbody tr:hover,
        #regulationTypeTable tbody tr:hover {
            background-color: #f8fafc !important;
        }

        .dataTables_info {
            color: #6b7280 !important;
            font-size: 14px !important;
            font-weight: 500 !important;
        }

        .dataTables_paginate .paginate_button {
            border: 1px solid #e5e7eb !important;
            border-radius: 6px !important;
            margin: 0 2px !important;
            padding: 6px 12px !important;
            color: #374151 !important;
            background: white !important;
        }

        .dataTables_paginate .paginate_button:hover {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        .dataTables_paginate .paginate_button.current {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: #fff;
            border-radius: 12px;
            padding: 32px 28px;
            max-width: 500px;
            width: 90%;
            margin: auto;
            box-shadow: 0 8px 32px rgba(34, 193, 182, 0.18);
            animation: modalSlideIn 0.3s ease;
            max-height: 90vh;
            overflow-y: auto;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: #23272b;
            text-align: center;
        }

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

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
            color: #374151;
        }

        .form-group input[type="text"],
        .form-group input[type="file"],
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
            background: #fff !important;
            color: #333 !important;
            font-size: 1rem;
            margin-top: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
            display: block !important;
            visibility: visible !important;
        }

        .form-group select {
            appearance: auto;
            -webkit-appearance: menulist;
            -moz-appearance: menulist;
            cursor: pointer;
        }

        .form-group select option {
            color: #333 !important;
            background: #fff !important;
            padding: 8px;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
            background: #fff !important;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .modal-actions {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-top: 24px;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 8px;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        /* Hide nice-select duplicate dropdown */
        .nice-select {
            display: none !important;
        }

        /* Force native select to show */
        select {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="admin-dashboard">
        <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Manajemen Peraturan</div>
                    <div class="subtitle">Kelola peraturan dan tipe peraturan</div>
                </div>
                <div class="header-actions">
                    <a href="feedback"><i class="fas fa-bell"></i></a>
                    <a href="pengaturan-situs"><i class="fas fa-cog"></i></a>
                    <form method="POST" action="<?php echo e(route('logout')); ?>" style="display:inline;">
                        <?php echo csrf_field(); ?>
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>
            <div class="main-content">
                <div id="alert-container"></div>

                <!-- Tab Container -->
                <div class="tab-container">
                    <div class="tab-buttons">
                        <button class="tab-button active" onclick="switchTab('regulation')">Peraturan</button>
                        <?php
                            $user = session('auth.user');
                            $isSuperadmin = $user && strtolower($user['role'] ?? '') === 'superadmin';
                        ?>
                        <?php if($isSuperadmin): ?>
                            <button class="tab-button" onclick="switchTab('regulationType')">Tipe Peraturan</button>
                        <?php endif; ?>
                    </div>

                    <!-- Regulation Tab -->
                    <div id="regulation-tab" class="tab-content active">
                        <div class="content-section">
                            <div
                                style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                                <div class="section-title">Daftar Peraturan</div>
                                <div class="header-actions">
                                    <button class="btn-secondary" onclick="loadRegulations()">
                                        <i class="fas fa-sync-alt"></i> Refresh
                                    </button>
                                    <button class="btn-primary" onclick="openAddRegulationModal()">
                                        <i class="fas fa-plus"></i> Tambah Peraturan
                                    </button>
                                </div>
                            </div>
                            <div id="regulationListContainer"></div>
                        </div>
                    </div>

                    <!-- Regulation Type Tab - Only for Superadmin -->
                    <?php if($isSuperadmin): ?>
                        <div id="regulationType-tab" class="tab-content">
                            <div class="content-section">
                                <div
                                    style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                                    <div class="section-title">Daftar Tipe Peraturan</div>
                                    <div class="header-actions">
                                        <button class="btn-secondary" onclick="loadRegulationTypes()">
                                            <i class="fas fa-sync-alt"></i> Refresh
                                        </button>
                                        <button class="btn-primary" onclick="openAddRegulationTypeModal()">
                                            <i class="fas fa-plus"></i> Tambah Tipe Peraturan
                                        </button>
                                    </div>
                                </div>
                                <div id="regulationTypeListContainer"></div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Modal Add/Edit Regulation -->
            <div id="regulationModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header" id="regulationModalTitle">Tambah Peraturan</div>
                    <form id="regulationForm">
                        <input type="hidden" id="regulation_id">
                        <div class="form-group">
                            <label for="regulation_title">Judul Peraturan *</label>
                            <input type="text" id="regulation_title" required placeholder="Masukkan judul peraturan">
                        </div>
                        <div class="form-group">
                            <label for="regulation_description">Deskripsi</label>
                            <textarea id="regulation_description" placeholder="Masukkan deskripsi peraturan" maxlength="100"></textarea>
                            <small style="color: #6b7280; font-size: 0.9rem;">Maksimal 100 karakter</small>
                        </div>
                        <div class="form-group">
                            <label for="regulation_type_id">Tipe Peraturan *</label>
                            <select id="regulation_type_id" name="regulation_type_id" required>
                                <option value="">Pilih tipe peraturan</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="regulation_file">File Peraturan *</label>
                            <input type="file" id="regulation_file" accept=".pdf,.doc,.docx" required>
                            <small style="color: #6b7280; font-size: 0.9rem;">Format: PDF, DOC, DOCX (Max: 10MB) - Wajib
                                diisi</small>
                        </div>
                        <div class="form-group">
                            <div class="checkbox-group">
                                <input type="checkbox" id="regulation_inherited">
                                <label for="regulation_inherited">Peraturan Turunan</label>
                            </div>
                        </div>
                        <div class="modal-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-save"></i> Simpan
                            </button>
                            <button type="button" class="btn-danger" onclick="closeRegulationModal()">
                                <i class="fas fa-times"></i> Batal
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Modal Add/Edit Regulation Type -->
            <div id="regulationTypeModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header" id="regulationTypeModalTitle">Tambah Tipe Peraturan</div>
                    <form id="regulationTypeForm">
                        <input type="hidden" id="regulationType_id">
                        <div class="form-group">
                            <label for="regulationType_name">Nama Tipe Peraturan *</label>
                            <input type="text" id="regulationType_name" required
                                placeholder="Masukkan nama tipe peraturan">
                        </div>
                        <div class="form-group">
                            <label for="regulationType_description">Deskripsi</label>
                            <textarea id="regulationType_description" placeholder="Masukkan deskripsi tipe peraturan" maxlength="100"></textarea>
                            <small style="color: #6b7280; font-size: 0.9rem;">Maksimal 100 karakter</small>
                        </div>
                        <div class="modal-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-save"></i> Simpan
                            </button>
                            <button type="button" class="btn-danger" onclick="closeRegulationTypeModal()">
                                <i class="fas fa-times"></i> Batal
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script>
        const baseUrl = '<?php echo e(env('BASE_URL')); ?>';
        let regulationList = [];
        let regulationTypeList = [];

        // Check user role
        const userRole = '<?php echo e(strtolower($user['role'] ?? '')); ?>';
        const isSuperadmin = userRole === 'superadmin';

        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
            alertContainer.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
            setTimeout(() => {
                alertContainer.innerHTML = '';
            }, 4000);
        }

        function getAuthToken() {
            return '<?php echo e(session('auth.token')); ?>';
        }

        // Check superadmin access
        function checkSuperadminAccess(action = 'access this feature') {
            if (!isSuperadmin) {
                showAlert('Akses ditolak! Hanya Superadmin yang dapat ' + action, 'error');
                return false;
            }
            return true;
        }

        // Tab Functions
        function switchTab(tabName) {
            console.log('=== SWITCHING TAB ===', tabName);
            try {
                document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

                const tabButton = document.querySelector(`button[onclick="switchTab('${tabName}')"]`);
                const tabContent = document.getElementById(`${tabName}-tab`);

                if (!tabButton || !tabContent) {
                    console.error('Tab not found:', tabName);
                    return;
                }

                tabButton.classList.add('active');
                tabContent.classList.add('active');

                if (tabName === 'regulation') {
                    loadRegulations();
                } else if (tabName === 'regulationType') {
                    loadRegulationTypes(true);
                }
            } catch (error) {
                console.error('Error switching tab:', error);
                showAlert('Gagal beralih tab: ' + error.message, 'error');
            }
        }

        // Regulation Functions
        async function loadRegulations() {
            try {
                const token = getAuthToken();
                console.log('=== LOADING REGULATIONS ===');

                // Load regulation types first for lookup
                if (!regulationTypeList || regulationTypeList.length === 0) {
                    await loadRegulationTypes(false);
                }

                const url = `${baseUrl}/api/admin/regulation`;
                const res = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!res.ok) throw new Error(`Gagal fetch peraturan (${res.status})`);

                const data = await res.json();
                regulationList = Array.isArray(data) ? data : (data.data || []);
                console.log('Loaded regulations:', regulationList.length);

                renderRegulationList();
            } catch (err) {
                console.error('Error loading regulations:', err);
                showAlert('Gagal memuat peraturan: ' + err.message, 'error');
                regulationList = [];
            }
        }

        function renderRegulationList() {
            const container = document.getElementById('regulationListContainer');
            if (!container) return;

            if (!regulationList || regulationList.length === 0) {
                container.innerHTML =
                    '<div style="padding:2rem;text-align:center;color:#9ca3af;font-size:1.1rem;">Belum ada peraturan. Klik "Tambah Peraturan" untuk menambahkan.</div>';
                return;
            }

            container.innerHTML = `<table id="regulationTable" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th>Judul</th>
                        <th>Deskripsi</th>
                        <th>Tipe</th>
                        <th>File</th>
                        <th>Turunan</th>
                        <th>Tanggal</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                ${regulationList.map(regulation => {
                    const regulationId = String(regulation.id).trim();
                    const createdDate = regulation.createdAt ? new Date(regulation.createdAt).toLocaleDateString('id-ID') : 'N/A';
                    
                    // Get type name
                    let typeName = 'N/A';
                    if (regulation.type?.name) {
                        typeName = regulation.type.name;
                    } else if (regulation.type_id && regulationTypeList.length > 0) {
                        const foundType = regulationTypeList.find(t => t.id == regulation.type_id);
                        typeName = foundType ? foundType.name : 'N/A';
                    }
                    
                    // Show file link with filename when available
                    let fileTag = '<span style="color:#9ca3af;">No File</span>';
                    if (regulation.path_file) {
                        // Try to extract filename from path
                        const parts = String(regulation.path_file).split('/');
                        const filename = parts.length ? parts[parts.length - 1] : regulation.path_file;
                        fileTag = '<a href="' + baseUrl + '/' + regulation.path_file + '" target="_blank" style="color:#22c1b6;"><i class="fas fa-file-pdf"></i> ' + filename + '</a>';
                    }
                    
                    const inheritedBg = regulation.is_inherited ? '#d1fae5' : '#fee2e2';
                    const inheritedColor = regulation.is_inherited ? '#065f46' : '#991b1b';
                    const inheritedText = regulation.is_inherited ? 'Ya' : 'Tidak';
                    
                    return '<tr><td style="font-weight:600;text-align:left;">' + (regulation.title || 'No Title') + '</td><td style="text-align:left;color:#6b7280;">' + (regulation.description || '-') + '</td><td>' + typeName + '</td><td>' + fileTag + '</td><td><span class="badge" style="background:' + inheritedBg + ';color:' + inheritedColor + ';">' + inheritedText + '</span></td><td>' + createdDate + '</td><td><button class="btn-primary" style="padding:6px 16px;font-size:0.9rem;margin-right:6px;" onclick="openEditRegulationModal(\'' + regulationId + '\')"><i class="fas fa-edit"></i> Edit</button><button class="btn-danger" style="padding:6px 16px;font-size:0.9rem;" onclick="deleteRegulation(\'' + regulationId + '\')"><i class="fas fa-trash"></i> Hapus</button></td></tr>';
                }).join('')}
                </tbody>
            </table>`;

            if (window.$ && window.$.fn.dataTable) {
                $('#regulationTable').DataTable({
                    order: [
                        [4, "desc"]
                    ],
                    pageLength: 10,
                    language: {
                        search: "Cari:",
                        lengthMenu: "Tampilkan _MENU_ data per halaman",
                        info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        paginate: {
                            first: "Pertama",
                            last: "Terakhir",
                            next: "Selanjutnya",
                            previous: "Sebelumnya"
                        }
                    }
                });
            }
        }

        async function openAddRegulationModal() {
            try {
                console.log('=== OPENING ADD REGULATION MODAL ===');

                // Load regulation types first
                console.log('Loading regulation types...');
                await loadRegulationTypes(false);
                console.log('Regulation types loaded:', regulationTypeList);

                // Reset form
                document.getElementById('regulationForm').reset();
                document.getElementById('regulation_id').value = '';
                document.getElementById('regulationModalTitle').textContent = 'Tambah Peraturan';

                // Show modal
                document.getElementById('regulationModal').style.display = 'flex';

                // Wait for modal to render
                await new Promise(resolve => setTimeout(resolve, 150));

                // Populate dropdown
                console.log('Populating dropdown...');
                populateRegulationTypeDropdown();

                // Verify dropdown
                const dropdown = document.getElementById('regulation_type_id');
                console.log('Dropdown after populate:', {
                    exists: !!dropdown,
                    optionsCount: dropdown ? dropdown.options.length : 0,
                    disabled: dropdown ? dropdown.disabled : 'N/A',
                    display: dropdown ? dropdown.style.display : 'N/A'
                });
            } catch (error) {
                console.error('Error opening add modal:', error);
                showAlert('Gagal memuat form: ' + error.message, 'error');
            }
        }

        async function openEditRegulationModal(id) {
            try {
                const regulation = regulationList.find(r => r.id == id);
                if (!regulation) {
                    showAlert('Peraturan tidak ditemukan', 'error');
                    return;
                }

                await loadRegulationTypes(false);

                document.getElementById('regulation_id').value = regulation.id;
                document.getElementById('regulation_title').value = regulation.title;
                document.getElementById('regulation_description').value = regulation.description || '';
                document.getElementById('regulation_inherited').checked = regulation.is_inherited;

                populateRegulationTypeDropdown();
                document.getElementById('regulation_type_id').value = regulation.type_id || '';

                document.getElementById('regulationModalTitle').textContent = 'Edit Peraturan';
                document.getElementById('regulationModal').style.display = 'flex';
            } catch (error) {
                console.error('Error opening edit modal:', error);
                showAlert('Gagal memuat form edit: ' + error.message, 'error');
            }
        }

        function populateRegulationTypeDropdown() {
            console.log('=== POPULATING REGULATION TYPE DROPDOWN ===');
            const dropdown = document.getElementById('regulation_type_id');
            if (!dropdown) {
                console.error('Dropdown element not found!');
                return;
            }

            console.log('Regulation type list:', regulationTypeList);
            dropdown.innerHTML = '<option value="">Pilih tipe peraturan</option>';

            if (regulationTypeList && regulationTypeList.length > 0) {
                console.log('Adding ' + regulationTypeList.length + ' types to dropdown');
                regulationTypeList.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type.id;
                    option.textContent = type.name;
                    dropdown.appendChild(option);
                    console.log('Added type:', type.name, 'ID:', type.id);
                });
            } else {
                console.warn('No regulation types available');
            }

            dropdown.disabled = false;
            dropdown.style.display = 'block';
            dropdown.style.visibility = 'visible';
            console.log('Dropdown populated, total options:', dropdown.options.length);
        }

        function closeRegulationModal() {
            document.getElementById('regulationModal').style.display = 'none';
        }

        document.getElementById('regulationForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const id = document.getElementById('regulation_id').value;
            const title = document.getElementById('regulation_title').value.trim();
            const description = document.getElementById('regulation_description').value.trim();
            const typeId = document.getElementById('regulation_type_id').value;
            const isInherited = document.getElementById('regulation_inherited').checked;
            const fileInput = document.getElementById('regulation_file');
            const token = getAuthToken();

            if (!title || !typeId) {
                showAlert('Judul dan tipe peraturan harus diisi!', 'error');
                return;
            }

            // Validasi file wajib untuk data baru
            if (!id && (!fileInput.files || !fileInput.files[0])) {
                showAlert('File peraturan wajib diupload!', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('title', title);
            formData.append('description', description);
            formData.append('type_id', typeId);
            formData.append('is_inherited', isInherited ? 1 : 0);

            console.log('=== FORM DATA BEFORE SUBMIT ===');
            console.log('Title:', title);
            console.log('Type ID:', typeId);
            console.log('Is Inherited:', isInherited ? 1 : 0);
            console.log('File input:', fileInput);
            console.log('Has file:', fileInput && fileInput.files && fileInput.files[0]);

            if (fileInput && fileInput.files && fileInput.files[0]) {
                const file = fileInput.files[0];
                console.log('File details:', {
                    name: file.name,
                    size: file.size,
                    type: file.type
                });
                formData.append('regulation_file', file);
            }

            try {
                let url = `${baseUrl}/api/admin/regulation`;
                let method = 'POST';
                if (id) {
                    url += `/${id}`;
                    method = 'PUT';
                }

                console.log('Submitting to:', url, 'Method:', method);

                const res = await fetch(url, {
                    method,
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    body: formData
                });

                console.log('Response status:', res.status);

                if (res.ok) {
                    showAlert('Peraturan berhasil disimpan!', 'success');
                    closeRegulationModal();
                    loadRegulations();
                } else {
                    const clonedResponse = res.clone();
                    let errorMessage = 'Unknown error';
                    try {
                        const errorJson = await res.json();
                        console.error('Error JSON:', errorJson);
                        errorMessage = errorJson.message || errorJson.error || JSON.stringify(errorJson);
                    } catch {
                        const errorText = await clonedResponse.text();
                        console.error('Error Text:', errorText);
                        errorMessage = errorText.substring(0, 500);
                    }
                    console.error('Full error message:', errorMessage);
                    showAlert(`Gagal simpan data (${res.status}): ${errorMessage}`, 'error');
                }
            } catch (err) {
                console.error('Fetch error:', err);
                showAlert('Gagal simpan: ' + err.message, 'error');
            }
        });

        async function deleteRegulation(id) {
            if (!confirm('Yakin ingin menghapus peraturan ini?')) return;

            const token = getAuthToken();
            const url = `${baseUrl}/api/admin/regulation/${id}`;

            try {
                const res = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (res.ok) {
                    showAlert('Peraturan berhasil dihapus!', 'success');
                    loadRegulations();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal hapus data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal hapus: ' + err.message, 'error');
            }
        }

        // Regulation Type Functions
        async function loadRegulationTypes(renderList = true) {
            if (renderList && !checkSuperadminAccess('melihat tipe peraturan')) return;

            try {
                const token = getAuthToken();
                console.log('=== LOADING REGULATION TYPES ===');
                console.log('API URL:', `${baseUrl}/api/admin/regulation-type`);
                const url = `${baseUrl}/api/admin/regulation-type`;
                const res = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                console.log('Response status:', res.status);
                if (!res.ok) {
                    const errorText = await res.text();
                    console.error('API Error:', errorText);
                    throw new Error(`Gagal fetch tipe peraturan (${res.status}): ${errorText}`);
                }

                const data = await res.json();
                console.log('Raw API response:', data);
                regulationTypeList = Array.isArray(data) ? data : (data.data || []);
                console.log('Loaded regulation types:', regulationTypeList.length, regulationTypeList);

                if (renderList) renderRegulationTypeList();
                return regulationTypeList;
            } catch (err) {
                console.error('Error loading regulation types:', err);
                showAlert('Gagal memuat tipe peraturan: ' + err.message, 'error');
                regulationTypeList = [];
                throw err;
            }
        }

        function renderRegulationTypeList() {
            const container = document.getElementById('regulationTypeListContainer');
            if (!container) return;

            if (!regulationTypeList || regulationTypeList.length === 0) {
                container.innerHTML =
                    '<div style="padding:2rem;text-align:center;color:#9ca3af;font-size:1.1rem;">Belum ada tipe peraturan. Klik "Tambah Tipe Peraturan" untuk menambahkan.</div>';
                return;
            }

            container.innerHTML = `<table id="regulationTypeTable" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th>Nama</th>
                        <th>Deskripsi</th>
                        <th>Tanggal Dibuat</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                ${regulationTypeList.map(type => {
                    const typeId = String(type.id).trim();
                    const createdDate = type.createdAt ? new Date(type.createdAt).toLocaleDateString('id-ID') : 'N/A';
                    return '<tr><td style="font-weight:600;text-align:left;">' + (type.name || 'No Name') + '</td><td style="text-align:left;">' + (type.description || 'No Description') + '</td><td>' + createdDate + '</td><td><button class="btn-primary" style="padding:6px 16px;font-size:0.9rem;margin-right:6px;" onclick="openEditRegulationTypeModal(\'' + typeId + '\')"><i class="fas fa-edit"></i> Edit</button><button class="btn-danger" style="padding:6px 16px;font-size:0.9rem;" onclick="deleteRegulationType(\'' + typeId + '\')"><i class="fas fa-trash"></i> Hapus</button></td></tr>';
                }).join('')}
                </tbody>
            </table>`;

            if (window.$ && window.$.fn.dataTable) {
                $('#regulationTypeTable').DataTable({
                    order: [
                        [2, "desc"]
                    ],
                    pageLength: 10,
                    language: {
                        search: "Cari:",
                        lengthMenu: "Tampilkan _MENU_ data per halaman",
                        info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        paginate: {
                            first: "Pertama",
                            last: "Terakhir",
                            next: "Selanjutnya",
                            previous: "Sebelumnya"
                        }
                    }
                });
            }
        }

        function openAddRegulationTypeModal() {
            if (!checkSuperadminAccess('menambah tipe peraturan')) return;

            document.getElementById('regulationTypeForm').reset();
            document.getElementById('regulationType_id').value = '';
            document.getElementById('regulationTypeModalTitle').textContent = 'Tambah Tipe Peraturan';
            document.getElementById('regulationTypeModal').style.display = 'flex';
        }

        function openEditRegulationTypeModal(id) {
            if (!checkSuperadminAccess('mengedit tipe peraturan')) return;

            const regulationType = regulationTypeList.find(t => t.id == id);
            if (!regulationType) {
                showAlert('Tipe peraturan tidak ditemukan', 'error');
                return;
            }

            document.getElementById('regulationType_id').value = regulationType.id;
            document.getElementById('regulationType_name').value = regulationType.name;
            document.getElementById('regulationType_description').value = regulationType.description || '';
            document.getElementById('regulationTypeModalTitle').textContent = 'Edit Tipe Peraturan';
            document.getElementById('regulationTypeModal').style.display = 'flex';
        }

        function closeRegulationTypeModal() {
            document.getElementById('regulationTypeModal').style.display = 'none';
        }

        document.getElementById('regulationTypeForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            if (!checkSuperadminAccess('menyimpan tipe peraturan')) return;

            const id = document.getElementById('regulationType_id').value;
            const name = document.getElementById('regulationType_name').value.trim();
            const description = document.getElementById('regulationType_description').value.trim();
            const token = getAuthToken();

            if (!name) {
                showAlert('Nama tipe peraturan harus diisi!', 'error');
                return;
            }

            const formData = {
                name,
                description
            };

            try {
                let url = `${baseUrl}/api/admin/regulation-type`;
                let method = 'POST';
                if (id) {
                    url += `/${id}`;
                    method = 'PUT';
                }
                const res = await fetch(url, {
                    method,
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                if (res.ok) {
                    showAlert('Tipe peraturan berhasil disimpan!', 'success');
                    closeRegulationTypeModal();
                    loadRegulationTypes();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal simpan data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal simpan: ' + err.message, 'error');
            }
        });

        async function deleteRegulationType(id) {
            if (!checkSuperadminAccess('menghapus tipe peraturan')) return;
            if (!confirm('Yakin ingin menghapus tipe peraturan ini?')) return;

            const token = getAuthToken();
            const url = `${baseUrl}/api/admin/regulation-type/${id}`;

            try {
                const res = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (res.ok) {
                    showAlert('Tipe peraturan berhasil dihapus!', 'success');
                    loadRegulationTypes();
                } else {
                    const errorData = await res.text();
                    showAlert('Gagal hapus data: ' + errorData, 'error');
                }
            } catch (err) {
                showAlert('Gagal hapus: ' + err.message, 'error');
            }
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const regulationModal = document.getElementById('regulationModal');
            const regulationTypeModal = document.getElementById('regulationTypeModal');
            if (event.target === regulationModal) closeRegulationModal();
            if (event.target === regulationTypeModal) closeRegulationTypeModal();
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('=== PAGE INITIALIZATION ===');
            if (!window.$) {
                const scriptJq = document.createElement('script');
                scriptJq.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
                scriptJq.onload = () => {
                    const scriptDt = document.createElement('script');
                    scriptDt.src = 'https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js';
                    scriptDt.onload = () => loadRegulations();
                    document.body.appendChild(scriptDt);
                };
                document.body.appendChild(scriptJq);
            } else {
                loadRegulations();
            }
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\daerah\resources\views/admin/peraturanAdmin.blade.php ENDPATH**/ ?>