
<?php $__env->startSection("content"); ?>
<?php $__env->startSection("title","Update Roles"); ?>

<div class="row">
    <div class="col-xl-12 col-lg-12">
        <div class="alert alert-success my-3" style="display:none;" id="success"></div>
        
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-0">Update Roles</h4>
            </div>
            
            <div class="card-body">
                <form accept-charset="utf-8" name="update-form" id="update-form">
                    <?php echo csrf_field(); ?>
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="mb-3">
                                <label for="update-name" class="form-label"><?php echo e($dbs_roles['name_req']); ?><?php echo e($dbs_roles['name_title']); ?></label>
                                <input type = '<?php echo e($dbs_roles['name_html5_type']); ?>' name = "name"  id = "update-name" autocomplete = 'off' maxlength ='<?php echo e($dbs_roles['name_max']); ?>'  value='<?php echo e($row->name); ?>' <?php if($dbs_roles['name_html5_req']!=''): ?> <?php echo e($dbs_roles['name_html5_req']); ?> = <?php echo e($dbs_roles['name_html5_req']); ?> <?php endif; ?> class= 'form-control'>
                                <span class='text-danger' id='update-nameError'></span>
                            </div>
                        </div>

                        <div class="col-lg-6">
                            <div class="mb-3">
                                <label for="update-guard_name" class="form-label"><?php echo e($dbs_roles['guard_name_req']); ?><?php echo e($dbs_roles['guard_name_title']); ?></label>
                                <input type = '<?php echo e($dbs_roles['guard_name_html5_type']); ?>' name = "guard_name"  id = "update-guard_name" autocomplete = 'off' maxlength ='<?php echo e($dbs_roles['guard_name_max']); ?>'  value='<?php echo e($row->guard_name); ?>' <?php if($dbs_roles['guard_name_html5_req']!=''): ?> <?php echo e($dbs_roles['guard_name_html5_req']); ?> = <?php echo e($dbs_roles['guard_name_html5_req']); ?> <?php endif; ?> class= 'form-control'>
                                <span class='text-danger' id='update-guard_nameError'></span>
                            </div>
                        </div>
                    </div>

                    <div class="card-header mt-3 d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <h4 class="card-title mb-0">Permissions</h4>
                        <div class="d-flex flex-wrap gap-2">
                            <input type="file" id="import-permissions-csv-input" accept=".csv,text/csv" class="d-none">
                            <button type="button" class="btn btn-outline-primary btn-sm" id="import-permissions-csv-btn">
                                <i class="ri-file-upload-line"></i> Import CSV
                            </button>
                            <button type="button" class="btn btn-success btn-sm" id="export-permissions-csv">
                                <i class="ri-file-download-line"></i> Export CSV
                            </button>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="permissions-table">
                                <thead class="table-light">
                                    <tr>
                                        <th class="text-center" style="width: 3rem;" title="Select rows to include in CSV export">
                                            <input type="checkbox" id="permExportSelectAll" checked aria-label="Check all rows for export">
                                        </th>
                                        <th>Page</th>
                                        <th class="text-center">
                                            List<br><input type="checkbox" id="checkAllList">
                                        </th>
                                        <th class="text-center">
                                            Create<br><input type="checkbox" id="checkAllCreate">
                                        </th>
                                        <th class="text-center">
                                            Edit<br><input type="checkbox" id="checkAllEdit">
                                        </th>
                                        <th class="text-center">
                                            Delete<br><input type="checkbox" id="checkAllDelete">
                                        </th>
                                        <th class="text-center">
                                            All<br><input type="checkbox" id="checkAll">
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $grouped = collect($permissions)->groupBy('page'); ?>
                                    <?php $__currentLoopData = $grouped; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $page => $perms): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td class="text-center align-middle">
                                            <input type="checkbox" class="perm-export-row" data-page="<?php echo e($page); ?>" checked aria-label="Include this page in CSV export">
                                        </td>
                                        <td><?php echo e(ucfirst(str_replace('_', ' ', $page))); ?></td>
                                        <?php $__currentLoopData = ['list', 'create', 'edit', 'delete']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $action): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <?php $perm = $perms->firstWhere('title', $action); ?>
                                        <td class="text-center">
                                            <?php if($perm): ?>
                                            <input type="checkbox" name="permissions[]" value="<?php echo e($perm->id); ?>"
                                                   class="perm-<?php echo e($action); ?> page-<?php echo e($page); ?>"
                                                   data-perm-name="<?php echo e($perm->name); ?>"
                                                   data-perm-guard="<?php echo e($perm->guard_name); ?>"
                                                   data-perm-page="<?php echo e($page); ?>"
                                                   data-perm-title="<?php echo e($perm->title); ?>"
                                                   <?php if(in_array($perm->id, $assignedPermissions)): ?> checked <?php endif; ?>>
                                            <?php endif; ?>
                                        </td>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <td class="text-center">
                                            <input type="checkbox" class="row-check-all" data-page="<?php echo e($page); ?>">
                                        </td>
                                    </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="alert alert-info py-2 px-3 mt-2 mb-0 d-none small" id="permissions-import-feedback" role="status"></div>
                        <span class='text-danger' id='update-permissionsError'></span>
                    </div>

                    <div class="p-3 mb-3 rounded">
                        <div class="row justify-content-end g-2">
                            <div class="col-lg-3">
                                <div id="edit-mode">
                                    <button type='submit' name='update-submit' id='update-submit' class='btn btn-outline-secondary w-100' data-args1='<?php echo e(route("roles.update", $row->id)); ?>' data-args2='admin/roles' onclick='addUpdate(event,"update")'>
                                        <i class="ri-save-line"></i> Save 
                                    </button>
                                </div>
                            </div>
                            <div class="col-lg-2">
                                <a href="<?php echo e(url('/admin/roles')); ?>" class="btn btn-primary w-100">
                                    <i class="ri-close-circle-line"></i> Cancel
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script>
    function escapeCsvField(val) {
        const s = String(val == null ? '' : val);
        if (/[",\n\r]/.test(s)) {
            return '"' + s.replace(/"/g, '""') + '"';
        }
        return s;
    }

    /** Parse CSV text into rows (array of string arrays); handles quotes, commas, \r\n, and BOM. */
    function parseCsvText(text) {
        text = String(text).replace(/^\uFEFF/, '');
        const rows = [];
        let row = [];
        let cur = '';
        let inQuotes = false;
        for (let i = 0; i < text.length; i++) {
            const c = text[i];
            if (inQuotes) {
                if (c === '"') {
                    if (text[i + 1] === '"') {
                        cur += '"';
                        i++;
                    } else {
                        inQuotes = false;
                    }
                } else {
                    cur += c;
                }
            } else if (c === '"') {
                inQuotes = true;
            } else if (c === ',') {
                row.push(cur);
                cur = '';
            } else if (c === '\n' || c === '\r') {
                if (c === '\r' && text[i + 1] === '\n') {
                    i++;
                }
                row.push(cur);
                if (row.some(function (cell) { return String(cell).length > 0; })) {
                    rows.push(row);
                }
                row = [];
                cur = '';
            } else {
                cur += c;
            }
        }
        row.push(cur);
        if (row.some(function (cell) { return String(cell).length > 0; })) {
            rows.push(row);
        }
        return rows;
    }

    function csvAssignedToBool(val) {
        const v = String(val == null ? '' : val).trim().toLowerCase();
        return v === 'yes' || v === 'true' || v === '1' || v === 'y' || v === 'on';
    }

    /** Match exported CSV rows to permission checkboxes: prefer id; else name/page/title. */
    function findPermissionInputByRow(rowObj) {
        const id = String(rowObj.id != null ? rowObj.id : '').trim();
        if (id !== '') {
            const inputs = document.querySelectorAll('input[name="permissions[]"]');
            for (let i = 0; i < inputs.length; i++) {
                if (String(inputs[i].value) === id) {
                    return inputs[i];
                }
            }
            return null;
        }

        const name = String(rowObj.name != null ? rowObj.name : '').trim();
        const page = String(rowObj.page != null ? rowObj.page : '').trim();
        const title = String(rowObj.title != null ? rowObj.title : '').trim();
        if (!name && !page && !title) {
            return null;
        }

        let found = null;
        document.querySelectorAll('input[name="permissions[]"]').forEach(function (el) {
            if (found) {
                return;
            }
            const en = (el.getAttribute('data-perm-name') || '').trim();
            const ep = (el.getAttribute('data-perm-page') || '').trim();
            const et = (el.getAttribute('data-perm-title') || '').trim();
            if (name && en !== name) {
                return;
            }
            if (page && ep !== page) {
                return;
            }
            if (title && et !== title) {
                return;
            }
            found = el;
        });
        return found;
    }

    (function () {
        const exportAll = document.getElementById('permExportSelectAll');
        const exportRows = () => document.querySelectorAll('.perm-export-row');

        exportAll.addEventListener('change', function () {
            exportRows().forEach(function (el) { el.checked = exportAll.checked; });
        });

        exportRows().forEach(function (rowCb) {
            rowCb.addEventListener('change', function () {
                const all = Array.from(exportRows());
                exportAll.checked = all.length > 0 && all.every(function (c) { return c.checked; });
                exportAll.indeterminate = all.some(function (c) { return c.checked; }) && !exportAll.checked;
            });
        });

        document.getElementById('export-permissions-csv').addEventListener('click', function () {
            const header = ['id', 'name', 'guard_name', 'page', 'title', 'assigned_to_role'];
            const lines = [header.map(escapeCsvField).join(',')];
            let count = 0;

            document.querySelectorAll('#permissions-table tbody tr').forEach(function (tr) {
                const exportCb = tr.querySelector('.perm-export-row');
                if (!exportCb || !exportCb.checked) return;

                tr.querySelectorAll('input[name="permissions[]"]').forEach(function (inp) {
                    count++;
                    lines.push([
                        inp.value,
                        inp.getAttribute('data-perm-name') || '',
                        inp.getAttribute('data-perm-guard') || '',
                        inp.getAttribute('data-perm-page') || '',
                        inp.getAttribute('data-perm-title') || '',
                        inp.checked ? 'yes' : 'no'
                    ].map(escapeCsvField).join(','));
                });
            });

            if (count === 0) {
                alert('Select one or more pages using the checkboxes in the first column, then export again.');
                return;
            }

            const bom = '\uFEFF';
            const blob = new Blob([bom + lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'role-<?php echo e((int) $row->id); ?>-permissions-export.csv';
            a.click();
            URL.revokeObjectURL(url);
        });

        const importInput = document.getElementById('import-permissions-csv-input');
        const importBtn = document.getElementById('import-permissions-csv-btn');
        const importFeedback = document.getElementById('permissions-import-feedback');

        importBtn.addEventListener('click', function () {
            importInput.click();
        });

        importInput.addEventListener('change', function () {
            const file = importInput.files && importInput.files[0];
            importInput.value = '';
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (e) {
                const text = e.target.result;
                const rows = parseCsvText(text);
                if (rows.length < 2) {
                    importFeedback.textContent = 'CSV has no data rows. Use the same format as Export (header row required).';
                    importFeedback.classList.remove('d-none', 'alert-success');
                    importFeedback.classList.add('alert-danger');
                    return;
                }

                const headers = rows[0].map(function (h) {
                    return String(h).trim().toLowerCase().replace(/^\ufeff/, '');
                });
                const idx = {
                    id: headers.indexOf('id'),
                    name: headers.indexOf('name'),
                    guard_name: headers.indexOf('guard_name'),
                    page: headers.indexOf('page'),
                    title: headers.indexOf('title'),
                    assigned: headers.indexOf('assigned_to_role')
                };

                if (idx.assigned < 0) {
                    importFeedback.textContent = 'Missing column "assigned_to_role". Export a sample file and edit that column (yes/no).';
                    importFeedback.classList.remove('d-none', 'alert-success');
                    importFeedback.classList.add('alert-danger');
                    return;
                }

                let applied = 0;
                let skipped = 0;
                const missing = [];

                for (let r = 1; r < rows.length; r++) {
                    const cells = rows[r];
                    if (!cells || !cells.length) continue;
                    const rowObj = {
                        id: idx.id >= 0 ? cells[idx.id] : '',
                        name: idx.name >= 0 ? cells[idx.name] : '',
                        guard_name: idx.guard_name >= 0 ? cells[idx.guard_name] : '',
                        page: idx.page >= 0 ? cells[idx.page] : '',
                        title: idx.title >= 0 ? cells[idx.title] : '',
                        assigned: cells[idx.assigned]
                    };

                    const inp = findPermissionInputByRow(rowObj);
                    if (!inp) {
                        skipped++;
                        const label = String(rowObj.id || rowObj.name || ('row ' + (r + 1))).trim();
                        if (missing.length < 8) missing.push(label);
                        continue;
                    }
                    inp.checked = csvAssignedToBool(rowObj.assigned);
                    applied++;
                }

                importFeedback.classList.remove('d-none', 'alert-danger');
                importFeedback.classList.add('alert-success');
                let msg = 'Import applied: ' + applied + ' permission(s) updated.';
                if (skipped) {
                    msg += ' ' + skipped + ' row(s) had no matching checkbox on this screen.';
                    if (missing.length) {
                        msg += ' Examples: ' + missing.join(', ') + (skipped > missing.length ? '…' : '') + '.';
                    }
                }
                msg += ' Click Save to persist changes to this role.';
                importFeedback.textContent = msg;
            };
            reader.onerror = function () {
                importFeedback.textContent = 'Could not read the file.';
                importFeedback.classList.remove('d-none', 'alert-success');
                importFeedback.classList.add('alert-danger');
            };
            reader.readAsText(file, 'UTF-8');
        });
    })();

    // Check all by column
    document.getElementById('checkAllList').addEventListener('change', function () {
        document.querySelectorAll('.perm-list').forEach(el => el.checked = this.checked);
    });
    document.getElementById('checkAllCreate').addEventListener('change', function () {
        document.querySelectorAll('.perm-create').forEach(el => el.checked = this.checked);
    });
    document.getElementById('checkAllEdit').addEventListener('change', function () {
        document.querySelectorAll('.perm-edit').forEach(el => el.checked = this.checked);
    });
    document.getElementById('checkAllDelete').addEventListener('change', function () {
        document.querySelectorAll('.perm-delete').forEach(el => el.checked = this.checked);
    });

    // Check all permissions in the entire table
    document.getElementById('checkAll').addEventListener('change', function () {
        document.querySelectorAll('input[name="permissions[]"]').forEach(el => el.checked = this.checked);
    });

    // Check all in a specific row
    document.querySelectorAll('.row-check-all').forEach(rowCheckbox => {
        rowCheckbox.addEventListener('change', function () {
            let page = this.getAttribute('data-page');
            document.querySelectorAll(`.page-${page}`).forEach(el => el.checked = this.checked);
        });
    });
</script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make("layouts.metor.admin", \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /Applications/MAMP/htdocs/payroll/resources/views/roles/edit.blade.php ENDPATH**/ ?>