

<?php $__env->startSection('backend_content'); ?>
    <?php $__env->startPush('backend_css'); ?>
        <style>
            /* ── Avatar ── */
            .avatar {
                width: 38px;
                height: 38px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: 700;
                font-size: 13px;
                flex-shrink: 0;
            }

            /* ── Row hover ── */
            .hover-shadow:hover {
                background: #f5f8ff;
                transition: background 0.2s;
            }

            /* ── Toaster ── */
            #toaster-container {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                display: flex;
                flex-direction: column;
                gap: 10px;
                pointer-events: none;
            }

            .toast-msg {
                display: flex;
                align-items: center;
                gap: 12px;
                min-width: 300px;
                max-width: 380px;
                padding: 14px 18px;
                border-radius: 10px;
                color: #fff;
                font-size: 14px;
                font-weight: 500;
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
                pointer-events: all;
                animation: slideIn 0.35s ease forwards;
                position: relative;
                overflow: hidden;
            }

            .toast-msg::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 0;
                height: 3px;
                background: rgba(255, 255, 255, 0.4);
                animation: progress 3.5s linear forwards;
            }

            .toast-msg.toast-success {
                background: #1a7f5a;
            }

            .toast-msg.toast-error {
                background: #c0392b;
            }

            .toast-msg.toast-warning {
                background: #d68910;
            }

            .toast-msg .toast-icon {
                font-size: 20px;
            }

            .toast-msg .toast-close {
                margin-left: auto;
                cursor: pointer;
                opacity: 0.75;
                font-size: 18px;
                line-height: 1;
                background: none;
                border: none;
                color: #fff;
                padding: 0;
            }

            .toast-msg .toast-close:hover {
                opacity: 1;
            }

            @keyframes slideIn {
                from {
                    transform: translateX(120%);
                    opacity: 0;
                }

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

            @keyframes slideOut {
                from {
                    transform: translateX(0);
                    opacity: 1;
                }

                to {
                    transform: translateX(120%);
                    opacity: 0;
                }
            }

            @keyframes progress {
                from {
                    width: 100%;
                }

                to {
                    width: 0%;
                }
            }

            /* ── Confirm Delete overlay ── */
            #deleteConfirmOverlay {
                display: none;
                position: fixed;
                inset: 0;
                background: rgba(0, 0, 0, 0.45);
                z-index: 1060;
                align-items: center;
                justify-content: center;
            }

            #deleteConfirmOverlay.show {
                display: flex;
            }

            #deleteConfirmBox {
                background: #fff;
                border-radius: 14px;
                padding: 30px 32px;
                max-width: 380px;
                width: 90%;
                text-align: center;
                box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
                animation: popIn 0.25s ease;
            }

            @keyframes popIn {
                from {
                    transform: scale(0.85);
                    opacity: 0;
                }

                to {
                    transform: scale(1);
                    opacity: 1;
                }
            }

            #deleteConfirmBox .del-icon {
                font-size: 48px;
                color: #e74c3c;
                margin-bottom: 12px;
            }

            /* ── Spinner ── */
            .btn-spinner {
                width: 16px;
                height: 16px;
                border: 2px solid rgba(255, 255, 255, 0.4);
                border-top-color: #fff;
                border-radius: 50%;
                animation: spin 0.6s linear infinite;
                display: inline-block;
            }

            @keyframes spin {
                to {
                    transform: rotate(360deg);
                }
            }

            /* ── Permissions Modal ── */
            .permission-group {
                margin-bottom: 24px;
                border-radius: 12px;
                overflow: hidden;
                border: 1px solid #e0e6ed;
                background: #fff;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            }

            .permission-group-header {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 16px 18px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                font-weight: 600;
                font-size: 14px;
                cursor: pointer;
                user-select: none;
                transition: all 0.2s;
            }

            .permission-group-header:hover {
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            }

            .permission-group-header.collapsed {
                background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);
                color: #495057;
                border-bottom: 1px solid #e0e6ed;
            }

            .permission-group-header i {
                font-size: 18px;
            }

            .permission-group-header i:last-child {
                margin-left: auto;
                transition: transform 0.3s;
            }

            .permission-group-header.collapsed i:last-child {
                transform: rotate(-90deg);
            }

            .permission-group-content {
                padding: 20px;
                background: #fafbfc;
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
                gap: 12px;
            }

            .permission-item {
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 12px 14px;
                border-radius: 8px;
                background: white;
                border: 1.5px solid #d5dce0;
                cursor: pointer;
                transition: all 0.2s ease;
                position: relative;
            }

            .permission-item:hover {
                border-color: #667eea;
                background: linear-gradient(135deg, #f0f4ff 0%, #fafbff 100%);
                box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
            }

            .permission-item input[type="checkbox"] {
                cursor: pointer;
                width: 18px;
                height: 18px;
                accent-color: #667eea;
                flex-shrink: 0;
            }

            .permission-item input[type="checkbox"]:checked+label {
                color: #667eea;
                font-weight: 600;
            }

            .permission-item label {
                flex: 1;
                margin: 0;
                cursor: pointer;
                color: #495057;
                text-transform: capitalize;
                font-size: 13px;
                font-weight: 500;
                letter-spacing: 0.3px;
            }

            /* Permission Summary */
            .permission-summary {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 18px;
                background: linear-gradient(135deg, #f0f4ff 0%, #fafbff 100%);
                border: 1.5px solid #e0e6ed;
                border-radius: 10px;
                margin-bottom: 20px;
            }

            .permission-summary-label {
                font-weight: 600;
                color: #495057;
                font-size: 14px;
                letter-spacing: 0.3px;
            }

            .permission-count {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 8px 16px;
                border-radius: 20px;
                font-size: 13px;
                font-weight: 700;
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                letter-spacing: 0.5px;
                transition: transform 0.15s ease-out;
                transform-origin: center;
            }

            .permission-count i {
                font-size: 16px;
            }

            /* Buttons */
            .permission-actions {
                display: flex;
                gap: 10px;
                margin-bottom: 20px;
            }

            .permission-actions button {
                flex: 1;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: 0.3px;
                transition: all 0.2s;
                border-radius: 8px;
            }

            .permission-actions .btn-outline-primary:hover {
                background: #667eea;
                border-color: #667eea;
                color: white;
            }

            .permission-actions .btn-outline-secondary:hover {
                background: #6c757d;
                border-color: #6c757d;
                color: white;
            }

            /* Modal Header & Footer */
            .permissions-modal-header {
                display: flex;
                flex-direction: column;
                gap: 6px;
            }

            .permissions-modal-header h5 {
                font-size: 18px;
                font-weight: 700;
                letter-spacing: 0.3px;
                color: #2c3e50;
            }

            .permissions-modal-header .text-muted {
                font-size: 13px;
                font-weight: 500;
                letter-spacing: 0.2px;
            }

            /* Empty State */
            .permissions-empty {
                text-align: center;
                padding: 40px 20px;
            }

            .permissions-empty i {
                font-size: 48px;
                color: #cbd5e0;
                margin-bottom: 12px;
            }
        </style>
        </style>
        </style>
    <?php $__env->stopPush(); ?>

    
    <div id="toaster-container"></div>

    
    <div id="deleteConfirmOverlay">
        <div id="deleteConfirmBox">
            <div class="del-icon"><i class="bx bxs-trash-alt"></i></div>
            <h5 class="fw-bold mb-1">Delete Role?</h5>
            <p class="text-muted small mb-4">This action cannot be undone. The role will be permanently removed.</p>
            <div class="d-flex gap-2 justify-content-center">
                <button class="btn btn-light px-4" id="cancelDeleteBtn">Cancel</button>
                <button class="btn btn-danger px-4" id="confirmDeleteBtn">
                    <span id="deleteSpinner" class="btn-spinner d-none me-1"></span>
                    Yes, Delete
                </button>
            </div>
        </div>
    </div>

    <div class="container-fluid">

        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="fw-bold mb-1">Role Management</h4>
                <small class="text-muted">Manage roles and their permissions</small>
            </div>
            <div class="d-flex gap-2">
                <input type="text" id="searchInput" class="form-control" placeholder="Search role..."
                    style="width:220px;">
                <button class="btn btn-primary" id="addRoleBtn" data-bs-toggle="modal" data-bs-target="#roleModal">
                    <i class="bx bx-plus"></i> Add Role
                </button>
            </div>
        </div>

        
        <div class="card border-0 shadow-sm">
            <div class="card-body table-responsive p-0">
                <table class="table align-middle mb-0" id="rolesTable">
                    <thead class="table-light">
                        <tr>
                            <th>Role</th>
                            <th>Permissions</th>
                            <th>Users</th>
                            <th>Status</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody id="rolesBody">
                        <?php $__empty_1 = true; $__currentLoopData = $roles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <?php echo $__env->make('backend.roles_permissions._row', ['role' => $role], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr id="emptyRow">
                                <td colspan="5" class="text-center text-muted py-4">
                                    <i class="bx bx-info-circle fs-3"></i>
                                    <div class="mt-2">No roles found. Please add a role.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

    
    <div class="modal fade" id="roleModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow">

                <div class="modal-header border-0 pb-0">
                    <h5 class="modal-title fw-bold" id="modalTitle">Create Role</h5>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body pt-3">
                    <input type="hidden" id="roleId">

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Role Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="roleName" placeholder="e.g. Admin">
                        <div class="invalid-feedback" id="nameError"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Status</label>
                        <select class="form-select" id="roleStatus">
                            <option value="1" selected>Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                </div>

                <div class="modal-footer border-0 pt-0">
                    <button class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-primary px-4" id="saveRoleBtn">
                        <span id="saveSpinner" class="btn-spinner d-none me-1"></span>
                        <span id="saveBtnText">Save Role</span>
                    </button>
                </div>

            </div>
        </div>
    </div>

    
    <div class="modal fade" id="permissionsModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content border-0 shadow-lg">

                <div class="modal-header border-0 pb-3"
                    style="background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);">
                    <div class="permissions-modal-header">
                        <h5 id="permModalTitle">Configure Role Permissions</h5>
                        <small class="text-muted">Select permissions to assign to this role</small>
                    </div>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body pt-4">
                    <input type="hidden" id="permRoleId">

                    
                    <div class="permission-summary">
                        <span class="permission-summary-label">
                            <i class="bx bx-check-double" style="font-size: 16px; margin-right: 6px;"></i>
                            Permissions Selected
                        </span>
                        <span class="permission-count">
                            <i class="bx bx-check-circle"></i>
                            <span id="permissionCountBadge">0</span>
                        </span>
                    </div>

                    
                    <div class="permission-actions">
                        <button class="btn btn-outline-primary btn-sm" id="selectAllPermsBtn">
                            <i class="bx bx-check-double me-1"></i>Select All
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" id="deselectAllPermsBtn">
                            <i class="bx bx-x-circle me-1"></i>Clear All
                        </button>
                    </div>

                    
                    <div id="permissionsContainer"></div>
                </div>

                <div class="modal-footer border-0 pt-3" style="background: #f8f9fa;">
                    <button class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-primary px-5" id="savePermissionsBtn"
                        style="font-weight: 600; letter-spacing: 0.3px;">
                        <span id="permSpinner" class="btn-spinner d-none me-2"></span>
                        <i class="bx bx-check me-1"></i>Save Permissions
                    </button>
                </div>

            </div>
        </div>
    </div>

    
    <div class="modal fade" id="usersModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content border-0 shadow-lg">

                <div class="modal-header border-0 pb-3"
                    style="background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);">
                    <div class="permissions-modal-header">
                        <h5 id="userModalTitle">Assign Users to Role</h5>
                        <small class="text-muted">Select users to assign to this role</small>
                    </div>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body pt-4">
                    <input type="hidden" id="userRoleId">

                    
                    <div class="permission-summary">
                        <span class="permission-summary-label">
                            <i class="bx bx-user" style="font-size: 16px; margin-right: 6px;"></i>
                            Users Selected
                        </span>
                        <span class="permission-count">
                            <i class="bx bx-user-check"></i>
                            <span id="userCountBadge">0</span>
                        </span>
                    </div>

                    
                    <div class="permission-actions">
                        <button class="btn btn-outline-primary btn-sm" id="selectAllUsersBtn">
                            <i class="bx bx-check-double me-1"></i>Select All
                        </button>
                        <button class="btn btn-outline-secondary btn-sm" id="deselectAllUsersBtn">
                            <i class="bx bx-x-circle me-1"></i>Clear All
                        </button>
                    </div>

                    
                    <div class="mb-3">
                        <div class="input-group">
                            <span class="input-group-text"><i class="bx bx-search"></i></span>
                            <input type="text" class="form-control" id="userSearchInput"
                                placeholder="Search users by name or email...">
                        </div>
                    </div>

                    
                    <div id="usersContainer"></div>
                </div>

                <div class="modal-footer border-0 pt-3" style="background: #f8f9fa;">
                    <button class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-primary px-5" id="saveUsersBtn"
                        style="font-weight: 600; letter-spacing: 0.3px;">
                        <span id="userSpinner" class="btn-spinner d-none me-2"></span>
                        <i class="bx bx-check me-1"></i>Save Users
                    </button>
                </div>

            </div>
        </div>
    </div>

    <?php $__env->startPush('backend_js'); ?>
        <script>
            (function() {

                /* ═══════════════════════════
                   CSRF helper
                ═══════════════════════════ */
                const csrf = () => document.querySelector('meta[name="csrf-token"]')?.content ?? '';

                /* ═══════════════════════════
                   Routes (generated by Laravel)
                ═══════════════════════════ */
                const routes = {
                    store: "<?php echo e(route('admin.roles-permissions.store')); ?>",
                    edit: (id) => `/admin/roles-permissions/${id}/edit`,
                    update: (id) => `/admin/roles-permissions/${id}/update`,
                    destroy: (id) => `/admin/roles-permissions/${id}/destroy`,
                    permissions: (id) => `/admin/roles-permissions/${id}/permissions`,
                    assignPermissions: (id) => `/admin/roles-permissions/${id}/assign-permissions`,
                    users: (id) => `/admin/roles-permissions/${id}/users`,
                    assignUsers: (id) => `/admin/roles-permissions/${id}/assign-users`,
                };

                /* ═══════════════════════════
                   Toaster
                ═══════════════════════════ */
                function toast(message, type = 'success') {
                    const icons = {
                        success: 'bx-check-circle',
                        error: 'bxs-x-circle',
                        warning: 'bxs-error'
                    };
                    const container = document.getElementById('toaster-container');

                    const el = document.createElement('div');
                    el.className = `toast-msg toast-${type}`;
                    el.innerHTML = `
                    <i class="bx ${icons[type] ?? icons.success} toast-icon"></i>
                    <span>${message}</span>
                    <button class="toast-close" aria-label="close">&times;</button>
                `;

                    el.querySelector('.toast-close').addEventListener('click', () => removeToast(el));
                    container.appendChild(el);

                    setTimeout(() => removeToast(el), 3600);
                }

                function removeToast(el) {
                    el.style.animation = 'slideOut 0.3s ease forwards';
                    setTimeout(() => el.remove(), 300);
                }

                /* ═══════════════════════════
                   Modal helpers
                ═══════════════════════════ */
                const modal = document.getElementById('roleModal');
                const bsModal = new bootstrap.Modal(modal);
                const modalTitle = document.getElementById('modalTitle');
                const roleIdInput = document.getElementById('roleId');
                const roleNameIn = document.getElementById('roleName');
                const roleStatus = document.getElementById('roleStatus');
                const nameError = document.getElementById('nameError');
                const saveBtn = document.getElementById('saveRoleBtn');
                const saveSpinner = document.getElementById('saveSpinner');
                const saveBtnTxt = document.getElementById('saveBtnText');

                const permModal = document.getElementById('permissionsModal');
                const bsPermModal = new bootstrap.Modal(permModal);
                const permRoleId = document.getElementById('permRoleId');
                const savePermBtn = document.getElementById('savePermissionsBtn');
                const permSpinner = document.getElementById('permSpinner');

                const userModal = document.getElementById('usersModal');
                const bsUserModal = new bootstrap.Modal(userModal);
                const userRoleId = document.getElementById('userRoleId');
                const saveUserBtn = document.getElementById('saveUsersBtn');
                const userSpinner = document.getElementById('userSpinner');

                let cachedUsers = [];
                let selectedUserIds = new Set();

                function resetModal() {
                    roleIdInput.value = '';
                    roleNameIn.value = '';
                    roleStatus.value = '1';
                    roleNameIn.classList.remove('is-invalid');
                    nameError.textContent = '';
                    modalTitle.textContent = 'Create Role';
                    saveBtnTxt.textContent = 'Save Role';
                }

                document.getElementById('addRoleBtn').addEventListener('click', resetModal);

                modal.addEventListener('hidden.bs.modal', resetModal);

                function setLoading(flag) {
                    saveBtn.disabled = flag;
                    saveSpinner.classList.toggle('d-none', !flag);
                }

                function setPermLoading(flag) {
                    savePermBtn.disabled = flag;
                    permSpinner.classList.toggle('d-none', !flag);
                }

                function setUserLoading(flag) {
                    saveUserBtn.disabled = flag;
                    userSpinner.classList.toggle('d-none', !flag);
                }

                // Reset permissions modal when closed
                permModal.addEventListener('hidden.bs.modal', function() {
                    document.getElementById('permissionsContainer').innerHTML = '';
                    document.getElementById('permissionCountBadge').textContent = '0';
                });

                // Reset users modal when closed
                userModal.addEventListener('hidden.bs.modal', function() {
                    document.getElementById('usersContainer').innerHTML = '';
                    document.getElementById('userCountBadge').textContent = '0';
                    document.getElementById('userSearchInput').value = '';
                    cachedUsers = [];
                    selectedUserIds.clear();
                });

                /* ═══════════════════════════
                   Avatar helper (mirrors PHP)
                ═══════════════════════════ */
                const COLORS = ['bg-primary', 'bg-info', 'bg-success', 'bg-warning', 'bg-danger', 'bg-secondary'];

                function avatarColor(name) {
                    let hash = 0;
                    for (let i = 0; i < name.length; i++) hash = (Math.imul(31, hash) + name.charCodeAt(i)) | 0;
                    let idx = Math.abs(hash) % COLORS.length;
                    return COLORS[idx];
                }

                function normalizeRoleName(name) {
                    return name.trim().toLowerCase().replace(/\s+/g, '-').replace(/_+/g, '-');
                }

                function isProtectedRole(role) {
                    const protectedNames = ['super-admin', 'superadmin'];
                    return protectedNames.includes(normalizeRoleName(role.name));
                }

                function buildRow(role) {
                    const initials = role.name.substring(0, 2).toUpperCase();
                    const color = avatarColor(role.name);
                    const badge = role.status == 1 ?
                        '<span class="badge bg-info text-white">Active</span>' :
                        '<span class="badge bg-danger text-white">Inactive</span>';
                    const protectedRole = isProtectedRole(role);

                    return `
                <tr class="hover-shadow" data-id="${role.id}">
                    <td>
                        <div class="d-flex align-items-center gap-2">
                            <div class="avatar ${color} text-white">${initials}</div>
                            <div class="fw-semibold role-name">${role.name}</div>
                        </div>
                    </td>
                    <td><span class="badge bg-light text-dark permissions-count">0 Permissions</span></td>
                    <td><span class="badge bg-light text-dark users-count">0 Users</span></td>
                    <td>${badge}</td>
                    <td class="text-end">
                        <div class="dropdown">
                            <i class="bx bx-dots-vertical-rounded" data-bs-toggle="dropdown" style="cursor:pointer;"></i>
                            <ul class="dropdown-menu dropdown-menu-end">
                                ${protectedRole ? `
                                                                                                                                                                                            <li>
                                                                                                                                                                                                <span class="dropdown-item disabled">
                                                                                                                                                                                                    <i class="bx bx-lock me-2"></i>Protected
                                                                                                                                                                                                </span>
                                                                                                                                                                                            </li>
                                                                                                                                                                                        ` : `
                                                                                                                                                                                            <li><a class="dropdown-item user-btn" href="#" data-id="${role.id}">
                                                                                                                                                                                                <i class="bx bx-user me-2"></i>Users
                                                                                                                                                                                            </a></li>
                                                                                                                                                                                            <li><a class="dropdown-item perm-btn" href="#" data-id="${role.id}">
                                                                                                                                                                                                <i class="bx bx-key me-2"></i>Permissions
                                                                                                                                                                                            </a></li>
                                                                                                                                                                                            <li><a class="dropdown-item edit-btn" href="#" data-id="${role.id}">
                                                                                                                                                                                                <i class="bx bx-edit me-2"></i>Edit
                                                                                                                                                                                            </a></li>
                                                                                                                                                                                            <li><a class="dropdown-item text-danger delete-btn" href="#" data-id="${role.id}">
                                                                                                                                                                                                <i class="bx bx-trash me-2"></i>Delete
                                                                                                                                                                                            </a></li>
                                                                                                                                                                                        `}
                            </ul>
                        </div>
                    </td>
                </tr>`;
                }

                /* ═══════════════════════════
                   STORE
                ═══════════════════════════ */
                document.getElementById('saveRoleBtn').addEventListener('click', async function() {
                    const id = roleIdInput.value;
                    const name = roleNameIn.value.trim();

                    if (!name) {
                        roleNameIn.classList.add('is-invalid');
                        nameError.textContent = 'Role name is required.';
                        return;
                    }
                    roleNameIn.classList.remove('is-invalid');

                    const isEdit = !!id;
                    const url = isEdit ? routes.update(id) : routes.store;
                    const method = isEdit ? 'PUT' : 'POST';

                    setLoading(true);

                    try {
                        const res = await fetch(url, {
                            method,
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': csrf(),
                                'Accept': 'application/json',
                            },
                            body: JSON.stringify({
                                name,
                                status: roleStatus.value
                            }),
                        });

                        const data = await res.json();

                        if (!res.ok) {
                            if (res.status === 422 && data.errors?.name) {
                                roleNameIn.classList.add('is-invalid');
                                nameError.textContent = data.errors.name[0];
                            } else {
                                toast(data.message ?? 'Something went wrong.', 'error');
                            }
                            return;
                        }

                        bsModal.hide();
                        toast(data.message, 'success');

                        if (isEdit) {
                            const row = document.querySelector(`tr[data-id="${id}"]`);
                            if (row) row.outerHTML = buildRow({
                                id,
                                name,
                                status: roleStatus.value
                            });
                        } else {
                            const body = document.getElementById('rolesBody');
                            const empty = document.getElementById('emptyRow');
                            if (empty) empty.remove();
                            body.insertAdjacentHTML('afterbegin', buildRow(data.role ?? {
                                id: Date.now(),
                                name,
                                status: roleStatus.value
                            }));
                        }

                    } catch (err) {
                        toast('Network error. Please try again.', 'error');
                    } finally {
                        setLoading(false);
                    }
                });

                /* ═══════════════════════════
                   EDIT  – fetch & fill modal
                ═══════════════════════════ */
                document.getElementById('rolesBody').addEventListener('click', async function(e) {
                    const editBtn = e.target.closest('.edit-btn');
                    if (!editBtn) return;
                    e.preventDefault();

                    const id = editBtn.dataset.id;

                    try {
                        const res = await fetch(routes.edit(id), {
                            headers: {
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrf()
                            },
                        });
                        const data = await res.json();

                        if (!res.ok || !data.success) {
                            toast('Could not load role.', 'error');
                            return;
                        }

                        roleIdInput.value = data.role.id;
                        roleNameIn.value = data.role.name;
                        roleStatus.value = data.role.status ? '1' : '0';
                        modalTitle.textContent = 'Edit Role';
                        saveBtnTxt.textContent = 'Update Role';

                        bsModal.show();

                    } catch {
                        toast('Network error.', 'error');
                    }
                });

                /* ═══════════════════════════
                   PERMISSIONS MODAL
                ═══════════════════════════ */
                document.getElementById('rolesBody').addEventListener('click', async function(e) {
                    const permBtn = e.target.closest('.perm-btn');
                    if (!permBtn) return;
                    e.preventDefault();

                    const roleId = permBtn.dataset.id;
                    permRoleId.value = roleId;

                    try {
                        const res = await fetch(routes.permissions(roleId), {
                            headers: {
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrf()
                            },
                        });
                        const data = await res.json();

                        if (!res.ok || !data.success) {
                            toast('Could not load permissions.', 'error');
                            return;
                        }

                        const container = document.getElementById('permissionsContainer');
                        container.innerHTML = '';

                        // Render all permissions in a flat list
                        const flatListHtml = `
                        <div class="permission-flat-list">
                            ${data.allPermissions.sort((a, b) => a.name.localeCompare(b.name)).map(perm => {
                                const isChecked = data.rolePermissions.includes(perm.id);
                                return `
                                                                                                                                                                                                    <div class="permission-item">
                                                                                                                                                                                                        <input type="checkbox" class="perm-checkbox" value="${perm.id}" id="perm_${perm.id}" ${isChecked ? 'checked' : ''}>
                                                                                                                                                                                                        <label for="perm_${perm.id}">${perm.name}</label>
                                                                                                                                                                                                    </div>
                                                                                                                                                                                                `;
                            }).join('')}
                        </div>
                    `;
                        container.insertAdjacentHTML('beforeend', flatListHtml);

                        // Attach event listeners to all checkboxes
                        container.querySelectorAll('.perm-checkbox').forEach(checkbox => {
                            checkbox.addEventListener('change', updatePermissionCount);
                        });

                        updatePermissionCount();
                        bsPermModal.show();
                    } catch {
                        toast('Network error.', 'error');
                    }
                });

                /* ═══════════════════════════
                   Permission Count Update
                ═══════════════════════════ */
                function updatePermissionCount() {
                    const checked = document.querySelectorAll('.perm-checkbox:checked').length;
                    const badge = document.getElementById('permissionCountBadge');
                    badge.textContent = checked;

                    // Add animation
                    badge.parentElement.style.transform = 'scale(1.05)';
                    setTimeout(() => {
                        badge.parentElement.style.transform = 'scale(1)';
                    }, 150);
                }

                /* ═══════════════════════════
                   Select/Deselect All
                ═══════════════════════════ */
                document.getElementById('selectAllPermsBtn').addEventListener('click', function() {
                    document.querySelectorAll('.perm-checkbox').forEach(cb => {
                        cb.checked = true;
                    });
                    updatePermissionCount();
                });

                document.getElementById('deselectAllPermsBtn').addEventListener('click', function() {
                    document.querySelectorAll('.perm-checkbox').forEach(cb => {
                        cb.checked = false;
                    });
                    updatePermissionCount();
                });

                /* ═══════════════════════════
                   SAVE PERMISSIONS
                ═══════════════════════════ */
                document.getElementById('savePermissionsBtn').addEventListener('click', async function() {
                    const roleId = permRoleId.value;
                    const permissions = Array.from(document.querySelectorAll('.perm-checkbox:checked')).map(
                        el => el.value);

                    setPermLoading(true);

                    try {
                        const res = await fetch(routes.assignPermissions(roleId), {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': csrf(),
                                'Accept': 'application/json',
                            },
                            body: JSON.stringify({
                                permissions
                            }),
                        });

                        const data = await res.json();

                        if (!res.ok) {
                            toast(data.message ?? 'Error saving permissions.', 'error');
                            return;
                        }

                        bsPermModal.hide();
                        toast(data.message, 'success');

                        // Update permissions count in table
                        const row = document.querySelector(`tr[data-id="${roleId}"]`);
                        if (row) {
                            row.querySelector('.permissions-count').textContent =
                                `${permissions.length} Permissions`;
                        }
                    } catch {
                        toast('Network error.', 'error');
                    } finally {
                        setPermLoading(false);
                    }
                });

                /* ═══════════════════════════
                   USERS MODAL
                ═══════════════════════════ */
                document.getElementById('rolesBody').addEventListener('click', async function(e) {
                    const userBtn = e.target.closest('.user-btn');
                    if (!userBtn) return;
                    e.preventDefault();

                    const roleId = userBtn.dataset.id;
                    userRoleId.value = roleId;
                    document.getElementById('userSearchInput').value = '';
                    await loadUsers(roleId);
                    bsUserModal.show();
                });

                async function loadUsers(roleId, search = '') {
                    try {
                        const params = new URLSearchParams();
                        if (search) params.append('search', search);
                        params.append('limit', '5');

                        const res = await fetch(`${routes.users(roleId)}?${params}`, {
                            headers: {
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrf()
                            },
                        });
                        const data = await res.json();

                        if (!res.ok || !data.success) {
                            toast('Could not load users.', 'error');
                            return;
                        }

                        cachedUsers = data.allUsers;
                        selectedUserIds = new Set(data.roleUsers);
                        renderUsers(cachedUsers);
                    } catch {
                        toast('Network error.', 'error');
                    }
                }

                function buildUserItem(user) {
                    const isChecked = selectedUserIds.has(user.id);
                    return `
                            <div class="permission-item">
                                <input type="checkbox" class="user-checkbox" value="${user.id}" id="user_${user.id}" ${isChecked ? 'checked' : ''}>
                                <label for="user_${user.id}">${user.name} (${user.email})</label>
                            </div>
                        `;
                }

                function renderUsers(users) {
                    const container = document.getElementById('usersContainer');
                    container.innerHTML = `
                            <div class="permission-flat-list">
                                ${users.map(buildUserItem).join('')}
                            </div>
                        `;

                    container.querySelectorAll('.user-checkbox').forEach(checkbox => {
                        checkbox.addEventListener('change', function() {
                            const id = Number(this.value);
                            if (this.checked) {
                                selectedUserIds.add(id);
                            } else {
                                selectedUserIds.delete(id);
                            }
                            updateUserCount();
                        });
                    });

                    updateUserCount();
                }

                function filterUsers() {
                    const searchTerm = document.getElementById('userSearchInput').value.trim();
                    loadUsers(userRoleId.value, searchTerm);
                }

                // Add search input event listener with debounce
                let searchTimeout;
                document.getElementById('userSearchInput').addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(filterUsers, 300); // 300ms debounce
                });

                /* ═══════════════════════════
                   User Count Update
                ═══════════════════════════ */
                function updateUserCount() {
                    const visibleChecked = document.querySelectorAll('.user-checkbox:checked').length;
                    const badge = document.getElementById('userCountBadge');
                    badge.textContent = visibleChecked;

                    // Add animation
                    badge.parentElement.style.transform = 'scale(1.05)';
                    setTimeout(() => {
                        badge.parentElement.style.transform = 'scale(1)';
                    }, 150);
                }

                /* ═══════════════════════════
                   Select/Deselect All Users
                ═══════════════════════════ */
                document.getElementById('selectAllUsersBtn').addEventListener('click', function() {
                    document.querySelectorAll('.user-checkbox').forEach(cb => {
                        cb.checked = true;
                        selectedUserIds.add(Number(cb.value));
                    });
                    updateUserCount();
                });

                document.getElementById('deselectAllUsersBtn').addEventListener('click', function() {
                    document.querySelectorAll('.user-checkbox').forEach(cb => {
                        cb.checked = false;
                        selectedUserIds.delete(Number(cb.value));
                    });
                    updateUserCount();
                });

                /* ═══════════════════════════
                   SAVE USERS
                ═══════════════════════════ */
                document.getElementById('saveUsersBtn').addEventListener('click', async function() {
                    const roleId = userRoleId.value;
                    const users = Array.from(selectedUserIds);

                    setUserLoading(true);

                    try {
                        const res = await fetch(routes.assignUsers(roleId), {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': csrf(),
                                'Accept': 'application/json',
                            },
                            body: JSON.stringify({
                                users
                            }),
                        });

                        const data = await res.json();

                        if (!res.ok) {
                            toast(data.message ?? 'Error saving users.', 'error');
                            return;
                        }

                        bsUserModal.hide();
                        toast(data.message, 'success');

                        // Update users count in table
                        const row = document.querySelector(`tr[data-id="${roleId}"]`);
                        if (row) {
                            row.querySelector('.users-count').textContent =
                                `${users.length} Users`;
                        }

                    } catch {
                        toast('Network error.', 'error');
                    } finally {
                        setUserLoading(false);
                    }
                });

                /* ═══════════════════════════
                   DELETE
                ═══════════════════════════ */
                let pendingDeleteId = null;

                const overlay = document.getElementById('deleteConfirmOverlay');
                const confirmDelBtn = document.getElementById('confirmDeleteBtn');
                const cancelDelBtn = document.getElementById('cancelDeleteBtn');
                const deleteSpinner = document.getElementById('deleteSpinner');

                document.getElementById('rolesBody').addEventListener('click', function(e) {
                    const delBtn = e.target.closest('.delete-btn');
                    if (!delBtn) return;
                    e.preventDefault();

                    pendingDeleteId = delBtn.dataset.id;
                    overlay.classList.add('show');
                });

                cancelDelBtn.addEventListener('click', () => {
                    overlay.classList.remove('show');
                    pendingDeleteId = null;
                });

                overlay.addEventListener('click', (e) => {
                    if (e.target === overlay) {
                        overlay.classList.remove('show');
                        pendingDeleteId = null;
                    }
                });

                confirmDelBtn.addEventListener('click', async function() {
                    if (!pendingDeleteId) return;

                    confirmDelBtn.disabled = true;
                    deleteSpinner.classList.remove('d-none');

                    try {
                        const res = await fetch(routes.destroy(pendingDeleteId), {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': csrf(),
                                'Accept': 'application/json'
                            },
                        });
                        const data = await res.json();

                        overlay.classList.remove('show');

                        if (!res.ok || !data.success) {
                            toast(data.message ?? 'Delete failed.', 'error');
                            return;
                        }

                        const row = document.querySelector(
                            `tr[data-id="${pendingDeleteId}"]`);
                        if (row) {
                            row.style.transition = 'opacity 0.3s';
                            row.style.opacity = '0';
                            setTimeout(() => {
                                row.remove();
                                if (!document.querySelector('#rolesBody tr')) {
                                    document.getElementById('rolesBody').innerHTML = `
                                <tr id="emptyRow">
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="bx bx-info-circle fs-3"></i>
                                        <div class="mt-2">No roles found. Please add a role.</div>
                                    </td>
                                </tr>`;
                                }
                            }, 300);
                        }

                        toast(data.message, 'success');

                    } catch {
                        toast('Network error.', 'error');
                        overlay.classList.remove('show');
                    } finally {
                        confirmDelBtn.disabled = false;
                        deleteSpinner.classList.add('d-none');
                        pendingDeleteId = null;
                    }
                });

                /* ═══════════════════════════
                   Search / Filter
                ═══════════════════════════ */
                document.getElementById('searchInput').addEventListener('input', function() {
                    const q = this.value.toLowerCase().trim();
                    document.querySelectorAll('#rolesBody tr[data-id]').forEach(row => {
                        const name = row.querySelector('.role-name')?.textContent
                            .toLowerCase() ?? '';
                        row.style.display = name.includes(q) ? '' : 'none';
                    });
                });

            })();
        </script>
    <?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Abdur Rahman\Desktop\faa\resources\views\backend\roles_permissions\index.blade.php ENDPATH**/ ?>