<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';

$db = getDB();
$adminUserName = $_SESSION['user_name'];
$adminPage     = 'customers';
$adminPageTitle= 'Customers';

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

if($search){
    $stmt = $db->prepare("SELECT u.id,u.name,u.email,u.phone,u.address,u.is_active,u.created_at,COUNT(o.id) AS order_count,COALESCE(SUM(o.total),0) AS total_spent FROM users u LEFT JOIN orders o ON u.id=o.user_id WHERE u.role='customer' AND (u.name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?) GROUP BY u.id ORDER BY u.created_at DESC");
    $like = "%$search%";
    $stmt->execute([$like,$like,$like]);
} else {
    $stmt = $db->query("SELECT u.id,u.name,u.email,u.phone,u.address,u.is_active,u.created_at,COUNT(o.id) AS order_count,COALESCE(SUM(o.total),0) AS total_spent FROM users u LEFT JOIN orders o ON u.id=o.user_id WHERE u.role='customer' GROUP BY u.id ORDER BY u.created_at DESC");
}
$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php require_once __DIR__ . '/layout_top.php'; ?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.75rem;flex-wrap:wrap;gap:1rem">
  <div>
    <h1 style="font-weight:900;font-size:1.4rem;color:#0f172a;margin:0 0 .2rem" id="customerCount"><?= count($customers) ?> Customers</h1>
    <p style="color:#64748b;font-size:.85rem;margin:0">All registered customer accounts</p>
  </div>
  <!-- Live search -->
  <div style="position:relative">
    <div style="position:absolute;left:13px;top:50%;transform:translateY(-50%);pointer-events:none">
      <svg width="16" height="16" fill="none" stroke="#94a3b8" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    </div>
    <input type="text" id="customerSearch" placeholder="Search name or email…"
      value="<?= htmlspecialchars($search) ?>"
      style="font-family:inherit;font-size:.875rem;padding:.65rem 1rem .65rem 2.4rem;border:2px solid #e2e8f0;border-radius:12px;outline:none;width:260px;transition:border-color .2s"
      onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'"
      oninput="filterCustomers(this.value)">
  </div>
</div>

<div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden">
  <?php if(empty($customers)): ?>
  <div style="text-align:center;padding:4rem;color:#94a3b8">
    <div style="font-size:48px;margin-bottom:1rem;opacity:.25">👥</div>
    <p>No customers found.</p>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
    <table style="width:100%;border-collapse:collapse">
      <thead>
        <tr style="background:#f8f9fb">
          <?php foreach(['Customer','Email','Phone','Address','Orders','Spent','Joined','Status'] as $h): ?>
          <th style="padding:.85rem 1.25rem;text-align:left;font-size:.72rem;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em;white-space:nowrap"><?= $h ?></th>
          <?php endforeach; ?>
        </tr>
      </thead>
      <tbody id="customersTableBody">
        <?php foreach($customers as $c): ?>
        <tr style="border-top:1px solid #f1f5f9" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background=''">
          <td style="padding:.85rem 1.25rem">
            <div style="display:flex;align-items:center;gap:.75rem">
              <div style="width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#0f172a,#1e293b);display:flex;align-items:center;justify-content:center;color:#f97316;font-weight:800;font-size:.85rem;flex-shrink:0"><?= strtoupper(substr($c['name'],0,1)) ?></div>
              <span style="font-weight:700;font-size:.875rem;color:#0f172a"><?= htmlspecialchars($c['name']) ?></span>
            </div>
          </td>
          <td style="padding:.85rem 1.25rem;font-size:.82rem;color:#475569"><?= htmlspecialchars($c['email']) ?></td>
          <td style="padding:.85rem 1.25rem;font-size:.82rem;color:#64748b"><?= htmlspecialchars($c['phone']??'—') ?></td>
          <td style="padding:.85rem 1.25rem;max-width:160px">
            <?php if($c['address']??''): ?>
              <div style="font-size:.8rem;color:#475569;line-height:1.5"><?= htmlspecialchars($c['address']) ?></div>
            <?php else: ?>
              <span style="color:#cbd5e1;font-size:.8rem;font-style:italic">—</span>
            <?php endif; ?>
          </td>
          <td style="padding:.85rem 1.25rem;font-weight:700;font-size:.875rem;color:#0f172a;text-align:center"><?= $c['order_count'] ?></td>
          <td style="padding:.85rem 1.25rem;font-weight:700;color:#f97316">₦<?= number_format($c['total_spent']) ?></td>
          <td style="padding:.85rem 1.25rem;font-size:.82rem;color:#64748b;white-space:nowrap"><?= date('M j, Y', strtotime($c['created_at'])) ?></td>
          <td style="padding:.85rem 1.25rem">
            <span style="background:<?= $c['is_active']?'#f0fdf4':'#fef2f2' ?>;color:<?= $c['is_active']?'#16a34a':'#dc2626' ?>;border:1px solid <?= $c['is_active']?'#bbf7d0':'#fecaca' ?>;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px">
              <?= $c['is_active']?'Active':'Inactive' ?>
            </span>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<script>
function filterCustomers(q) {
  q = q.toLowerCase().trim();
  var rows = document.querySelectorAll('#customersTableBody tr');
  var visible = 0;
  rows.forEach(function(row) {
    var text = row.innerText.toLowerCase();
    var show = !q || text.indexOf(q) !== -1;
    row.style.display = show ? '' : 'none';
    if (show) visible++;
  });
  // Update count label
  var countEl = document.getElementById('customerCount');
  if (countEl) {
    countEl.textContent = (q ? visible + ' result' + (visible !== 1 ? 's' : '') : '<?= count($customers) ?> Customers');
  }
}
window.addEventListener('DOMContentLoaded', function() {
  var input = document.getElementById('customerSearch');
  if (input && input.value) filterCustomers(input.value);
});
</script>

<?php require_once __DIR__ . '/layout_bottom.php'; ?>
