<?php /* users/role_form.php */
$isEdit      = !empty($role);
$action      = $isEdit ? APP_URL.'/roles/edit/'.$role['id'] : APP_URL.'/roles/create';
$rolePermSet = array_flip($rolePerms ?? []);
$isBuiltin   = $isEdit && in_array($role['role_name'],['super_admin','admin','developer','manager','cashier','stock_keeper','accountant']);
$isBypass    = $isEdit && in_array($role['role_name'],['super_admin','admin','developer']);

$moduleIcons = [
  'dashboard'=>'bi-speedometer2','sales'=>'bi-receipt','customers'=>'bi-people',
  'purchases'=>'bi-cart3','suppliers'=>'bi-truck','products'=>'bi-box-seam',
  'stock'=>'bi-layers','categories'=>'bi-tags','brands'=>'bi-bookmark',
  'units'=>'bi-rulers','finance'=>'bi-bank','expenses'=>'bi-wallet2',
  'reports'=>'bi-bar-chart','payroll'=>'bi-cash-coin','users'=>'bi-person-gear',
  'roles'=>'bi-shield-lock','settings'=>'bi-gear','backup'=>'bi-database-down',
  'branches'=>'bi-building','developer'=>'bi-tools',
];
$moduleColors = [
  'sales'=>'#16a34a','customers'=>'#16a34a','purchases'=>'#0891b2',
  'suppliers'=>'#0891b2','products'=>'#d97706','stock'=>'#d97706',
  'categories'=>'#d97706','brands'=>'#d97706','units'=>'#d97706',
  'finance'=>'#7c3aed','expenses'=>'#7c3aed','reports'=>'#1d4ed8',
  'payroll'=>'#059669','users'=>'#dc2626','roles'=>'#dc2626',
  'settings'=>'#64748b','backup'=>'#64748b','branches'=>'#64748b',
  'developer'=>'#dc2626',
];
?>

<style>
.rf-hero{background:linear-gradient(135deg,#0f2557,#1e40af);border-radius:12px;
  padding:18px 22px;color:#fff;margin-bottom:18px}
.mod-card{border:1.5px solid #e2e8f0;border-radius:10px;overflow:hidden;margin-bottom:10px}
.mod-header{padding:8px 14px;display:flex;align-items:center;justify-content:space-between;
  gap:8px;cursor:pointer;user-select:none;border-bottom:1px solid #f1f5f9;background:#f8fafc}
.mod-header:hover{background:#f1f5f9}
.perm-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));
  gap:6px;padding:12px 14px}
.perm-toggle{display:flex;align-items:center;gap:8px;padding:6px 10px;
  border-radius:8px;cursor:pointer;transition:background .12s;border:1.5px solid #e2e8f0}
.perm-toggle:hover{background:#eff6ff;border-color:#93c5fd}
.perm-toggle input:checked ~ .perm-label{color:#1d4ed8;font-weight:700}
.perm-toggle input:checked ~ .perm-icon{color:#1d4ed8}
.perm-toggle:has(input:checked){background:#eff6ff;border-color:#3b82f6}
.perm-label{font-size:.78rem;font-weight:600;color:#374151}
.perm-desc{font-size:.65rem;color:#94a3b8;margin-top:1px}
.select-all-btn{font-size:.68rem;font-weight:700;border:none;background:none;
  color:#3b82f6;cursor:pointer;padding:2px 6px;border-radius:4px}
.select-all-btn:hover{background:#dbeafe}
.save-bar{position:sticky;bottom:0;background:#fff;border-top:1.5px solid #e2e8f0;
  padding:12px 0;margin-top:16px;z-index:10}
</style>

<div class="rf-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1">
        <i class="bi bi-shield-<?= $isEdit?'check':'plus' ?> me-2"></i>
        <?= $isEdit ? 'Edit Role: <strong>'.e(ucfirst(str_replace('_',' ',$role['role_name']))).'</strong>' : 'Create New Role' ?>
      </h5>
      <div style="opacity:.8;font-size:.8rem">
        <?php if($isEdit):?>
        <?= $role['user_count']??0 ?> users assigned &nbsp;·&nbsp;
        <?php if($isBypass):?>
        <span class="badge bg-warning text-dark">⚡ Full Access — all permissions bypassed</span>
        <?php endif;?>
        <?php else:?>
        Set role name then assign permissions
        <?php endif;?>
      </div>
    </div>
    <a href="<?= APP_URL ?>/roles" class="btn btn-outline-light btn-sm">
      <i class="bi bi-arrow-left me-1"></i>Back to Roles
    </a>
  </div>
</div>

<?= flashMessages() ?>

<form method="POST" action="<?= $action ?>" id="roleForm">
  <?= Auth::csrfField() ?>

  <div class="row g-3">

    <!-- Left: Role info -->
    <div class="col-lg-4">
      <div class="card mb-3">
        <div class="card-header fw-semibold small bg-transparent">
          <i class="bi bi-info-circle me-1 text-primary"></i>Role Information
        </div>
        <div class="card-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">Role Name <span class="text-danger">*</span></label>
            <input type="text" name="role_name" class="form-control fw-semibold"
                   value="<?= e($role['role_name']??'') ?>"
                   placeholder="e.g. supervisor"
                   <?= $isBuiltin?'readonly':'' ?>
                   required>
            <?php if($isBuiltin):?>
            <div class="form-text">Built-in role name cannot be changed</div>
            <?php else:?>
            <div class="form-text">Lowercase, underscores only</div>
            <?php endif;?>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" class="form-control" rows="3"
                      placeholder="What can this role do?"><?= e($role['description']??'') ?></textarea>
          </div>

          <?php if($isEdit):?>
          <!-- Permission stats -->
          <div class="p-3 rounded" style="background:#f8fafc;border:1px solid #e2e8f0">
            <div class="fw-semibold small mb-2">
              <i class="bi bi-pie-chart me-1 text-primary"></i>Permission Summary
            </div>
            <?php
            $totalPerms = count(array_merge(...array_values($permsByModule)));
            $assignedCount = $isBypass ? $totalPerms : count($rolePerms??[]);
            $pct = $totalPerms > 0 ? round($assignedCount/$totalPerms*100) : 0;
            ?>
            <div class="d-flex justify-content-between small mb-1">
              <span class="text-muted">Assigned</span>
              <span class="fw-bold"><?= $isBypass ? 'All' : "{$assignedCount}/{$totalPerms}" ?></span>
            </div>
            <div style="height:8px;background:#e2e8f0;border-radius:4px">
              <div style="width:<?=$pct?>%;height:8px;border-radius:4px;background:#3b82f6;transition:width .3s"></div>
            </div>
            <?php if($isBypass):?>
            <div class="text-center mt-2 small text-warning fw-semibold">
              <i class="bi bi-lightning-fill me-1"></i>Bypasses all permission checks
            </div>
            <?php endif;?>
          </div>
          <?php endif;?>
        </div>
      </div>

      <!-- Quick actions -->
      <div class="card">
        <div class="card-header fw-semibold small bg-transparent">
          <i class="bi bi-lightning me-1 text-warning"></i>Quick Select
        </div>
        <div class="card-body d-flex flex-column gap-2">
          <button type="button" onclick="selectAll(true)"
                  class="btn btn-sm btn-outline-success fw-semibold">
            <i class="bi bi-check-all me-1"></i>Grant All Permissions
          </button>
          <button type="button" onclick="selectAll(false)"
                  class="btn btn-sm btn-outline-danger fw-semibold">
            <i class="bi bi-x-circle me-1"></i>Remove All Permissions
          </button>
          <hr class="my-1">
          <?php foreach([
            ['Sales Role',    ['sales','customers']],
            ['Stock Role',    ['products','stock','categories','brands','units']],
            ['Finance Role',  ['finance','expenses','reports']],
            ['Manager Role',  ['sales','customers','purchases','suppliers','products','stock','reports']],
          ] as[$preset,$mods]):?>
          <button type="button"
                  onclick="applyPreset(<?= json_encode($mods) ?>)"
                  class="btn btn-sm btn-outline-primary fw-semibold">
            <i class="bi bi-lightning me-1"></i><?= $preset ?>
          </button>
          <?php endforeach;?>
        </div>
      </div>
    </div>

    <!-- Right: Permissions -->
    <div class="col-lg-8">
      <div class="fw-semibold mb-2 d-flex align-items-center gap-2">
        <i class="bi bi-sliders text-primary fs-5"></i>
        Assign Permissions
        <span class="badge bg-primary ms-1" id="permCount">0</span>
        <?php if($isBypass):?>
        <span class="badge bg-warning text-dark">All permissions auto-granted for this role</span>
        <?php endif;?>
      </div>

      <?php foreach($permsByModule as $module => $perms):
        $modColor = $moduleColors[$module] ?? '#64748b';
        $modIcon  = $moduleIcons[$module] ?? 'bi-dot';
        $allSelected = true;
        foreach($perms as $p) {
          if(!isset($rolePermSet[$p['id']])) { $allSelected=false; break; }
        }
      ?>
      <div class="mod-card">
        <div class="mod-header" onclick="toggleModule('mod_<?= $module ?>')">
          <div class="d-flex align-items-center gap-2">
            <div style="width:28px;height:28px;border-radius:6px;background:<?=$modColor?>22;
                        display:flex;align-items:center;justify-content:center;flex-shrink:0">
              <i class="bi <?=$modIcon?>" style="color:<?=$modColor?>;font-size:.9rem"></i>
            </div>
            <span class="fw-semibold small" style="color:<?=$modColor?>"><?= ucfirst($module) ?></span>
            <span class="badge" style="background:<?=$modColor?>22;color:<?=$modColor?>;font-size:.6rem">
              <?= count($perms) ?> perms
            </span>
          </div>
          <div class="d-flex align-items-center gap-2">
            <button type="button" class="select-all-btn"
                    onclick="event.stopPropagation();toggleModuleAll('mod_<?= $module ?>')">
              <?= $allSelected ? 'Deselect all' : 'Select all' ?>
            </button>
            <i class="bi bi-chevron-down" id="chevron_<?= $module ?>" style="font-size:.7rem;color:#94a3b8"></i>
          </div>
        </div>

        <div id="mod_<?= $module ?>" style="display:block">
          <div class="perm-grid">
            <?php foreach($perms as $p):
              $checked = $isBypass || isset($rolePermSet[$p['id']]);
              $action  = str_replace($module.'.','', $p['permission_key']);
            ?>
            <label class="perm-toggle">
              <input type="checkbox" name="permissions[]"
                     value="<?= $p['id'] ?>"
                     class="form-check-input mt-0"
                     <?= $checked?'checked':'' ?>
                     onchange="updateCount()">
              <div>
                <div class="perm-label"><?= e($action) ?></div>
                <div class="perm-desc"><?= e(ucfirst(str_replace('.',' ',$p['permission_key']))) ?></div>
              </div>
            </label>
            <?php endforeach;?>
          </div>
        </div>
      </div>
      <?php endforeach;?>

      <!-- Save bar -->
      <div class="save-bar">
        <div class="d-flex gap-2 justify-content-between align-items-center">
          <span class="text-muted small">
            <span id="permCount2" class="fw-bold text-primary">0</span> permissions selected
          </span>
          <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/roles" class="btn btn-outline-secondary fw-semibold">
              Cancel
            </a>
            <button type="submit" class="btn btn-primary fw-bold px-5">
              <i class="bi bi-check-circle me-1"></i>
              <?= $isEdit ? 'Save Changes' : 'Create Role' ?>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>

<script>
// Track permission count
function updateCount() {
  const c = document.querySelectorAll('input[name="permissions[]"]:checked').length;
  const el1 = document.getElementById('permCount');
  const el2 = document.getElementById('permCount2');
  if(el1) el1.textContent = c;
  if(el2) el2.textContent = c;
}

function selectAll(val) {
  document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = val);
  updateCount();
}

function toggleModuleAll(modId) {
  const cbs = document.querySelectorAll(`#${modId} input[name="permissions[]"]`);
  const allChecked = [...cbs].every(cb => cb.checked);
  cbs.forEach(cb => cb.checked = !allChecked);
  updateCount();
}

function toggleModule(modId) {
  const el = document.getElementById(modId);
  const mod = modId.replace('mod_','');
  const chevron = document.getElementById('chevron_'+mod);
  if(el.style.display === 'none') {
    el.style.display = 'block';
    if(chevron) chevron.style.transform = '';
  } else {
    el.style.display = 'none';
    if(chevron) chevron.style.transform = 'rotate(-90deg)';
  }
}

// Apply preset
const permsByModule = <?= json_encode(array_map(fn($ps)=>array_map(fn($p)=>$p['id'],$ps), $permsByModule)) ?>;

function applyPreset(modules) {
  // Uncheck all first
  document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = false);
  // Check modules in preset
  modules.forEach(mod => {
    if(permsByModule[mod]) {
      permsByModule[mod].forEach(id => {
        const cb = document.querySelector(`input[value="${id}"]`);
        if(cb) cb.checked = true;
      });
    }
  });
  updateCount();
}

// Init count
updateCount();
</script>