<?php
/**
 * Reusable module × action permission matrix.
 *
 * Expected variables:
 *   $groupedPerms  — PermissionModel::grouped()
 *   $assignedIds   — int[] of checked permission ids (optional, default [])
 *   $inputName      — form field name (default 'permissions[]')
 */
$actionColumns = ['view', 'create', 'edit', 'delete', 'export', 'print', 'approve'];
$assignedIds   = $assignedIds ?? [];
$inputName     = $inputName ?? 'permissions[]';

$byGroupAction = [];
foreach ($groupedPerms as $group => $perms) {
    foreach ($perms as $p) {
        $parts = explode('.', $p['slug'], 2);
        $action = $parts[1] ?? '';
        $byGroupAction[$group][$action] = $p;
    }
}
?>

<div class="table-responsive">
    <table class="table table-sm align-middle mb-0 permission-matrix">
        <thead>
            <tr>
                <th>Module</th>
                <?php foreach ($actionColumns as $col): ?>
                    <th class="text-center text-capitalize"><?= esc($col) ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($groupedPerms as $group => $perms): ?>
                <tr>
                    <td class="fw-semibold text-capitalize"><?= esc($group) ?></td>
                    <?php foreach ($actionColumns as $col): ?>
                        <td class="text-center">
                            <?php if (isset($byGroupAction[$group][$col])): ?>
                                <?php $perm = $byGroupAction[$group][$col]; ?>
                                <input type="checkbox" class="form-check-input" name="<?= esc($inputName) ?>"
                                       value="<?= $perm['id'] ?>"
                                       <?= in_array((int) $perm['id'], array_map('intval', $assignedIds), true) ? 'checked' : '' ?>>
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
