<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content">
            <h2 class="text-center mt-4 mb-3">Edit Role Permissions</h2>

            <!-- Flash messages -->
            <?php if (session()->getFlashdata('status')): ?>
                <div class="alert alert-success"><?= session()->getFlashdata('status'); ?></div>
            <?php elseif (session()->getFlashdata('error')): ?>
                <div class="alert alert-danger"><?= session()->getFlashdata('error'); ?></div>
            <?php endif; ?>

            <!-- Top action bar -->
            <div class="form-group d-flex justify-content-center flex-wrap gap-2 mb-3">
                <button type="button" class="btn btn-secondary" onclick="selectAllPermissions()">Select All</button>
                <button type="button" class="btn btn-secondary" onclick="deselectAllPermissions()">Deselect All</button>
                <button form="permissionsForm" type="submit" class="btn btn-primary">Save Permissions</button>
                <a href="<?= site_url('rolepermission/roles') ?>" class="btn btn-outline-secondary">Cancel</a>
            </div>

            <!-- Role Selection -->
            <?php if (isset($roles)): ?>
                <form id="roleSelectForm" class="mb-3" onsubmit="return false;">
                    <div class="form-group" style="max-width:480px;">
                        <label for="roleSelect" class="form-label">Select Role</label>
                        <select name="role_id" id="roleSelect" class="form-control" onchange="loadPermissions(this.value)">
                            <option value="">-- Select Role --</option>
                            <?php foreach ($roles as $role): ?>
                                <option value="<?= $role['id']; ?>" <?= isset($roleId) && (string)$roleId === (string)$role['id'] ? 'selected' : ''; ?>>
                                    <?= esc($role['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
            <?php else: ?>
                <p>No roles available. Please add roles first.</p>
            <?php endif; ?>

            <!-- Permissions Form -->
            <form id="permissionsForm" method="post" action="<?= site_url('rolepermission/edit_role_permissions/' . ($roleId ?? '')); ?>" class="mt-3" <?= empty($roleId) ? 'style="display:none;"' : '' ?>>
                <?= csrf_field() ?>
                <input type="hidden" name="role_id" id="roleId" value="<?= $roleId ?? ''; ?>">

                <div class="table-responsive">
                    <table id="permissionsTableEl" class="table table-bordered table-striped align-middle w-100">
                        <thead class="table-light">
                        <tr>
                            <th style="min-width:260px;">Permission</th>
                            <th>Create</th>
                            <th>Read</th>
                            <th>Update</th>
                            <th>Delete</th>
                        </tr>
                        </thead>
                        <tbody id="permissionsTable">
                        <?php if (isset($permissions, $existingPermissions, $roleId)): ?>
                            <?php foreach ($permissions as $permission): ?>
                                <?php $existingPermission = $existingPermissions[$permission['id']] ?? null; ?>
                                <tr>
                                    <td><?= esc($permission['name']); ?></td>
                                    <td class="text-center">
                                        <input type="checkbox" class="permission-checkbox"
                                               name="permissions[<?= $permission['id'] ?>][create]" value="1"
                                               <?= ($existingPermission['can_create'] ?? false) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="text-center">
                                        <input type="checkbox" class="permission-checkbox"
                                               name="permissions[<?= $permission['id'] ?>][read]" value="1"
                                               <?= ($existingPermission['can_read'] ?? false) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="text-center">
                                        <input type="checkbox" class="permission-checkbox"
                                               name="permissions[<?= $permission['id'] ?>][update]" value="1"
                                               <?= ($existingPermission['can_update'] ?? false) ? 'checked' : ''; ?>>
                                    </td>
                                    <td class="text-center">
                                        <input type="checkbox" class="permission-checkbox"
                                               name="permissions[<?= $permission['id'] ?>][delete]" value="1"
                                               <?= ($existingPermission['can_delete'] ?? false) ? 'checked' : ''; ?>>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Bottom action bar -->
                <div class="form-group d-flex justify-content-center flex-wrap gap-2 mt-3">
                    <button type="button" class="btn btn-secondary" onclick="selectAllPermissions()">Select All</button>
                    <button type="button" class="btn btn-secondary" onclick="deselectAllPermissions()">Deselect All</button>
                    <button type="submit" class="btn btn-primary">Save Permissions</button>
                    <a href="<?= site_url('rolepermission/roles') ?>" class="btn btn-outline-secondary">Cancel</a>
                </div>
            </form>
            <br>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('styles') ?>
    <!-- DataTables (Bootstrap 5) CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/dt-2.1.8/r-3.0.3/datatables.min.css">
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
    <!-- DataTables + deps (assumes jQuery already included by your layout) -->
    <script src="https://cdn.datatables.net/v/bs5/dt-2.1.8/r-3.0.3/datatables.min.js"></script>

    <script>
        let dtInstance = null;

        function initPermissionTable() {
            // Destroy an existing instance safely
            if (dtInstance) {
                dtInstance.destroy();
                dtInstance = null;
            }
            // Initialize DataTable
            dtInstance = new DataTable('#permissionsTableEl', {
                responsive: true,
                paging: true,
                searching: true,
                info: true,
                ordering: true,      // keeps alphabetical sort by Permission column
                order: [[0, 'asc']], // default sort by Permission name
                pageLength: 100,
                lengthMenu: [10, 25, 50, 100],
                // Ensure checkboxes remain interactive
                columnDefs: [
                    { targets: [1,2,3,4], orderable: false, searchable: false, className: 'text-center' }
                ]
            });
        }

        // Load permissions for the selected role via AJAX
        function loadPermissions(roleId) {
            if (roleId) {
                // Update form action & hidden input
                $('#permissionsForm').attr('action', '<?= site_url("rolepermission/edit_role_permissions"); ?>/' + roleId);
                $('#roleId').val(roleId);

                // Show form while loading (optional UX)
                $('#permissionsForm').show();

                $.get('<?= site_url("rolepermission/load_permissions"); ?>/' + roleId, function (data) {
                    // Replace tbody content with rows returned by server
                    $('#permissionsTable').html(data);

                    // Re-init DataTable after DOM update
                    initPermissionTable();
                }).fail(function () {
                    alert('Error loading permissions. Please try again.');
                });
            } else {
                // Hide form if no role selected
                $('#permissionsForm').hide();

                // If table exists, destroy DT to avoid errors
                if (dtInstance) {
                    dtInstance.destroy();
                    dtInstance = null;
                }
            }
        }

        // Select/Deselect helpers
        function selectAllPermissions() {
            $('.permission-checkbox').prop('checked', true);
        }
        function deselectAllPermissions() {
            $('.permission-checkbox').prop('checked', false);
        }

        // On page load: if role preselected, ensure DT is in place
        $(document).ready(function () {
            <?php if (isset($roleId) && !empty($roleId)): ?>
                $('#permissionsForm').show();
                initPermissionTable();
            <?php else: ?>
                $('#permissionsForm').hide();
            <?php endif; ?>
        });
    </script>
<?= $this->endSection() ?>
