<?php /* users/index.php */
$roleColors = [
  'super_admin' => ['#7c3aed','bi-shield-fill-check'],
  'admin'       => ['#1d4ed8','bi-shield-fill'],
  'developer'   => ['#059669','bi-code-slash'],
  'manager'     => ['#0891b2','bi-person-badge-fill'],
  'accountant'  => ['#d97706','bi-calculator-fill'],
  'cashier'     => ['#16a34a','bi-cash-coin'],
  'stock_keeper'=> ['#6366f1','bi-boxes'],
  'hr_manager'  => ['#db2777','bi-people-fill'],
];
$onlineThresh = 300; // 5 min = online
?>

<style>
.usr-hero{background:linear-gradient(135deg,#0f172a,#1e3a5f 55%,#1d4ed8);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.63rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.85}
.usr-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.usr-table td{font-size:.78rem;padding:8px 10px;vertical-align:middle}
.usr-table tr:hover td{background:#f8fafc}
.usr-avatar{width:38px;height:38px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.82rem;font-weight:700;flex-shrink:0;position:relative}
.online-dot{width:10px;height:10px;border-radius:50%;background:#16a34a;
  border:2px solid #fff;position:absolute;bottom:-1px;right:-1px}
.role-badge{display:inline-flex;align-items:center;gap:4px;padding:3px 8px;
  border-radius:12px;font-size:.65rem;font-weight:700}
.last-seen-bar{height:4px;border-radius:2px;background:#f1f5f9;margin-top:4px;overflow:hidden}
.last-seen-fill{height:4px;border-radius:2px;background:#16a34a}
</style>

<!-- Hero -->
<div class="usr-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-people-fill me-2"></i>User Management</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=$activeCount?> active users &nbsp;·&nbsp;
        <?=count($roleBreakdown)?> roles in use &nbsp;·&nbsp;
        <?=count(array_filter($users,fn($u)=>(int)($u['seconds_ago']??9999)<=$onlineThresh))?> online now
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('users.create')):?>
      <a href="<?=APP_URL?>/users/create"
         class="btn btn-light btn-sm fw-semibold" style="color:#1d4ed8">
        <i class="bi bi-person-plus me-1"></i>Add User
      </a>
      <?php endif;?>
      <a href="<?=APP_URL?>/roles"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-shield-check me-1"></i>Roles
      </a>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Row -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #1d4ed8">
      <div class="val" style="color:#1d4ed8"><?=$totalUsers?></div>
      <div class="lbl" style="color:#1d4ed8">Total Users</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a"><?=$activeCount?></div>
      <div class="lbl" style="color:#16a34a">Active</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #059669">
      <div class="val" style="color:#059669">
        <?=count(array_filter($users,fn($u)=>(int)($u['seconds_ago']??9999)<=$onlineThresh))?>
      </div>
      <div class="lbl" style="color:#059669">Online Now</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?=$totalUsers-$activeCount?></div>
      <div class="lbl" style="color:#dc2626">Inactive</div>
    </div>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-9">

    <!-- Filters -->
    <div class="card mb-3">
      <div class="card-body py-2">
        <form method="GET" action="<?=APP_URL?>/users"
              class="d-flex gap-2 flex-wrap align-items-end">
          <div class="input-group input-group-sm" style="max-width:220px">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control"
                   placeholder="Name, username, email…"
                   value="<?=e($search)?>">
          </div>
          <select name="role" class="form-select form-select-sm" style="max-width:150px">
            <option value="0">All Roles</option>
            <?php foreach($roles as $r):?>
            <option value="<?=$r['id']?>" <?=$roleF==$r['id']?'selected':''?>>
              <?=e($r['role_name'])?>
            </option>
            <?php endforeach;?>
          </select>
          <?php if(count($branches)>1):?>
          <select name="branch" class="form-select form-select-sm" style="max-width:140px">
            <option value="0">All Branches</option>
            <?php foreach($branches as $b):?>
            <option value="<?=$b['id']?>" <?=$branchF==$b['id']?'selected':''?>>
              <?=e($b['name'])?>
            </option>
            <?php endforeach;?>
          </select>
          <?php endif;?>
          <select name="status" class="form-select form-select-sm" style="max-width:110px">
            <option value="all"    <?=$statusF==='all'?   'selected':''?>>All</option>
            <option value="active" <?=$statusF==='active'?'selected':''?>>✓ Active</option>
            <option value="inactive"<?=$statusF==='inactive'?'selected':''?>>✗ Inactive</option>
          </select>
          <button class="btn btn-secondary btn-sm fw-semibold">
            <i class="bi bi-funnel me-1"></i>Filter
          </button>
          <a href="<?=APP_URL?>/users" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-x-lg"></i>
          </a>
        </form>
      </div>
    </div>

    <!-- Users Table -->
    <div class="card">
      <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
        <span class="fw-semibold small">
          <i class="bi bi-people me-1"></i>User List
        </span>
        <span class="badge bg-secondary"><?=count($users)?> users</span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm table-hover mb-0 usr-table">
          <thead class="table-dark">
            <tr>
              <th class="ps-3">#</th>
              <th>User</th>
              <th>Role</th>
              <th>Branch</th>
              <th class="text-center">Last Active</th>
              <th class="text-center">Status</th>
              <th class="text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($users)):?>
            <tr>
              <td colspan="7" class="text-center text-muted py-5">
                <i class="bi bi-people d-block fs-2 mb-2 opacity-25"></i>
                No users found.
              </td>
            </tr>
            <?php endif;?>

            <?php foreach($users as $i=>$user):
              $isActive  = $user['status'] === 'active';
              $secAgo    = (int)($user['seconds_ago'] ?? 9999);
              $isOnline  = $secAgo <= $onlineThresh;
              $isMe      = $user['id'] === Auth::id();

              $roleLower = strtolower(str_replace(' ','_',$user['role_name']));
              $roleClr   = ($roleColors[$roleLower]??['#64748b','bi-person'])[0];
              $roleIcon  = ($roleColors[$roleLower]??['#64748b','bi-person'])[1];

              $initials  = strtoupper(substr($user['name'],0,1)
                         .(strpos($user['name'],' ')!==false
                           ?substr(strrchr($user['name'],' '),1,1):''));

              // Last active display
              if ($secAgo <= 60)            $lastSeen = 'Just now';
              elseif ($secAgo <= 3600)      $lastSeen = round($secAgo/60).' min ago';
              elseif ($secAgo <= 86400)     $lastSeen = round($secAgo/3600).' hr ago';
              elseif ($secAgo <= 604800)    $lastSeen = round($secAgo/86400).' days ago';
              elseif ($secAgo >= 9999)      $lastSeen = $user['last_login']
                                              ? date('d M Y',strtotime($user['last_login']))
                                              : 'Never';
              else                          $lastSeen = round($secAgo/86400).' days ago';
            ?>
            <tr class="<?=$isActive?'':'opacity-50'?>">
              <td class="ps-3 text-muted small"><?=$i+1?></td>

              <!-- User -->
              <td>
                <div class="d-flex align-items-center gap-2">
                  <div class="usr-avatar"
                       style="background:<?=$roleClr?>18;color:<?=$roleClr?>">
                    <?=e($initials)?>
                    <?php if($isOnline && $isActive):?>
                    <div class="online-dot"></div>
                    <?php endif;?>
                  </div>
                  <div>
                    <div class="fw-semibold d-flex align-items-center gap-1">
                      <?=e($user['name'])?>
                      <?php if($isMe):?>
                      <span class="badge bg-primary" style="font-size:.55rem">You</span>
                      <?php endif;?>
                    </div>
                    <div style="font-size:.65rem;color:#94a3b8">
                      <i class="bi bi-person me-1"></i><?=e($user['username'])?>
                      <?php if($user['email']):?>
                      &nbsp;·&nbsp;<i class="bi bi-envelope me-1"></i><?=e($user['email'])?>
                      <?php endif;?>
                    </div>
                  </div>
                </div>
              </td>

              <!-- Role -->
              <td>
                <span class="role-badge"
                      style="background:<?=$roleClr?>18;color:<?=$roleClr?>">
                  <i class="bi <?=$roleIcon?>"></i>
                  <?=e($user['role_name'])?>
                </span>
                <?php if(Auth::can('users.edit') && !$isMe):?>
                <div style="margin-top:3px">
                  <form method="POST" action="<?=APP_URL?>/users/role/<?=$user['id']?>"
                        class="d-inline">
                    <?=Auth::csrfField()?>
                    <select name="role_id" class="form-select form-select-sm d-inline-block"
                            style="width:auto;font-size:.65rem;padding:1px 4px"
                            onchange="this.form.submit()"
                            title="Change role">
                      <?php foreach($roles as $r):?>
                      <option value="<?=$r['id']?>"
                              <?=$r['id']==$user['role_id']?'selected':''?>>
                        <?=e($r['role_name'])?>
                      </option>
                      <?php endforeach;?>
                    </select>
                  </form>
                </div>
                <?php endif;?>
              </td>

              <!-- Branch -->
              <td class="small text-muted">
                <i class="bi bi-building me-1"></i>
                <?=e($user['branch_name']??'Main Branch')?>
              </td>

              <!-- Last Active -->
              <td class="text-center">
                <?php if($isOnline && $isActive):?>
                <span class="badge bg-success" style="font-size:.62rem">
                  <i class="bi bi-circle-fill me-1" style="font-size:.45rem"></i>Online
                </span>
                <?php else:?>
                <div class="small text-muted"><?=$lastSeen?></div>
                <?php if($user['last_login'] && !$isOnline):?>
                <div style="font-size:.62rem;color:#94a3b8">
                  Login: <?=date('d M',strtotime($user['last_login']))?>
                </div>
                <?php endif;?>
                <?php endif;?>
              </td>

              <!-- Status -->
              <td class="text-center">
                <span class="badge <?=$isActive?'bg-success':'bg-secondary'?>"
                      style="font-size:.62rem">
                  <?=$isActive?'Active':'Inactive'?>
                </span>
              </td>

              <!-- Actions -->
              <td class="text-center">
                <div class="d-flex gap-1 justify-content-center">
                  <?php if(Auth::can('users.edit')):?>
                  <a href="<?=APP_URL?>/users/edit/<?=$user['id']?>"
                     class="btn btn-sm btn-outline-secondary py-0 px-2" title="Edit">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <?php if(!$isMe):?>
                  <form method="POST"
                        action="<?=APP_URL?>/users/toggle/<?=$user['id']?>"
                        onsubmit="return confirm('<?=$isActive?'Deactivate':'Activate'?> <?=e($user['name'])?>?')">
                    <?=Auth::csrfField()?>
                    <button class="btn btn-sm <?=$isActive?'btn-outline-warning':'btn-outline-success'?> py-0 px-1"
                            title="<?=$isActive?'Deactivate':'Activate'?>">
                      <i class="bi <?=$isActive?'bi-pause-circle':'bi-play-circle'?>"></i>
                    </button>
                  </form>
                  <?php endif;?>
                  <?php endif;?>
                  <?php if(Auth::can('users.delete') && !$isMe):?>
                  <form method="POST"
                        action="<?=APP_URL?>/users/delete/<?=$user['id']?>"
                        onsubmit="return confirm('Permanently delete <?=e($user['name'])?>?')">
                    <?=Auth::csrfField()?>
                    <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Delete">
                      <i class="bi bi-trash3"></i>
                    </button>
                  </form>
                  <?php endif;?>
                </div>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>

  </div>

  <!-- Right: Role Breakdown -->
  <div class="col-lg-3">
    <div class="card">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-shield-check me-1 text-primary"></i>Role Breakdown
      </div>
      <div class="card-body p-2">
        <?php
        $maxRole = max(array_column($roleBreakdown,'cnt')??[1]);
        foreach($roleBreakdown as $rb):
          $rk   = strtolower(str_replace(' ','_',$rb['role_name']));
          $clr  = ($roleColors[$rk]??['#64748b','bi-person'])[0];
          $icon = ($roleColors[$rk]??['#64748b','bi-person'])[1];
          $pct  = $maxRole>0?round($rb['cnt']/$maxRole*100):0;
        ?>
        <div class="mb-2 p-2 rounded" style="background:<?=$clr?>0d">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span class="small fw-semibold d-flex align-items-center gap-1"
                  style="color:<?=$clr?>">
              <i class="bi <?=$icon?>"></i>
              <?=e($rb['role_name'])?>
            </span>
            <span class="badge" style="background:<?=$clr?>;font-size:.6rem">
              <?=$rb['cnt']?>
            </span>
          </div>
          <div style="height:4px;background:<?=$clr?>20;border-radius:2px">
            <div style="height:4px;border-radius:2px;width:<?=$pct?>%;background:<?=$clr?>"></div>
          </div>
        </div>
        <?php endforeach;?>

        <div class="border-top pt-2 mt-1 d-flex justify-content-between"
             style="font-size:.72rem;font-weight:700">
          <span>TOTAL</span>
          <span class="text-primary"><?=$activeCount?> active</span>
        </div>
      </div>
    </div>

    <!-- Quick add link -->
    <?php if(Auth::can('users.create')):?>
    <div class="mt-2">
      <a href="<?=APP_URL?>/users/create"
         class="btn btn-primary btn-sm fw-semibold w-100">
        <i class="bi bi-person-plus me-1"></i>Add New User
      </a>
    </div>
    <div class="mt-2">
      <a href="<?=APP_URL?>/roles"
         class="btn btn-outline-secondary btn-sm w-100">
        <i class="bi bi-shield-check me-1"></i>Manage Roles & Permissions
      </a>
    </div>
    <?php endif;?>
  </div>

</div>