<?php
$aktifRole = App\Core\Request::int('role_id', (int)($roles[1]['id'] ?? 2));
$jml = [];
foreach ($jumlahPengguna as $j) $jml[(int)$j['role_id']] = (int)$j['n'];
$cur = array_values(array_filter($roles, fn($r)=>(int)$r['id']===$aktifRole))[0] ?? $roles[0];
?>
<div class="row g-3">
  <div class="col-lg-3">
    <div class="card"><div class="card-header"><i class="bi bi-person-badge me-1"></i>Peran</div>
      <div class="list-group list-group-flush">
        <?php foreach ($roles as $r): ?>
          <a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center <?= (int)$r['id']===$aktifRole?'active':'' ?>"
             href="<?= url('/pengguna/peran',['role_id'=>(int)$r['id']]) ?>">
            <span><?= e($r['name']) ?><br><small class="<?= (int)$r['id']===$aktifRole?'text-white-50':'text-body-secondary' ?>"><?= e(truncate($r['description'],44)) ?></small></span>
            <span class="badge bg-<?= (int)$r['id']===$aktifRole?'light text-dark':'secondary' ?>"><?= nf($jml[(int)$r['id']] ?? 0) ?></span>
          </a>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <div class="col-lg-9">
    <form method="post" action="<?= url('/pengguna/peran/simpan') ?>">
      <?= csrf() ?>
      <input type="hidden" name="role_id" value="<?= $aktifRole ?>">
      <div class="card">
        <div class="card-header"><i class="bi bi-shield-lock me-1"></i>Hak Akses — <?= e($cur['name']) ?>
          <div class="card-actions">
            <?php if ($aktifRole !== 1 && can('pengguna','edit')): ?>
              <button class="btn btn-sm btn-primary" type="submit"><i class="bi bi-save me-1"></i>Simpan Hak Akses</button>
            <?php endif; ?>
          </div>
        </div>
        <div class="card-body">
          <?php if ($aktifRole === 1): ?>
            <div class="alert alert-info mb-3"><i class="bi bi-info-circle me-1"></i>Super Administrator selalu memiliki akses penuh dan tidak dapat dibatasi.</div>
          <?php endif; ?>
          <div class="row g-3 mb-3">
            <div class="col-md-6"><label class="form-label" for="data_scope">Cakupan Data</label>
              <select class="form-select" id="data_scope" name="data_scope" <?= $aktifRole===1?'disabled':'' ?>>
                <?php foreach (['all'=>'Seluruh data perusahaan','own_collection'=>'Hanya invoice yang ditagihnya',
                                'own_sales'=>'Hanya invoice sales yang terhubung','own_area'=>'Hanya area yang terhubung'] as $k=>$v): ?>
                  <option value="<?= $k ?>" <?= ($cur['data_scope'] ?? 'all')===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select>
              <div class="form-text">Pembatasan ini diterapkan langsung pada query database, bukan hanya di tampilan.</div></div>
            <div class="col-md-6 d-flex align-items-end gap-2">
              <button class="btn btn-outline-secondary btn-sm" type="button" id="pilihSemua">Pilih Semua</button>
              <button class="btn btn-outline-secondary btn-sm" type="button" id="kosongkan">Kosongkan</button>
              <button class="btn btn-outline-secondary btn-sm" type="button" id="hanyaLihat">Hanya Lihat &amp; Ekspor</button>
            </div>
          </div>
          <div class="table-wrap" style="max-height:60vh"><table class="table table-sm table-sticky mb-0">
            <thead><tr><th>Modul</th>
              <?php foreach ($actionLabels as $a => $al): ?><th class="ctr"><?= e($al) ?></th><?php endforeach; ?>
            </tr></thead>
            <tbody>
            <?php foreach ($byModule as $mod => $perms): ?>
              <tr>
                <td class="fw-semibold"><?= e(ucwords(str_replace('_',' ',$mod))) ?></td>
                <?php foreach ($actionLabels as $a => $al):
                  $found = null;
                  foreach ($perms as $pp) if ($pp['action'] === $a) { $found = $pp; break; } ?>
                  <td class="ctr">
                    <?php if ($found): ?>
                      <input class="form-check-input izin" type="checkbox" name="permissions[]" value="<?= (int)$found['id'] ?>"
                             data-aksi="<?= e($a) ?>" <?= isset($matrix[$aktifRole][(int)$found['id']]) || $aktifRole===1 ? 'checked':'' ?>
                             <?= $aktifRole===1?'disabled':'' ?> aria-label="<?= attr($al.' '.$mod) ?>">
                    <?php else: ?><span class="text-body-tertiary">—</span><?php endif; ?>
                  </td>
                <?php endforeach; ?>
              </tr>
            <?php endforeach; ?>
            </tbody></table></div>
        </div>
      </div>
    </form>
  </div>
</div>
<?php viewStart('scripts'); ?>
<script>
document.getElementById('pilihSemua').addEventListener('click', () => document.querySelectorAll('.izin:not([disabled])').forEach(c => c.checked = true));
document.getElementById('kosongkan').addEventListener('click', () => document.querySelectorAll('.izin:not([disabled])').forEach(c => c.checked = false));
document.getElementById('hanyaLihat').addEventListener('click', () => document.querySelectorAll('.izin:not([disabled])').forEach(c =>
  c.checked = ['view','export','print'].includes(c.dataset.aksi)));
</script>
<?php viewStop(); ?>
