<?php /* users/roles.php */
$builtIn = ['super_admin','admin','developer','manager','hr_manager','cashier','stock_keeper','accountant'];
$roleConfig = [
  'super_admin'  => ['color'=>'#7c3aed','bg'=>'#f5f3ff','icon'=>'bi-shield-fill-check','label'=>'Super Admin'],
  'admin'        => ['color'=>'#1d4ed8','bg'=>'#eff6ff','icon'=>'bi-shield-fill',       'label'=>'Admin'],
  'developer'    => ['color'=>'#dc2626','bg'=>'#fef2f2','icon'=>'bi-tools',             'label'=>'Developer'],
  'manager'      => ['color'=>'#0369a1','bg'=>'#f0f9ff','icon'=>'bi-person-workspace',  'label'=>'Manager'],
  'hr_manager'   => ['color'=>'#7c3aed','bg'=>'#f5f3ff','icon'=>'bi-people-fill',       'label'=>'HR Manager'],
  'cashier'      => ['color'=>'#059669','bg'=>'#f0fdf4','icon'=>'bi-cash-register',     'label'=>'Cashier'],
  'stock_keeper' => ['color'=>'#d97706','bg'=>'#fffbeb','icon'=>'bi-boxes',             'label'=>'Stock Keeper'],
  'accountant'   => ['color'=>'#475569','bg'=>'#f8fafc','icon'=>'bi-calculator',        'label'=>'Accountant'],
];
$moduleIcons = [
  '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','dashboard'=>'bi-speedometer2',
];
$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',
];
$bypass = ['super_admin','admin','developer'];
?>

<style>
.roles-hero{background:linear-gradient(135deg,#0f2557,#1e40af);border-radius:12px;padding:20px 24px;color:#fff;margin-bottom:18px}

/* ── TABLE VIEW ─────────────────────────────────── */
.rt-wrap{overflow-x:auto;border-radius:10px;border:1px solid #e2e8f0}
.rt-table{border-collapse:collapse;width:100%;min-width:900px}
.rt-table thead th{
  background:#0f172a;color:#fff;font-size:.7rem;padding:10px 12px;
  text-align:center;white-space:nowrap;letter-spacing:.04em;
  position:sticky;top:0;z-index:3;
}
.rt-table thead th:first-child{text-align:left;min-width:160px;z-index:4}
.rt-table tbody td{padding:7px 10px;border-bottom:1px solid #f1f5f9;vertical-align:middle;font-size:.78rem}
.rt-table tbody tr:hover td{background:#f8fafc}
.rt-table tbody tr:last-child td{border:none}
.role-name-cell{display:flex;align-items:center;gap:8px}
.role-badge-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;
  justify-content:center;font-size:.9rem;flex-shrink:0}

/* Permission cells */
.perm-cell{text-align:center;padding:6px 8px !important}
.perm-tick{width:24px;height:24px;border-radius:5px;margin:0 auto;
  display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700}
.perm-tick.yes{background:#dcfce7;color:#15803d}
.perm-tick.no{ background:#f1f5f9;color:#cbd5e1}
.perm-tick.bypass{background:#fef9c3;color:#854d0e}
.perm-tick.partial{background:#dbeafe;color:#1d4ed8}

/* Module group header row */
.mod-group-row td{background:#f8fafc;font-size:.65rem;font-weight:800;
  color:#64748b;text-transform:uppercase;letter-spacing:.07em;padding:5px 12px !important}

/* Progress bar */
.perm-bar{height:6px;background:#e2e8f0;border-radius:3px;margin-top:3px;min-width:60px}
.perm-bar-fill{height:6px;border-radius:3px;transition:width .4s ease}

/* Add role card */
.add-role-btn{border:2px dashed #e2e8f0;border-radius:10px;padding:12px 20px;
  display:inline-flex;align-items:center;gap:8px;cursor:pointer;
  font-weight:600;color:#64748b;transition:all .15s;background:transparent;font-size:.82rem}
.add-role-btn:hover{border-color:#3b82f6;color:#1d4ed8;background:#eff6ff}
</style>

<!-- Hero -->
<div class="roles-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-lock me-2"></i>Roles & Permissions</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= count($roles) ?> roles &nbsp;·&nbsp;
        <?= count($permissions) ?> permissions &nbsp;·&nbsp;
        <i class="bi bi-lightning-fill text-warning me-1"></i>⚡ = Full bypass (super_admin/admin/developer)
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?= APP_URL ?>/users" class="btn btn-outline-light btn-sm">
        <i class="bi bi-people me-1"></i>Users
      </a>
      <button class="btn btn-light btn-sm fw-semibold" style="color:#1d4ed8"
              data-bs-toggle="modal" data-bs-target="#addRoleModal">
        <i class="bi bi-plus-circle me-1"></i>Add Role
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- Tab nav -->
<ul class="nav nav-tabs mb-3" id="roleTabs">
  <li class="nav-item">
    <a class="nav-link active fw-semibold" data-bs-toggle="tab" href="#tab-table">
      <i class="bi bi-table me-1"></i>Permission Table
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link fw-semibold" data-bs-toggle="tab" href="#tab-cards">
      <i class="bi bi-grid me-1"></i>Role Cards
    </a>
  </li>
</ul>

<div class="tab-content">

<!-- ══ TAB: Permission Table ════════════════════════════════ -->
<div class="tab-pane fade show active" id="tab-table">

  <div class="rt-wrap">
    <table class="rt-table">
      <thead>
        <tr>
          <th style="text-align:left">Permission</th>
          <?php foreach($roles as $role):
            $rn = $role['role_name'];
            $rc = $roleConfig[$rn] ?? ['color'=>'#64748b','bg'=>'#f8fafc','icon'=>'bi-person','label'=>ucfirst(str_replace('_',' ',$rn))];
            $isBp = in_array($rn, $bypass);
          ?>
          <th>
            <div style="color:<?=$isBp?'#fde68a':'#fff'?>"><?= e($rc['label']) ?></div>
            <div style="font-size:.6rem;opacity:.6"><?= $role['user_count']??0 ?> user<?=($role['user_count']??0)!=1?'s':''?></div>
          </th>
          <?php endforeach;?>
          <th style="min-width:80px">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $lastModule = '';
        $totalPerms = count($permissions);
        foreach($permissions as $p):
          $mod = $p['module'];
          if($mod !== $lastModule):
            $lastModule = $mod;
            $modColor = $moduleColors[$mod] ?? '#64748b';
            $modIcon  = $moduleIcons[$mod]  ?? 'bi-dot';
        ?>
        <!-- Module group row -->
        <tr class="mod-group-row">
          <td colspan="<?= count($roles)+2 ?>">
            <i class="bi <?=$modIcon?> me-1" style="color:<?=$modColor?>"></i>
            <?= strtoupper(e($mod)) ?>
          </td>
        </tr>
        <?php endif;?>

        <tr>
          <td style="padding-left:20px">
            <span class="fw-semibold" style="font-size:.78rem"><?= e($p['action']) ?></span>
            <div style="font-size:.62rem;color:#94a3b8"><?= e($p['permission_key']) ?></div>
          </td>
          <?php foreach($roles as $role):
            $rn      = $role['role_name'];
            $isBp    = in_array($rn,$bypass);
            $hasPerm = in_array($p['id'], $rolePermMap[$role['id']]??[]);
          ?>
          <td class="perm-cell">
            <?php if($isBp): ?>
            <div class="perm-tick bypass" title="Full bypass — all permissions granted">
              <i class="bi bi-lightning-fill"></i>
            </div>
            <?php elseif($hasPerm): ?>
            <div class="perm-tick yes" title="<?=e($rn)?> has this permission">
              <i class="bi bi-check-lg"></i>
            </div>
            <?php else: ?>
            <div class="perm-tick no" title="<?=e($rn)?> does not have this permission">
              <i class="bi bi-dash"></i>
            </div>
            <?php endif;?>
          </td>
          <?php endforeach;?>
          <td></td>
        </tr>
        <?php endforeach;?>

        <!-- Summary row -->
        <tr style="background:#f8fafc;border-top:2px solid #e2e8f0">
          <td class="fw-bold small ps-3">TOTAL PERMISSIONS</td>
          <?php foreach($roles as $role):
            $rn    = $role['role_name'];
            $isBp  = in_array($rn,$bypass);
            $cnt   = $isBp ? $totalPerms : count($rolePermMap[$role['id']]??[]);
            $pct   = $totalPerms > 0 ? round($cnt/$totalPerms*100) : 0;
            $rc    = $roleConfig[$rn] ?? ['color'=>'#64748b'];
          ?>
          <td class="text-center">
            <div class="fw-bold" style="color:<?=$rc['color']?>;font-size:.82rem">
              <?= $isBp ? 'All' : "{$cnt}/{$totalPerms}" ?>
            </div>
            <div class="perm-bar">
              <div class="perm-bar-fill" style="width:<?=$pct?>%;background:<?=$rc['color']?>"></div>
            </div>
          </td>
          <?php endforeach;?>
          <td></td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- Edit buttons below table -->
  <div class="d-flex gap-2 flex-wrap mt-3 align-items-center">
    <?php foreach($roles as $role):
      $rn=$role['role_name'];
      $rc=$roleConfig[$rn]??['color'=>'#64748b','label'=>ucfirst(str_replace('_',' ',$rn))];
    ?>
    <a href="<?= APP_URL ?>/roles/edit/<?= $role['id'] ?>"
       class="btn btn-sm fw-semibold"
       style="border:2px solid <?=$rc['color']?>33;background:<?=$rc['color']?>11;color:<?=$rc['color']?>">
      <i class="bi bi-sliders me-1"></i><?= e($rc['label']) ?>
    </a>
    <?php endforeach;?>
    <button class="add-role-btn" data-bs-toggle="modal" data-bs-target="#addRoleModal">
      <i class="bi bi-plus-circle"></i> Add Role
    </button>
  </div>
</div>

<!-- ══ TAB: Role Cards ═══════════════════════════════════════ -->
<div class="tab-pane fade" id="tab-cards">
  <div class="row g-3">
    <?php foreach($roles as $role):
      $rn  = $role['role_name'];
      $rc  = $roleConfig[$rn] ?? ['color'=>'#64748b','bg'=>'#f8fafc','icon'=>'bi-person-circle','label'=>ucfirst(str_replace('_',' ',$rn))];
      $isBp = in_array($rn,$bypass);
      $rPerms = $rolePermMap[$role['id']] ?? [];
      $cnt = $isBp ? count($permissions) : count($rPerms);
      $pct = count($permissions)>0 ? round($cnt/count($permissions)*100) : 0;
    ?>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div style="border:2px solid <?=$rc['color']?>33;border-radius:12px;overflow:hidden;height:100%">

        <!-- Header -->
        <div style="background:<?=$rc['bg']?>;padding:14px 16px;display:flex;align-items:center;gap:10px">
          <div class="role-badge-icon" style="background:<?=$rc['color']?>22;color:<?=$rc['color']?>">
            <i class="bi <?=$rc['icon']?> fs-5"></i>
          </div>
          <div class="flex-grow-1">
            <div class="fw-bold" style="color:<?=$rc['color']?>"><?= e($rc['label']) ?></div>
            <div style="font-size:.68rem;color:#64748b">
              <code style="font-size:.6rem"><?=e($rn)?></code>
              &nbsp;·&nbsp; <?=$role['user_count']??0?> user<?=($role['user_count']??0)!=1?'s':''?>
            </div>
          </div>
          <a href="<?=APP_URL?>/roles/edit/<?=$role['id']?>"
             class="btn btn-sm py-0 px-2"
             style="border:1px solid <?=$rc['color']?>44;color:<?=$rc['color']?>;background:transparent"
             title="Edit Permissions">
            <i class="bi bi-sliders"></i>
          </a>
        </div>

        <div style="padding:12px 14px">
          <?php if($isBp):?>
          <div style="background:<?=$rc['color']?>11;border:1px solid <?=$rc['color']?>33;border-radius:8px;padding:8px 10px;font-size:.72rem;font-weight:600;color:<?=$rc['color']?>;text-align:center">
            <i class="bi bi-lightning-fill me-1"></i>Full Access — All Permissions
          </div>
          <?php else:?>
          <!-- Top permissions -->
          <div class="d-flex flex-wrap gap-1 mb-2">
            <?php
            $shown = 0;
            foreach($permissions as $p) {
              if(!in_array($p['id'],$rPerms)) continue;
              if($shown >= 8) break;
              $mc = $moduleColors[$p['module']]??'#64748b';
              $action = str_replace($p['module'].'.','', $p['permission_key']);
              echo "<span style='background:{$mc}15;color:{$mc};border-radius:20px;padding:2px 8px;font-size:.62rem;font-weight:700'>{$action}</span>";
              $shown++;
            }
            $remaining = $cnt - $shown;
            if($remaining > 0) echo "<span style='background:#f1f5f9;color:#64748b;border-radius:20px;padding:2px 8px;font-size:.62rem'>+{$remaining} more</span>";
            ?>
          </div>
          <?php endif;?>

          <!-- Progress -->
          <div class="d-flex align-items-center gap-2 mt-2">
            <div class="perm-bar flex-grow-1">
              <div class="perm-bar-fill" style="width:<?=$pct?>%;background:<?=$rc['color']?>"></div>
            </div>
            <span style="font-size:.65rem;color:#64748b;white-space:nowrap;min-width:50px;text-align:right">
              <?= $isBp ? 'All' : "{$cnt}/".count($permissions) ?> perms
            </span>
          </div>
        </div>

      </div>
    </div>
    <?php endforeach;?>

    <!-- Add role -->
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div style="border:2px dashed #e2e8f0;border-radius:12px;height:100%;min-height:140px;
                  display:flex;flex-direction:column;align-items:center;justify-content:center;
                  gap:8px;cursor:pointer;transition:all .15s"
           onclick="new bootstrap.Modal(document.getElementById('addRoleModal')).show()"
           onmouseover="this.style.borderColor='#3b82f6';this.style.background='#eff6ff'"
           onmouseout="this.style.borderColor='#e2e8f0';this.style.background='transparent'">
        <i class="bi bi-plus-circle text-primary fs-2"></i>
        <div class="fw-semibold text-primary small">Create New Role</div>
      </div>
    </div>
  </div>
</div>

</div><!-- /tab-content -->

<!-- ── Add Role Modal ───────────────────────────────────────── -->
<div class="modal fade" id="addRoleModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold"><i class="bi bi-plus-circle me-2"></i>Create New Role</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/roles/create">
        <?= Auth::csrfField() ?>
        <div class="modal-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"
                   placeholder="e.g. supervisor" pattern="[a-z_]+" required autofocus>
            <div class="form-text">Lowercase letters and underscores only</div>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Description</label>
            <textarea name="description" class="form-control" rows="2"
                      placeholder="What can this role do?"></textarea>
          </div>
          <div>
            <label class="form-label small fw-semibold">
              <i class="bi bi-copy me-1 text-info"></i>Copy Permissions From
            </label>
            <select name="copy_from" class="form-select">
              <option value="">— Start Empty —</option>
              <?php foreach($roles as $r):
                if(in_array($r['role_name'],['super_admin','admin','developer'])) continue;
              ?>
              <option value="<?=$r['id']?>">
                <?=e(ucfirst(str_replace('_',' ',$r['role_name'])))?>
                (<?=$r['perm_count']??0?> perms)
              </option>
              <?php endforeach;?>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary fw-semibold">
            <i class="bi bi-arrow-right me-1"></i>Create & Edit Permissions
          </button>
        </div>
      </form>
    </div>
  </div>
</div>