<?php
include('../config/db.php');
include('../includes/auth.php');
require_once '../includes/csrf.php';
require_once '../includes/voucher_helpers.php';

$isAdmin = is_admin_role();
$flash = ''; $flashType = 'success';
if (isset($_GET['added'])) { $flash = 'User added successfully.'; $flashType = 'success'; }
$search  = trim($_GET['q'] ?? '');

// Handle POST actions (release, revoke, bulk_release, bulk_revoke, delete_customer)
require_once 'handlers/vouchers_handler.php';

// HTML output starts here
include('partials/header.php');

// ── Pagination & search ───────────────────────────────────────────────────────
$limit   = 15;
$page    = max(1, (int)($_GET['page'] ?? 1));

$where  = ['1=1'];
$params = [];
$types  = '';
if ($search !== '') {
    $where[]  = '(c.name LIKE ? OR c.phone LIKE ?)';
    $like     = '%' . $search . '%';
    $params   = [$like, $like];
    $types   .= 'ss';
}
$whereSQL = implode(' AND ', $where);

$cntQ = $conn->prepare("SELECT COUNT(*) c FROM customers c WHERE $whereSQL");
if ($types) $cntQ->bind_param($types, ...$params);
$cntQ->execute();
$cntQ->store_result();
$cntQ->bind_result($totalRows);
$cntQ->fetch();
$cntQ->close();
$totalRows = (int)$totalRows;
$totalPgs  = max(1, (int)ceil($totalRows / $limit));
$page      = min($page, $totalPgs);
$offset    = ($page - 1) * $limit;

// Fetch customers with their claim summary — store all rows eagerly
$custQ = $conn->prepare("
  SELECT c.id, c.name, c.phone, c.created_at,
         COUNT(vc.id) AS total_claims,
         SUM(vc.status='redeemed') AS redeemed,
         SUM(vc.status='claimed')  AS pending
  FROM customers c
  LEFT JOIN voucher_claims vc ON vc.customer_id = c.id
  WHERE $whereSQL
  GROUP BY c.id
  ORDER BY c.id DESC
  LIMIT $limit OFFSET $offset
");
if ($types) $custQ->bind_param($types, ...$params);
$custQ->execute();
$res = $custQ->get_result();
$customers = [];
while ($row = $res->fetch_assoc()) $customers[] = $row;
$custQ->close();

// Release dropdown: only show PRIVATE vouchers that are templates (not clones)
// Public vouchers are auto-claimed — no need to manually release them
// Clones are identified as private vouchers that have claims already (they were generated per-user)
// Templates are private vouchers with no claims yet OR created directly as private
$res2 = $conn->query("
  SELECT v.id, v.event_name, v.type, v.max_per_user, v.end_date, v.is_public,
         COUNT(vc.id) AS total_claims
  FROM vouchers v
  LEFT JOIN voucher_claims vc ON vc.voucher_id = v.id
  WHERE v.is_public = 0
    AND v.parent_voucher_id IS NULL
    AND (v.end_date >= CURDATE() OR v.end_date = '0000-00-00' OR v.end_date IS NULL)
  GROUP BY v.id
  HAVING total_claims = 0
  ORDER BY v.event_name
");
$voucherList = [];
while ($vr = $res2->fetch_assoc()) $voucherList[] = $vr;
$res2->free();

// Selected customer detail (for the sidebar panel)
$selectedId = (int)($_GET['uid'] ?? $_POST['uid'] ?? 0);
$selCust = null; $selClaims = []; $claimCountByVoucher = [];
if ($selectedId) {
    $sq = $conn->prepare('SELECT * FROM customers WHERE id=?');
    $sq->bind_param('i', $selectedId);
    $sq->execute();
    $sqRes = $sq->get_result();
    $selCust = $sqRes->fetch_assoc();
    $sqRes->free();
    $sq->close();

    if ($selCust) {
        $clQ = $conn->prepare("
            SELECT vc.id AS claim_id, vc.status, vc.claimed_at, vc.redeemed_at,
                   v.event_name, v.type, v.code, v.end_date, v.max_per_user, v.id AS voucher_id
            FROM voucher_claims vc
            JOIN vouchers v ON vc.voucher_id = v.id
            WHERE vc.customer_id = ?
            ORDER BY vc.id DESC
        ");
        $clQ->bind_param('i', $selectedId);
        $clQ->execute();
        $clRes = $clQ->get_result();
        while ($cl = $clRes->fetch_assoc()) {
            $selClaims[] = $cl;
            $claimCountByVoucher[$cl['voucher_id']] = ($claimCountByVoucher[$cl['voucher_id']] ?? 0) + 1;
        }
        $clRes->free();
        $clQ->close();
    }
}

$selRedeemed = 0;
$selPending  = 0;
foreach ($selClaims as $cl) {
    if ($cl['status'] === 'redeemed') {
        $selRedeemed++;
    } elseif ($cl['status'] === 'claimed') {
        $selPending++;
    }
}
?>

<?php if ($flash): ?>
<div class="adm-alert adm-alert-<?= $flashType === 'error' ? 'danger' : 'success' ?>" style="margin-bottom:18px">
  <i class="bi bi-<?= $flashType === 'error' ? 'exclamation-circle-fill' : 'check-circle-fill' ?>"></i>
  <?= htmlspecialchars($flash) ?>
</div>
<?php endif; ?>

<div class="pg-title">Users</div>
<div class="pg-sub">Customer accounts &amp; voucher management</div>

<?php if ($isAdmin): ?>
<!-- Bulk Release Panel -->
<div class="adm-card mb-4" style="padding:0;overflow:hidden" id="bulk-release-panel" style="display:none">
  <div class="adm-card-header">
    <span><i class="bi bi-gift-fill" style="color:var(--green)"></i> Bulk Release Voucher</span>
    <span id="bulk-sel-count" style="font-size:12px;color:var(--muted)">Select users below using checkboxes</span>
  </div>
  <div style="padding:16px">
    <form method="POST" id="bulk-release-form">
      <?php csrf_field(); ?>
      <input type="hidden" name="action" value="bulk_release">
      <div id="bulk-hidden-ids"></div>
      <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
        <div style="flex:1;min-width:200px">
          <label class="frm-label">Voucher to release</label>
          <select name="voucher_id" class="frm-ctrl" required>
            <option value="">— Select private voucher —</option>
            <?php if(empty($voucherList)): ?>
            <option disabled>No private vouchers available</option>
            <?php else: foreach ($voucherList as $vl): ?>
            <option value="<?= $vl['id'] ?>">
              ⭐ <?= htmlspecialchars($vl['event_name']) ?><?= $vl['type'] ? ' — '.htmlspecialchars($vl['type']) : '' ?>
              <?php if($vl['end_date'] && $vl['end_date'] !== '0000-00-00'): ?>
              · Expires <?= date('d M Y', strtotime($vl['end_date'])) ?>
              <?php endif; ?>
            </option>
            <?php endforeach; endif; ?>
          </select>
        </div>
        <button type="button" onclick="submitBulkRelease()" class="btn-success" style="padding:9px 18px" id="bulk-release-btn" disabled>
          <i class="bi bi-gift"></i> Release to <span id="bulk-btn-count">0</span> users
        </button>
        <button type="button" onclick="clearBulkSel()" class="btn-ghost" style="padding:9px 14px">
          <i class="bi bi-x"></i> Clear
        </button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="row g-4">

  <!-- ── LEFT: Customer list ── -->
  <div class="col-md-<?= $selectedId ? '5' : '12' ?>">

    <!-- Search -->
    <form method="GET" style="display:flex;gap:8px;margin-bottom:16px">
      <?php if ($selectedId): ?><input type="hidden" name="uid" value="<?= $selectedId ?>"><?php endif; ?>
      <input type="text" name="q" class="frm-ctrl" placeholder="Search name or phone…" value="<?= htmlspecialchars($search) ?>" style="flex:1">
      <button class="btn-accent" style="padding:9px 16px"><i class="bi bi-search"></i></button>
      <?php if ($search): ?><a href="users.php<?= $selectedId ? '?uid='.$selectedId : '' ?>" class="btn-ghost" style="padding:9px 14px"><i class="bi bi-x"></i></a><?php endif; ?>
    </form>

    <div class="adm-card" style="padding:0;overflow:hidden">
      <div class="adm-card-header">
        <span><?= number_format($totalRows) ?> Users</span>
        <div style="display:flex;align-items:center;gap:10px">
          <?php if ($isAdmin): ?>
          <button onclick="openAddUser()" class="btn-accent" style="padding:5px 12px;font-size:12px;display:flex;align-items:center;gap:5px">
            <i class="bi bi-person-plus-fill"></i> Add User
          </button>
          <?php endif; ?>
          <label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);cursor:pointer;font-weight:600">
            <input type="checkbox" id="usr-sel-all" onchange="toggleAllUsers(this)" style="width:15px;height:15px;accent-color:var(--accent)"> Select all
          </label>
        </div>
      </div>
      <div class="table-responsive">
      <table class="adm-table">
        <thead>
          <tr>
            <th style="width:36px"></th>
            <th>Customer</th>
            <th>Claims</th>
            <th class="d-none d-lg-table-cell">Joined</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($customers as $cu):
          $isSelected = $cu['id'] === $selectedId;
          $qStr = $search ? '&q=' . urlencode($search) : '';
        ?>
        <tr style="<?= $isSelected ? 'background:var(--accent-dim)' : '' ?>">
          <td onclick="event.stopPropagation()">
            <input type="checkbox" class="usr-sel" data-id="<?= $cu['id'] ?>"
                   style="width:15px;height:15px;accent-color:var(--accent);cursor:pointer"
                   onchange="updateUserBulkBar()">
          </td>
          <td style="cursor:pointer" onclick="window.location='users.php?uid=<?= $cu['id'] . $qStr . ($page > 1 ? '&page='.$page : '') ?>'">
            <div style="font-weight:600;<?= $isSelected ? 'color:var(--accent)' : '' ?>"><?= htmlspecialchars($cu['name']) ?></div>
            <div style="font-size:11.5px;color:var(--muted);font-family:var(--mono)"><?= htmlspecialchars($cu['phone']) ?></div>
          </td>
          <td>
            <div style="display:flex;gap:5px;flex-wrap:wrap">
              <?php if ($cu['total_claims'] > 0): ?>
                <span class="badge-active" style="font-size:10px"><?= $cu['redeemed'] ?> used</span>
                <?php if ($cu['pending'] > 0): ?>
                <span class="badge-pending" style="font-size:10px"><?= $cu['pending'] ?> pending</span>
                <?php endif; ?>
              <?php else: ?>
                <span style="font-size:11.5px;color:var(--muted)">No claims</span>
              <?php endif; ?>
            </div>
          </td>
          <td class="d-none d-lg-table-cell" style="font-size:12px;color:var(--muted)"><?= date('d M Y', strtotime($cu['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      </div>
      <!-- Pagination -->
      <?php if ($totalPgs > 1): ?>
      <div class="pg-bar">
        <span>Page <?= $page ?> of <?= $totalPgs ?></span>
        <div class="pg-nums">
          <?php
          $base = 'users.php?';
          if ($search) $base .= 'q=' . urlencode($search) . '&';
          if ($selectedId) $base .= 'uid=' . $selectedId . '&';
          $base .= 'page=';
          for ($p = max(1,$page-2); $p <= min($totalPgs,$page+2); $p++):
          ?>
          <a href="<?= $base . $p ?>" class="pg-num <?= $p===$page?'active':'' ?>"><?= $p ?></a>
          <?php endfor; ?>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- ── RIGHT: User detail panel ── -->
  <?php if ($selectedId && $selCust): ?>
  <div class="col-md-7">

    <!-- User Card -->
    <div class="adm-card mb-3" style="padding:18px 20px">
      <div style="display:flex;align-items:center;gap:14px;margin-bottom:14px">
        <div style="width:44px;height:44px;border-radius:50%;background:var(--accent-dim);border:2px solid var(--accent);display:grid;place-items:center;font-size:18px;font-weight:700;color:var(--accent);flex-shrink:0">
          <?= strtoupper(substr($selCust['name'],0,1)) ?>
        </div>
        <div>
          <div style="font-size:16px;font-weight:700"><?= htmlspecialchars($selCust['name']) ?></div>
          <div style="font-size:12px;color:var(--muted);font-family:var(--mono)"><?= htmlspecialchars($selCust['phone']) ?></div>
        </div>
        <div style="margin-left:auto;display:flex;gap:8px;align-items:center">
        <?php if ($isAdmin): ?>
        <form method="POST" onsubmit="return confirm('Delete this customer and all their voucher claims? This cannot be undone.');" style="margin:0">
          <?php csrf_field(); ?>
          <input type="hidden" name="action" value="delete_customer">
          <input type="hidden" name="customer_id" value="<?= (int)$selectedId ?>">
          <input type="hidden" name="search_q" value="<?= htmlspecialchars($search, ENT_QUOTES) ?>">
          <button type="submit" class="btn-danger" style="padding:6px 12px;font-size:12px">
            <i class="bi bi-trash"></i> Delete user
          </button>
        </form>
        <?php endif; ?>
        <a href="users.php<?= $search ? '?q='.urlencode($search) : '' ?>" class="btn-ghost" style="padding:6px 10px" title="Close">
          <i class="bi bi-x-lg"></i>
        </a>
        </div>
      </div>
      <div style="display:flex;gap:12px;flex-wrap:wrap">
        <div style="background:var(--bg);border-radius:8px;padding:10px 16px;flex:1;min-width:80px;text-align:center">
          <div style="font-family:var(--mono);font-size:20px;font-weight:700;color:var(--blue)"><?= count($selClaims) ?></div>
          <div style="font-size:10.5px;color:var(--muted);margin-top:2px">TOTAL CLAIMS</div>
        </div>
        <div style="background:var(--bg);border-radius:8px;padding:10px 16px;flex:1;min-width:80px;text-align:center">
          <div style="font-family:var(--mono);font-size:20px;font-weight:700;color:var(--green)"><?= $selRedeemed ?></div>
          <div style="font-size:10.5px;color:var(--muted);margin-top:2px">REDEEMED</div>
        </div>
        <div style="background:var(--bg);border-radius:8px;padding:10px 16px;flex:1;min-width:80px;text-align:center">
          <div style="font-family:var(--mono);font-size:20px;font-weight:700;color:var(--yellow)"><?= $selPending ?></div>
          <div style="font-size:10.5px;color:var(--muted);margin-top:2px">PENDING</div>
        </div>
      </div>
    </div>

    <?php if ($isAdmin): ?>
    <!-- Release Voucher Form -->
    <div class="adm-card mb-3" style="padding:0;overflow:hidden">
      <div class="adm-card-header">
        <span><i class="bi bi-gift-fill" style="color:var(--green)"></i> Release a Voucher</span>
      </div>
      <div style="padding:18px">
        <?php if (empty($voucherList)): ?>
          <p style="color:var(--muted);font-size:13px">No active public vouchers available to release.</p>
        <?php else: ?>
        <form method="POST" style="display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end">
          <?php csrf_field(); ?>
          <input type="hidden" name="action" value="release">
          <input type="hidden" name="customer_id" value="<?= $selectedId ?>">
          <div style="flex:1;min-width:200px">
            <label class="frm-label">Voucher</label>
            <select name="voucher_id" class="frm-ctrl" required>
              <option value="">— Select private voucher —</option>
              <?php if(empty($voucherList)): ?>
              <option disabled>No private vouchers available</option>
              <?php else: foreach ($voucherList as $vl): ?>
              <option value="<?= $vl['id'] ?>">
                ⭐ <?= htmlspecialchars($vl['event_name']) ?>
                <?= $vl['type'] ? ' — ' . htmlspecialchars($vl['type']) : '' ?>
                <?php if($vl['end_date'] && $vl['end_date'] !== '0000-00-00'): ?>
                · Expires <?= date('d M Y', strtotime($vl['end_date'])) ?>
                <?php endif; ?>
              </option>
              <?php endforeach; endif; ?>
            </select>
          </div>
          <button class="btn-success" style="padding:9px 18px;font-size:13px;white-space:nowrap">
            <i class="bi bi-gift"></i> Release
          </button>
        </form>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- User's Claims -->
    <div class="adm-card" style="padding:0;overflow:hidden">
      <div class="adm-card-header" style="justify-content:space-between;align-items:center">
        <span>Claim History</span>
        <?php if ($isAdmin && !empty($selClaims)): ?>
        <div style="display:flex;gap:8px;align-items:center">
          <label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);cursor:pointer;font-weight:600">
            <input type="checkbox" id="cl-sel-all" onchange="toggleAllClaims(this)" style="width:14px;height:14px;accent-color:var(--accent)"> Select all
          </label>
          <button onclick="submitBulkRevoke()" id="bulk-revoke-btn" class="btn-danger" style="padding:5px 12px;font-size:11px;display:none">
            <i class="bi bi-slash-circle"></i> Revoke selected
          </button>
        </div>
        <?php endif; ?>
      </div>
      <?php if (empty($selClaims)): ?>
        <div style="padding:28px;text-align:center;color:var(--muted);font-size:13px">
          <i class="bi bi-ticket" style="font-size:28px;display:block;margin-bottom:8px;opacity:.4"></i>
          No vouchers claimed yet.
        </div>
      <?php else: ?>
      <?php if ($isAdmin): ?>
      <form method="POST" id="bulk-revoke-form" style="display:none">
        <?php csrf_field(); ?>
        <input type="hidden" name="action" value="bulk_revoke">
        <input type="hidden" name="uid" value="<?= $selectedId ?>">
        <div id="bulk-revoke-ids"></div>
      </form>
      <?php endif; ?>
      <div class="table-responsive">
      <table class="adm-table">
        <thead>
          <tr>
            <?php if ($isAdmin): ?><th style="width:32px"></th><?php endif; ?>
            <th>Voucher</th><th>Status</th><th>Code</th><th>Action</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($selClaims as $cl):
          $isRed = $cl['status'] === 'redeemed';
          $isExp = $cl['end_date'] < date('Y-m-d');
        ?>
        <tr>
          <?php if ($isAdmin): ?>
          <td onclick="event.stopPropagation()">
            <input type="checkbox" class="cl-sel" data-id="<?= $cl['claim_id'] ?>"
                   style="width:14px;height:14px;accent-color:var(--accent);cursor:pointer"
                   onchange="updateClaimBulkBar()">
          </td>
          <?php endif; ?>
          <td>
            <div style="font-weight:600;font-size:13px"><?= htmlspecialchars($cl['event_name']) ?></div>
            <?php if ($cl['type']): ?><div style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($cl['type']) ?></div><?php endif; ?>
            <div style="font-size:10.5px;color:var(--muted);margin-top:2px"><?= date('d M, H:i', strtotime($cl['claimed_at'])) ?></div>
          </td>
          <td>
            <?php if ($isRed): ?>
              <span class="badge-redeemed"><i class="bi bi-check-circle-fill"></i> Redeemed</span>
              <?php if ($cl['redeemed_at']): ?>
              <div style="font-size:10.5px;color:var(--muted);margin-top:3px"><?= date('d M, H:i', strtotime($cl['redeemed_at'])) ?></div>
              <?php endif; ?>
            <?php elseif ($isExp): ?>
              <span class="badge-expired"><i class="bi bi-clock"></i> Expired</span>
            <?php else: ?>
              <span class="badge-pending"><i class="bi bi-hourglass"></i> Pending</span>
            <?php endif; ?>
          </td>
          <td style="font-family:var(--mono);font-size:11px;color:var(--accent)"><?= htmlspecialchars($cl['code']) ?></td>
          <td>
            <?php if ($isAdmin): ?>
            <?php $confirmMsg = $isRed
              ? 'Revoke this REDEEMED claim? The voucher will be hidden and the claim deleted.'
              : 'Revoke this pending claim? The voucher will be hidden.'; ?>
            <form method="POST" onsubmit="return confirm('<?= htmlspecialchars($confirmMsg, ENT_QUOTES) ?>')">
              <?php csrf_field(); ?>
              <input type="hidden" name="action" value="revoke">
              <input type="hidden" name="claim_id" value="<?= $cl['claim_id'] ?>">
              <input type="hidden" name="uid" value="<?= $selectedId ?>">
              <button class="btn-danger" style="padding:5px 10px;font-size:11px">
                <i class="bi bi-slash-circle"></i> Revoke
              </button>
            </form>
            <?php else: ?>
              <span style="font-size:11px;color:var(--muted)">—</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      </div>
      <?php endif; ?>
    </div>

  </div>
  <?php endif; ?>
</div>

<!-- Add User Modal -->
<div id="add-user-overlay" onclick="closeAddUser()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1040"></div>
<div id="add-user-modal" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1050;width:min(420px,92vw);background:var(--card);border:1px solid var(--border);border-radius:14px;box-shadow:0 8px 32px rgba(0,0,0,.4)">
  <div style="padding:16px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
    <div style="font-size:15px;font-weight:700;display:flex;align-items:center;gap:8px">
      <i class="bi bi-person-plus-fill" style="color:var(--accent)"></i> Add New User
    </div>
    <button onclick="closeAddUser()" style="background:none;border:none;color:var(--muted);font-size:22px;cursor:pointer;line-height:1;padding:4px"><i class="bi bi-x"></i></button>
  </div>
  <form method="POST" id="add-user-form" onsubmit="return validateAddUser()">
    <?php csrf_field(); ?>
    <input type="hidden" name="action" value="add_customer">
    <div style="padding:18px;display:flex;flex-direction:column;gap:14px">
      <div>
        <label class="frm-label">Full Name <span style="color:#e05252">*</span></label>
        <input type="text" name="new_name" id="au-name" class="frm-ctrl" placeholder="e.g. Ahmad Razif" maxlength="100" autocomplete="off">
      </div>
      <div>
        <label class="frm-label">Phone Number <span style="color:#e05252">*</span></label>
        <div style="display:flex;gap:8px">
          <select name="new_dial" id="au-dial" class="frm-ctrl" style="width:110px;flex-shrink:0">
            <option value="60">🇲🇾 +60</option>
            <option value="65">🇸🇬 +65</option>
            <option value="673">🇧🇳 +673</option>
            <option value="62">🇮🇩 +62</option>
            <option value="66">🇹🇭 +66</option>
            <option value="44">🇬🇧 +44</option>
            <option value="1">🇺🇸 +1</option>
          </select>
          <input type="tel" name="new_phone" id="au-phone" class="frm-ctrl" placeholder="123456789" maxlength="15" autocomplete="off" style="flex:1">
        </div>
        <div style="font-size:11px;color:var(--muted);margin-top:4px"><i class="bi bi-info-circle"></i> Enter without leading zero — e.g. 123456789</div>
      </div>
    </div>
    <div style="padding:14px 18px;border-top:1px solid var(--border);display:flex;gap:8px;justify-content:flex-end">
      <button type="button" onclick="closeAddUser()" class="btn-ghost" style="padding:9px 16px">Cancel</button>
      <button type="submit" class="btn-success" style="padding:9px 20px;display:flex;align-items:center;gap:6px">
        <i class="bi bi-person-check-fill"></i> Add User
      </button>
    </div>
  </form>
</div>

<script>
function openAddUser() {
  document.getElementById('add-user-modal').style.display   = 'block';
  document.getElementById('add-user-overlay').style.display = 'block';
  document.getElementById('au-name').focus();
}
function closeAddUser() {
  document.getElementById('add-user-modal').style.display   = 'none';
  document.getElementById('add-user-overlay').style.display = 'none';
  document.getElementById('au-name').value  = '';
  document.getElementById('au-phone').value = '';
}
function validateAddUser() {
  const name  = document.getElementById('au-name').value.trim();
  const phone = document.getElementById('au-phone').value.replace(/\D/g,'');
  if (!name)               { showToast('Name is required.', 'error'); return false; }
  if (phone.length < 7)    { showToast('Phone number is too short.', 'error'); return false; }
  if (phone.length > 15)   { showToast('Phone number is too long.', 'error'); return false; }
  return true;
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAddUser(); });
</script>

<script src="assets/bulk-actions.js?v=1"></script>

<?php include('partials/footer.php'); ?>
