<?php $__env->startPush('styles'); ?>
<style>
    /* DELETE button ka left border-radius remove */
    .btn-group .btn-outline-danger {
        border-top-left-radius: 0 !important;
        border-bottom-left-radius: 0 !important;
    }

    /* EDIT button ka right border-radius remove */
    .btn-group .btn-outline-secondary {
        border-top-right-radius: 0 !important;
        border-bottom-right-radius: 0 !important;
    }

    /* PERMISSIONS button ke left-right equal ho jayen */
    .btn-group .btn-outline-primary {
        border-radius: 0 !important;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="content">
    <div class="container-fluid py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">Roles</h1>
                <p class="text-secondary mb-0">View and manage application roles.</p>
            </div>
            <a href="<?php echo e(route('roles.create')); ?>" class="btn btn-primary">
                <i class="bi bi-shield-plus me-2"></i>Add Role
            </a>
        </div>

        <?php if(session('success')): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo e(session('success')); ?>

                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="card shadow-sm">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="rolesTable" class="table table-hover mb-0 align-middle table-striped">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 60px;">#</th>
                                <th>Role Name</th>
                                <th>Permissions</th>
                                <th>Guard</th>
                                <th>Status</th>
                                <th class="text-center" style="width: 220px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $roles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr data-role-row="<?php echo e($role->id); ?>">
                                    <td><?php echo e($index + 1); ?></td>
                                    <td class="text-capitalize"><?php echo e($role->name); ?></td>
                                    <td>
                                        <?php if($role->permissions_count): ?>
                                            <span class="badge text-bg-primary role-permission-count"
                                                  data-role-id="<?php echo e($role->id); ?>">
                                                <?php echo e($role->permissions_count); ?> permission(s)
                                            </span>
                                        <?php else: ?>
                                            <span class="text-secondary role-permission-count"
                                                  data-role-id="<?php echo e($role->id); ?>">No permissions</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo e($role->guard_name); ?></td>
                                      <td>
                                        <?php if($role->status === 'active'): ?>
                                            <span class="badge bg-success text-white">Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger text-white">Inactive</span>
                                        <?php endif; ?>
                                       </td>

                                    <td class="text-center">
                                        
                                         <div class="d-flex justify-content-center gap-2">

                                            <!-- EDIT (Yellow) -->
                                            <a href="<?php echo e(route('roles.edit', $role)); ?>"
                                                class="btn btn-warning text-white btn-action-square">
                                                <i class="bi bi-pencil-square"></i>
                                            </a>

                                            <!-- DELETE (Red) -->
                                            <form action="<?php echo e(route('roles.destroy', $role)); ?>"
                                                method="POST"
                                                class="d-inline"
                                                onsubmit="return confirm('Are you sure you want to delete this role?');">

                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>

                                                <button type="submit"
                                                    class="btn btn-danger text-white btn-action-square">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                              <!-- PERMISSIONS BUTTON -->
                                            <button class="btn btn-outline-primary"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#manageRolePermissionsModal<?php echo e($role->id); ?>">
                                                <i class="bi bi-sliders me-1"></i>Permissions
                                            </button>


                                        </div>

                                    </td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="5" class="text-center text-secondary py-4">
                                        <i class="bi bi-info-circle me-2"></i>No roles found.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php $__currentLoopData = $roles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
    <div class="modal fade role-permissions-modal" id="manageRolePermissionsModal<?php echo e($role->id); ?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">
                        Manage Permissions — <span class="text-capitalize"><?php echo e($role->name); ?></span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info d-flex align-items-center gap-2" role="alert">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>Changes save automatically when you toggle permissions.</div>
                    </div>
                    <div class="row g-3">
                        <?php $__currentLoopData = $permissions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $permission): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="col-12 col-md-6 col-lg-4">
                                <div class="form-check">
                                    <input
                                        class="form-check-input role-permission-checkbox"
                                        type="checkbox"
                                        id="role_<?php echo e($role->id); ?>_permission_<?php echo e($permission->id); ?>"
                                        data-role-id="<?php echo e($role->id); ?>"
                                        data-permission="<?php echo e($permission->name); ?>"
                                        <?php if($role->permissions->contains('id', $permission->id)): echo 'checked'; endif; ?>
                                    >
                                    <label class="form-check-label text-capitalize" for="role_<?php echo e($role->id); ?>_permission_<?php echo e($permission->id); ?>">
                                        <?php echo e($permission->name); ?>

                                    </label>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>
                <div class="modal-footer bg-body-tertiary">
                    <span class="text-secondary small role-permission-status" data-role-id="<?php echo e($role->id); ?>"></span>
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    var table = $('#rolesTable').DataTable({
        responsive: true,
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        order: [[0, 'asc']],
        columnDefs: [
            { orderable: false, targets: 4 }
        ],
         //AGAR BUTTONS SHOW KARAVANY HAIN EXCEL,PDF WAGIRA KY TO ISY NICHY BUTTONS KO UN COMMENT KRNA HY 
        //dom: '<"row"<"col-sm-12"B><"col-sm-12"f>>' +  FOR SHOW BUTTONS +SEARCH BAR 
        dom: '<"row"<"col-sm-12"f>>' + //FOR SEARCH BAR ONLY
             '<"row"<"col-sm-12"tr>>' +
             '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        processing: true,
        deferRender: true,
        buttons: [
            {
                extend: 'excel',
                text: '<i class="bi bi-file-earmark-spreadsheet me-1"></i>Excel',
                className: 'btn btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3]
                }
            },
            {
                extend: 'pdf',
                text: '<i class="bi bi-file-earmark-pdf me-1"></i>PDF',
                className: 'btn btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3]
                },
                customize: function(doc) {
                    doc.defaultStyle.fontSize = 9;
                    doc.styles.tableHeader.fontSize = 10;
                }
            },
            {
                extend: 'csv',
                text: '<i class="bi bi-filetype-csv me-1"></i>CSV',
                className: 'btn btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3]
                }
            },
            {
                extend: 'print',
                text: '<i class="bi bi-printer me-1"></i>Print',
                className: 'btn btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3]
                }
            }
        ],
        language: {
            search: "Search:",
            lengthMenu: "Show _MENU_ entries",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            infoEmpty: "Showing 0 to 0 of 0 entries",
            infoFiltered: "(filtered from _MAX_ total entries)",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Previous"
            },
            emptyTable: "No data available in table",
            zeroRecords: "No matching records found"
        }
    });
});

document.addEventListener('DOMContentLoaded', () => {
    const modals = document.querySelectorAll('.role-permissions-modal');

    modals.forEach((modal) => {
        modal.addEventListener('shown.bs.modal', () => {
            modal.querySelectorAll('.role-permission-checkbox').forEach((checkbox) => {
                checkbox.addEventListener('change', handlePermissionToggle);
            });
        });

        modal.addEventListener('hidden.bs.modal', () => {
            modal.querySelectorAll('.role-permission-checkbox').forEach((checkbox) => {
                checkbox.removeEventListener('change', handlePermissionToggle);
            });
            const statusEl = modal.querySelector('.role-permission-status');
            if (statusEl) statusEl.textContent = '';
        });
    });

    async function handlePermissionToggle(event) {
        const target = event.currentTarget;
        target.disabled = true;

        const roleId = target.dataset.roleId;
        const permission = target.dataset.permission;
        const assigned = target.checked;
        const statusEl = document.querySelector(`.role-permission-status[data-role-id="${roleId}"]`);
        const badgeEl = document.querySelector(`.role-permission-count[data-role-id="${roleId}"]`);

            statusEl.textContent = 'Saving...';

            try {
                const response = await fetch('<?php echo e(url('roles')); ?>/' + roleId + '/permissions/toggle', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({
                        permission,
                        assigned,
                    }),
                });

                if (!response.ok) {
                    throw new Error('Request failed');
                }

                const data = await response.json();

                statusEl.textContent = assigned
                    ? `Assigned "${permission}"`
                    : `Removed "${permission}"`;

                if (badgeEl) {
                    if (data.count > 0) {
                        badgeEl.classList.remove('text-secondary');
                        badgeEl.classList.add('badge', 'text-bg-primary');
                        badgeEl.textContent = `${data.count} permission(s)`;
                    } else {
                        badgeEl.classList.remove('badge', 'text-bg-primary');
                        badgeEl.classList.add('text-secondary');
                        badgeEl.textContent = 'No permissions';
                    }
                }
            } catch (error) {
                statusEl.textContent = 'Error saving changes.';
                target.checked = !assigned;
            } finally {
                target.disabled = false;
            }
    }
});
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH F:\www\waterPOS\resources\views\roles\index.blade.php ENDPATH**/ ?>