<?php
global $db, $config;

$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');

$q = trim((string)($_GET['q'] ?? ''));

$sql = "SELECT * FROM users";
$params = [];

if ($q !== '') {
  $sql .= " WHERE (
    full_name LIKE ?
    OR email LIKE ?
    OR phone LIKE ?
  )";
  $like = '%' . $q . '%';
  $params = [$like, $like, $like];
}

$sql .= " ORDER BY id DESC LIMIT 300";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

/* KPI stats */
$totalUsers = 0;
$activeUsers = 0;
$inactiveUsers = 0;

foreach ($rows as $r) {
  $totalUsers++;
  if ((int)$r['is_active'] === 1) $activeUsers++;
  else $inactiveUsers++;
}

$activeLast7Days = 0;
try {
  $st = $db->query("
    SELECT COUNT(*) c
    FROM users
    WHERE last_login_at IS NOT NULL
      AND last_login_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
  ");
  $activeLast7Days = (int)($st->fetch()['c'] ?? 0);
} catch (Throwable $e) {
  $activeLast7Days = 0;
}

?>

<style>

.users-hero{
  background:
    radial-gradient(circle at top right, rgba(249,115,22,0.18), transparent 35%),
    linear-gradient(180deg,#fff,#fffaf5);
  border:1px solid rgba(249,115,22,0.18);
  box-shadow:0 18px 55px rgba(15,23,42,0.06);
}

.users-kpi{
  background:#fff;
  border:1px solid rgba(249,115,22,0.15);
  box-shadow:0 10px 30px rgba(15,23,42,0.05);
  transition:.18s;
}

.users-kpi:hover{
  transform:translateY(-2px);
  box-shadow:0 16px 40px rgba(15,23,42,0.08);
}

.kpi-icon{
  width:40px;
  height:40px;
  border-radius:999px;
  display:grid;
  place-items:center;
  background:#fff7ed;
  border:1px solid #fdba74;
  font-size:18px;
}

.users-card{
  background:#fff;
  border:1px solid rgba(15,23,42,0.08);
  box-shadow:0 12px 38px rgba(15,23,42,0.06);
}

.users-head{
  background:linear-gradient(90deg,#fff7ed,#fff);
}

.users-row:hover{
  background:#fff7ed;
}

.status-pill{
  padding:4px 10px;
  border-radius:999px;
  font-size:12px;
  font-weight:700;
}

.status-active{
  background:#ecfdf5;
  border:1px solid #a7f3d0;
  color:#047857;
}

.status-inactive{
  background:#f1f5f9;
  border:1px solid #cbd5e1;
  color:#475569;
}

.btn-soft-orange{
  background:#fff7ed;
  border:1px solid #fed7aa;
  color:#9a3412;
  font-weight:600;
}

.btn-soft-orange:hover{
  background:#ffedd5;
}

.btn-outline-neutral{
  border:1px solid #e2e8f0;
  background:#fff;
  font-weight:600;
}

.btn-outline-neutral:hover{
  background:#f8fafc;
}

.badge-admin{
  display:inline-flex;
  gap:6px;
  align-items:center;
  font-size:12px;
  font-weight:700;
  padding:6px 10px;
  border-radius:999px;
  background:#fff7ed;
  border:1px solid #fed7aa;
  color:#c2410c;
}

</style>

<!-- HERO HEADER -->
<div class="users-hero rounded-3xl p-6 mb-6">

  <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">

    <div>
      <div class="badge-admin mb-3">👤 USER ADMIN</div>

      <h1 class="text-3xl font-bold text-slate-900">Users</h1>

      <div class="text-sm text-slate-600 mt-1">
        Manage internal system users, update profiles, activate accounts and reset passwords.
      </div>
    </div>

    <div>
      <a class="btn-primary px-5 py-3 rounded-2xl transition"
         href="<?= h($basePath) ?>/users/new"
         data-nav>
        + New User
      </a>
    </div>

  </div>


  <!-- KPI TILES -->
  <div class="grid md:grid-cols-4 gap-3 mt-6">

    <div class="users-kpi rounded-2xl p-4">
      <div class="kpi-icon">👥</div>
      <div class="text-xs text-slate-500 mt-3">Total Users</div>
      <div class="text-2xl font-bold text-slate-900"><?= $totalUsers ?></div>
    </div>

    <div class="users-kpi rounded-2xl p-4">
      <div class="kpi-icon">✅</div>
      <div class="text-xs text-slate-500 mt-3">Active Users</div>
      <div class="text-2xl font-bold text-slate-900"><?= $activeUsers ?></div>
    </div>

    <div class="users-kpi rounded-2xl p-4">
      <div class="kpi-icon">⏸</div>
      <div class="text-xs text-slate-500 mt-3">Inactive Users</div>
      <div class="text-2xl font-bold text-slate-900"><?= $inactiveUsers ?></div>
    </div>

    <div class="users-kpi rounded-2xl p-4">
        <div class="kpi-icon">📈</div>
        <div class="text-xs text-slate-500 mt-3">Logged In (7 Days)</div>
        <div class="text-2xl font-bold text-slate-900"><?= $activeLast7Days ?></div>
    </div>

  </div>

</div>



<!-- SEARCH -->
<div class="glass rounded-3xl p-5 mb-5">

  <form class="grid md:grid-cols-6 gap-3"
        onsubmit="event.preventDefault();
        const q=this.q.value.trim();
        const base=<?= json_encode($basePath) ?>;
        const url=(base?base:'')+'/users'+(q?('?q='+encodeURIComponent(q)):'');
        window.loadPartial?loadPartial(url,true):(location.href=url);">

    <div class="md:col-span-5">
      <label class="form-label">Search Users</label>

      <input name="q"
        value="<?= h($q) ?>"
        class="mt-1 w-full px-4 py-3 rounded-2xl border border-slate-200 bg-white outline-none focus:ring-2 focus:ring-orange-300"
        placeholder="Search by name, email, or phone">
    </div>

    <div class="flex items-end">
      <button class="w-full px-4 py-3 rounded-2xl btn-soft-orange transition">
        Search
      </button>
    </div>

  </form>

</div>



<!-- USERS TABLE -->
<div class="users-card rounded-3xl overflow-hidden">

<div class="overflow-x-auto">

<table class="w-full text-sm">

<thead class="users-head">
<tr>
<th class="p-3">User</th>
<th class="p-3">Email</th>
<th class="p-3">Phone</th>
<th class="p-3">Status</th>
<th class="p-3">Created</th>
<th class="p-3">Actions</th>
</tr>
</thead>

<tbody>

<?php foreach ($rows as $r): ?>

<tr class="border-t users-row">

<td class="p-3">
<div class="font-semibold"><?= h($r['full_name']) ?></div>
<div class="text-xs text-orange-600">User ID #<?= $r['id'] ?></div>
</td>

<td class="p-3"><?= h($r['email']) ?></td>

<td class="p-3"><?= h($r['phone'] ?: '—') ?></td>

<td class="p-3">
<?php if ($r['is_active']): ?>
<span class="status-pill status-active">Active</span>
<?php else: ?>
<span class="status-pill status-inactive">Inactive</span>
<?php endif; ?>
</td>

<td class="p-3 text-slate-500"><?= h($r['created_at']) ?></td>

<td class="p-3">

<div class="flex gap-2 flex-wrap">

<a class="px-3 py-2 rounded-2xl btn-outline-neutral"
   href="<?= h($basePath) ?>/users/edit?id=<?= $r['id'] ?>"
   data-nav>
Edit
</a>

<button
class="px-3 py-2 rounded-2xl btn-soft-orange"
data-action="toggle-user"
data-id="<?= $r['id'] ?>"
data-next="<?= $r['is_active']?0:1 ?>">
<?= $r['is_active']?'Deactivate':'Activate' ?>
</button>

<button
class="px-3 py-2 rounded-2xl bg-white border border-slate-200 hover:bg-slate-100"
data-action="reset-user-password"
data-id="<?= $r['id'] ?>"
data-name="<?= h($r['full_name']) ?>">
Reset Password
</button>

</div>

</td>

</tr>

<?php endforeach; ?>

<?php if (!$rows): ?>

<tr>
<td colspan="6" class="p-6 text-center text-slate-500">
No users found
</td>
</tr>

<?php endif; ?>

</tbody>
</table>

</div>
</div>