<?php
$rows = $rows ?? [];
$roles = $roles ?? [];
$counts = $counts ?? ['all' => 0, 'active' => 0, 'stopped' => 0];
$roleCounts = $roleCounts ?? [];
$status = $status ?? 'active';
$role = $role ?? '';
$q = $q ?? '';
$me = (int) (current_user()['id'] ?? 0);
$roleIcons = [
    'salesperson' => 'bi-briefcase-fill',
    'manager' => 'bi-diagram-3-fill',
    'admin' => 'bi-shield-lock-fill',
    'marketing' => 'bi-megaphone-fill',
    'service' => 'bi-tools',
];
$filterUrl = static function (string $st, string $rl) use ($q): string {
    $qs = [];
    if ($st !== 'active') {
        $qs['status'] = $st;
    }
    if ($rl !== '') {
        $qs['role'] = $rl;
    }
    if ($q !== '') {
        $qs['q'] = $q;
    }
    return url('users') . ($qs ? '?' . http_build_query($qs) : '');
};
$kpis = [
    [(string) (int) $counts['all'], 'People', 'bi-people-fill', '#2563eb', '#eff6ff', 'active', ''],
    [(string) (int) $counts['active'], 'Can log in', 'bi-person-check-fill', '#16a34a', '#f0fdf4', 'active', ''],
    [(string) (int) $counts['stopped'], 'Stopped', 'bi-person-x-fill', '#dc2626', '#fef2f2', 'stopped', ''],
    [(string) count($roles), 'Roles', 'bi-shield-check', '#7c3aed', '#f3e8ff', null, url('roles')],
];
$chips = [
    ['active', '', 'Active', (int) $counts['active']],
    ['stopped', '', 'Stopped', (int) $counts['stopped']],
];
foreach ($roles as $r) {
    $chips[] = [$status, (string) $r['code'], (string) $r['name'], (int) ($roleCounts[$r['code']] ?? 0)];
}
?>
<div class="usr-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Users</h1>
      <p class="page-sub mb-0">Add people and pick their role. Stop a login when someone leaves.</p>
    </div>
    <form class="task-search" method="get">
      <?php if ($status !== 'active'): ?><input type="hidden" name="status" value="<?= e($status) ?>"><?php endif; ?>
      <?php if ($role !== ''): ?><input type="hidden" name="role" value="<?= e($role) ?>"><?php endif; ?>
      <i class="bi bi-search"></i>
      <input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Search name or email">
    </form>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($kpis as $k): ?>
      <a class="task-summary-card <?= $k[5] && $status === $k[5] && $role === '' ? 'is-active' : '' ?>" href="<?= e($k[5] ? $filterUrl($k[5], '') : $k[6]) ?>" style="--task-accent: <?= e($k[3]) ?>; --task-tint: <?= e($k[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($k[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= e($k[0]) ?></div>
          <div class="task-summary-l"><?= e($k[1]) ?></div>
        </div>
      </a>
    <?php endforeach; ?>
  </div>

  <form class="camp-compose ajax-form mb-3" action="<?= e(url('users')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="camp-compose-head">
      <div class="task-summary-icon" style="--task-accent:#2563eb;--task-tint:#eff6ff"><i class="bi bi-person-plus-fill"></i></div>
      <div class="min-w-0">
        <div class="camp-compose-title">Add a person</div>
        <p class="camp-compose-sub mb-0">Pick at least one role. They sign in with this email and password.</p>
      </div>
    </div>
    <div class="usr-compose-grid">
      <div>
        <label class="form-label" for="usrFirst">First name</label>
        <input class="form-control" id="usrFirst" name="first_name" placeholder="Maya" required>
      </div>
      <div>
        <label class="form-label" for="usrLast">Last name</label>
        <input class="form-control" id="usrLast" name="last_name" placeholder="Chen" required>
      </div>
      <div>
        <label class="form-label" for="usrEmail">Email</label>
        <input class="form-control" id="usrEmail" type="email" name="email" placeholder="maya@company.com" required>
      </div>
      <div>
        <label class="form-label" for="usrPass">Password</label>
        <input class="form-control" id="usrPass" type="password" name="password" placeholder="At least 8 characters" required minlength="8">
      </div>
      <div class="usr-roles">
        <?php foreach ($roles as $r):
            $code = (string) $r['code'];
        ?>
          <label class="usr-role">
            <input class="visually-hidden" type="checkbox" name="role_ids[]" value="<?= (int) $r['id'] ?>">
            <i class="bi <?= e($roleIcons[$code] ?? 'bi-person-fill') ?>"></i>
            <span><?= e($r['name']) ?></span>
          </label>
        <?php endforeach; ?>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Add user</button>
  </form>

  <div class="task-toolbar mb-3">
    <div class="task-chips">
      <?php foreach ($chips as $c):
          $on = $status === $c[0] && $role === $c[1];
      ?>
        <a class="task-chip <?= $on ? 'active' : '' ?>" href="<?= e($filterUrl($c[0], $c[1])) ?>">
          <?= e($c[2]) ?>
          <span><?= (int) $c[3] ?></span>
        </a>
      <?php endforeach; ?>
    </div>
  </div>

  <?php if (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-person-plus"></i></div>
      <h2><?= $q !== '' || $status !== 'active' || $role !== '' ? 'No people in this view' : 'No people yet' ?></h2>
      <p><?= $q !== '' || $status !== 'active' || $role !== '' ? 'Try another filter or clear the search.' : 'Add someone above and pick a role so they can sign in.' ?></p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $r):
        $name = trim($r['first_name'] . ' ' . $r['last_name']);
        $on = (($r['login_status'] ?? $r['status'] ?? '') === 'active');
        $isMe = (int) $r['id'] === $me;
        $names = array_filter(array_map('trim', explode(',', (string) ($r['role_names'] ?? ''))));
        $have = array_filter(array_map('trim', explode(',', (string) ($r['role_codes'] ?? ''))));
        $eid = (int) $r['id'];
    ?>
      <div class="usr-card <?= $on ? '' : 'is-off' ?>">
        <div class="adm-person">
          <div class="lead-avatar"><?= e(name_initials($name)) ?></div>
          <div class="flex-grow-1 min-w-0">
            <div class="lead-name">
              <?= e($name !== '' ? $name : 'Untitled') ?>
              <?php if ($isMe): ?><span class="lst-chip lst-chip-open">You</span><?php endif; ?>
            </div>
            <div class="lead-sub">
              <span><?= e($r['email']) ?></span>
              <?php foreach ($names as $rn): ?>
                <span class="lst-chip"><?= e($rn) ?></span>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="task-meta usr-meta">
            <span class="lst-chip <?= $on ? 'lst-chip-open' : 'unsub-src-manual' ?>"><?= $on ? 'Active' : 'Stopped' ?></span>
            <span class="lead-date"><?= e(!empty($r['last_login_at']) ? relative_when($r['last_login_at']) : 'Never') ?></span>
            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#usrEdit<?= $eid ?>" aria-expanded="false">Edit</button>
            <?php if ($isMe): ?>
              <span class="usr-you">That’s you</span>
            <?php else: ?>
              <form class="ajax-form" action="<?= e(url('users/' . $eid . '/toggle')) ?>" method="post">
                <?= csrf_field() ?>
                <input type="hidden" name="active" value="<?= $on ? '0' : '1' ?>">
                <button class="btn btn-sm <?= $on ? 'btn-outline-danger' : 'btn-outline-primary' ?>" type="submit"><?= $on ? 'Stop login' : 'Allow login' ?></button>
              </form>
            <?php endif; ?>
          </div>
        </div>
        <div class="collapse usr-edit" id="usrEdit<?= $eid ?>">
          <form class="ajax-form" action="<?= e(url('users/' . $eid)) ?>" method="post">
            <?= csrf_field() ?>
            <div class="usr-compose-grid mb-0">
              <div>
                <label class="form-label" for="usrFirst<?= $eid ?>">First name</label>
                <input class="form-control" id="usrFirst<?= $eid ?>" name="first_name" value="<?= e($r['first_name']) ?>" required>
              </div>
              <div>
                <label class="form-label" for="usrLast<?= $eid ?>">Last name</label>
                <input class="form-control" id="usrLast<?= $eid ?>" name="last_name" value="<?= e($r['last_name']) ?>" required>
              </div>
              <div>
                <label class="form-label" for="usrEmail<?= $eid ?>">Email</label>
                <input class="form-control" id="usrEmail<?= $eid ?>" type="email" name="email" value="<?= e($r['email']) ?>" required>
              </div>
              <div>
                <label class="form-label" for="usrPass<?= $eid ?>">New password</label>
                <input class="form-control" id="usrPass<?= $eid ?>" type="password" name="password" placeholder="Leave blank to keep" minlength="8">
              </div>
              <div class="usr-roles">
                <?php foreach ($roles as $roleRow):
                    $code = (string) $roleRow['code'];
                ?>
                  <label class="usr-role">
                    <input class="visually-hidden" type="checkbox" name="role_ids[]" value="<?= (int) $roleRow['id'] ?>" <?= in_array($code, $have, true) ? 'checked' : '' ?>>
                    <i class="bi <?= e($roleIcons[$code] ?? 'bi-person-fill') ?>"></i>
                    <span><?= e($roleRow['name']) ?></span>
                  </label>
                <?php endforeach; ?>
              </div>
            </div>
            <button class="btn btn-primary mt-3" type="submit">Save changes</button>
          </form>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
