<?php
$pageTitle = 'Customers';
require_once __DIR__ . '/includes/header.php';

$customers = $db->query("
    SELECT c.*,
    (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) as order_count,
    (SELECT COALESCE(SUM(o.grand_total), 0) FROM orders o WHERE o.customer_id = c.id AND o.payment_status = 'paid') as total_spent_val,
    (SELECT MAX(o.created_at) FROM orders o WHERE o.customer_id = c.id) as last_order
    FROM customers c
    WHERE c.restaurant_id = ?
    ORDER BY c.total_orders DESC
    LIMIT 500
", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Customers</h6>
        <small class="text-muted">View customer information and order history</small>
    </div>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable mb-0">
                <thead class="table-light">
                    <tr><th>Name</th><th>Phone</th><th>Email</th><th>City</th><th>Orders</th><th>Total Spent</th><th>Last Order</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($customers as $cust): ?>
                        <tr>
                            <td><strong><?php echo sanitize($cust['name'] ?? 'N/A'); ?></strong></td>
                            <td><?php echo sanitize($cust['phone'] ?? '-'); ?></td>
                            <td><?php echo sanitize($cust['email'] ?? '-'); ?></td>
                            <td><?php echo sanitize($cust['city'] ?? '-'); ?></td>
                            <td><span class="badge bg-info"><?php echo $cust['total_orders']; ?></span></td>
                            <td><?php echo formatCurrency($cust['total_spent_val'] ?? $cust['total_spent'], $currency); ?></td>
                            <td><small><?php echo $cust['last_order'] ? timeAgo($cust['last_order']) : 'Never'; ?></small></td>
                            <td>
                                <a href="<?php echo $baseUrl; ?>/restaurant-admin/orders.php?customer_id=<?php echo $cust['id']; ?>" class="btn btn-sm btn-outline-primary" title="View Orders"><i class="fas fa-eye"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
