<?php
require __DIR__ . '/_auth.php';
require_admin();
$title = 'Customers';
$pdo = db();
$rows = array();
if ($pdo) {
    try {
        $stmt = $pdo->query('SELECT c.*, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id OR o.customer_email = c.email) AS order_count, (SELECT COUNT(*) FROM reup_requests r WHERE r.customer_id = c.id OR r.customer_email = c.email) AS reup_count, (SELECT COUNT(*) FROM custom_sofa_quotes q WHERE q.customer_id = c.id OR q.customer_email = c.email) AS custom_count FROM customers c ORDER BY c.created_at DESC');
        $rows = $stmt->fetchAll();
    } catch (Exception $e) {}
}
require __DIR__ . '/_header.php';
?>
<?php if (!$pdo): ?>
<div class="admin-card p-4"><h1 class="h4">MySQL setup required</h1><p>Customer accounts require the updated database schema.</p></div>
<?php else: ?>
<div class="admin-card p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div><h1 class="h4 mb-1">Customers</h1><p class="admin-muted mb-0">Buyer accounts with verification, order, Re-Up, and custom quote activity.</p></div>
    </div>
    <div class="table-responsive">
        <table class="table align-middle">
            <thead><tr><th>Customer</th><th>Contact</th><th>Verified</th><th>Orders</th><th>Re-Up</th><th>Custom</th><th>Status</th><th>Date</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($rows as $row): ?>
                <tr>
                    <td><strong><?= e($row['full_name']) ?></strong><br><span class="small admin-muted"><?= e($row['email']) ?></span></td>
                    <td><?= e($row['phone']) ?><br><span class="small admin-muted"><?= e($row['city']) ?></span></td>
                    <td><?= !empty($row['email_verified_at']) ? '<span class="badge text-bg-success">Email</span>' : '<span class="badge text-bg-warning">Unverified</span>' ?></td>
                    <td><?= (int) $row['order_count'] ?></td>
                    <td><?= (int) $row['reup_count'] ?></td>
                    <td><?= (int) $row['custom_count'] ?></td>
                    <td><span class="badge badge-soft"><?= e($row['status']) ?></span></td>
                    <td><?= e(date('M d, Y', strtotime($row['created_at']))) ?></td>
                    <td><a class="btn btn-sm btn-outline-primary" href="customer-view.php?id=<?= (int) $row['id'] ?>">View</a></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?><tr><td colspan="9" class="text-center admin-muted py-5">No customers yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
<?php require __DIR__ . '/_footer.php'; ?>
