<?php require __DIR__ . '/../../layouts/header.php'; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h1 class="page-title"><i class="fa-solid fa-user-lock"></i><?= e(trans('rbac_manager')) ?></h1>
  <a class="btn ec-btn ec-btn btn-outline-secondary rounded-3" href="<?= e(base_path('admin')) ?>"><?= e(trans('back')) ?></a>
</div>

<div class="row g-4">
  <div class="col-lg-4">
    <div class="ec-card  ">
      <div class="ec-card-bd p-4">
        <div class="fw-bold mb-3">Roles</div>
        <?php foreach ($roles as $role): ?>
          <a class="d-block border rounded-4 p-3 mb-2 bg-white" href="<?= e(base_path('admin/rbac?role_id='.(int)$role['id'])) ?>">
            <div class="fw-bold"><?= e((string)($role['name'] ?? $role['code'])) ?></div>
            <div class="small text-muted"><?= e((string)($role['code'] ?? '')) ?></div>
          </a>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <div class="col-lg-8">
    <?php $roleId = (int)($_GET['role_id'] ?? ($roles[0]['id'] ?? 0)); ?>
    <div class="ec-card  ">
      <div class="ec-card-bd p-4">
        <form method="post" action="<?= e(base_path('admin/rbac/save')) ?>">
          <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="role_id" value="<?= e((string)$roleId) ?>">

          <div class="fw-bold mb-3">Permissions</div>

          <?php $group=''; ?>
          <?php foreach ($perms as $p): ?>
            <?php if (($p['group_name'] ?? '') !== $group): $group = (string)($p['group_name'] ?? ''); ?>
              <div class="mt-3 mb-2 badge-soft"><i class="fa-solid fa-folder-open"></i> <?= e($group) ?></div>
            <?php endif; ?>

            <div class="form-check border rounded-4 p-3 mb-2 bg-white">
              <input class="form-check-input" type="checkbox" name="perm[]" value="<?= e((string)$p['id']) ?>"
                <?= !empty($map[$roleId][(int)$p['id']]) ? 'checked' : '' ?>>
              <label class="form-check-label fw-bold">
                <?= e((string)($p['name'] ?? '')) ?> <span class="text-muted small">(<?= e((string)($p['code'] ?? '')) ?>)</span>
              </label>
            </div>
          <?php endforeach; ?>

          <button class="btn ec-btn ec-btn btn-success rounded-3 mt-3"><?= e(trans('save')) ?></button>
        </form>
      </div>
    </div>
  </div>
</div>

<?php require __DIR__ . '/../../layouts/footer.php'; ?>
