<?= $this->include('layout/header') ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="mb-0">Manage Permissions: <?= esc($user['username'] ?? '') ?> (ID <?= (int)($user['id'] ?? 0) ?>)</h5>
  <a href="/settings/users" class="btn btn-outline-secondary btn-sm">Back to Users</a>
</div>

<?php if (session()->getFlashdata('success')): ?>
  <div class="alert alert-success py-2"><?= esc(session()->getFlashdata('success')) ?></div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')): ?>
  <div class="alert alert-danger py-2"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif; ?>

<?php
  // Build grouped permissions by namespace prefix (e.g., setup.*, reports.*)
  $permissionsMap = $permissionsMap ?? [];
  $assigned = $assigned ?? [];
  $groups = [];
  foreach ($permissionsMap as $key => $label) {
    $parts = explode('.', $key, 2);
    $ns = $parts[0] ?? 'other';
    $groups[$ns][$key] = $label;
  }
  $order = ['dashboard','setup','students','teachers','enrollment','payments','accounting','hr','payroll','reports','security','system','meta','other'];
  $titles = [
    'dashboard' => 'Dashboard',
    'setup' => 'Setup & Maintenance',
    'students' => 'Students',
    'teachers' => 'Teachers',
    'enrollment' => 'Registration / Enrollment',
    'payments' => 'Payments / Cash Receipts',
    'accounting' => 'Accounting',
    'hr' => 'HR',
    'payroll' => 'Payroll',
    'reports' => 'Reports',
    'security' => 'Security',
    'system' => 'System',
    'meta' => 'General Actions',
    'other' => 'Other',
  ];
?>

<div class="card">
  <div class="card-header">Uncheck what you want to restrict your user.</div>
  <div class="card-body">
    <form method="post" action="/settings/users/permissions/<?= (int)($user['id'] ?? 0) ?>">
      <?php foreach ($order as $ns): if (!isset($groups[$ns])) continue; ?>
        <div class="mb-3 perm-section">
          <h6 class="border-bottom pb-1 d-flex align-items-center">
            <?= esc($titles[$ns] ?? ucfirst($ns)) ?>
            <span class="ms-auto">
              <button type="button" class="btn btn-link btn-sm grant-all">Grant All</button>
              <button type="button" class="btn btn-link btn-sm revoke-all">Revoke All</button>
            </span>
          </h6>
          <div class="row">
            <?php foreach ($groups[$ns] as $permKey => $permLabel): ?>
              <div class="col-lg-4 col-md-6">
                <div class="form-check mb-2">
                  <input class="form-check-input" type="checkbox" name="permissions[]" value="<?= esc($permKey) ?>" id="perm_<?= esc(str_replace(['.', '*'], '_', $permKey)) ?>" <?= in_array($permKey, $assigned, true) ? 'checked' : '' ?> />
                  <label class="form-check-label" for="perm_<?= esc(str_replace(['.', '*'], '_', $permKey)) ?>">
                    <?= esc($permLabel) ?>
                  </label>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endforeach; ?>
      <div class="mt-3">
        <button type="submit" class="btn btn-primary">Save Permissions</button>
      </div>
    </form>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.perm-section').forEach(function (section) {
      const grantBtn = section.querySelector('.grant-all');
      const revokeBtn = section.querySelector('.revoke-all');
      if (grantBtn) {
        grantBtn.addEventListener('click', function () {
          section.querySelectorAll('input[type="checkbox"][name="permissions[]"]').forEach(function (cb) { cb.checked = true; });
        });
      }
      if (revokeBtn) {
        revokeBtn.addEventListener('click', function () {
          section.querySelectorAll('input[type="checkbox"][name="permissions[]"]').forEach(function (cb) { cb.checked = false; });
        });
      }
    });
  });
</script>
<?= $this->include('layout/footer') ?>