<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db = getDB();
$customers = $db->query("SELECT c.*, (SELECT COUNT(*) FROM orders WHERE customer_id=c.id) AS order_count, (SELECT SUM(total) FROM orders WHERE customer_id=c.id) AS total_spent FROM customers c ORDER BY c.id DESC")->fetchAll();
$page_title = 'Customers';
include __DIR__ . '/header.php';
?>
<div class="card">
  <div class="card-header">
    <h2>All Customers (<?= count($customers) ?>)</h2>
  </div>
  <div class="table-wrap">
    <table>
      <thead><tr><th>#</th><th>Name</th><th>Email</th><th>Phone</th><th>City</th><th>Orders</th><th>Total Spent</th><th>Status</th><th>Joined</th></tr></thead>
      <tbody>
        <?php foreach ($customers as $c): ?>
        <tr>
          <td><?= $c['id'] ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:10px;">
              <div style="width:34px;height:34px;background:var(--blue-main);color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.85rem;"><?= strtoupper(substr($c['name'],0,1)) ?></div>
              <strong><?= h($c['name']) ?></strong>
            </div>
          </td>
          <td><?= h($c['email']) ?></td>
          <td><?= h($c['phone']) ?></td>
          <td><?= h($c['city']) ?></td>
          <td><span class="badge badge-new"><?= $c['order_count'] ?> orders</span></td>
          <td><strong><?= rupee($c['total_spent'] ?? 0) ?></strong></td>
          <td><span class="badge badge-<?= ($c['status']??'active')==='active'?'active':'inactive' ?>"><?= ucfirst($c['status']??'active') ?></span></td>
          <td><?= date('d M Y', strtotime($c['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
