<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$stmt = $pdo->query("SELECT u.id, u.name, u.email, u.phone,
    COUNT(o.id) AS total_orders,
    COALESCE(SUM(o.total),0) AS total_spent,
    MAX(o.created_at) AS last_order
FROM users u
LEFT JOIN orders o ON o.user_id = u.id AND o.status IN ('paid','packed','shipped','done')
WHERE u.role = 'customer'
GROUP BY u.id, u.name, u.email, u.phone
ORDER BY total_spent DESC, total_orders DESC");
$customers = $stmt->fetchAll();
?>

<h2 class="fw-bold mb-4">Laporan Customer</h2>

<div class="card shadow-sm">
    <div class="card-body table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Nama</th>
                    <th>Email</th>
                    <th>No HP</th>
                    <th>Total Order</th>
                    <th>Total Belanja</th>
                    <th>Order Terakhir</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$customers): ?>
                    <tr><td colspan="6">Belum ada data.</td></tr>
                <?php endif; ?>
                <?php foreach ($customers as $customer): ?>
                    <tr>
                        <td><?= sanitize($customer['name']); ?></td>
                        <td><?= sanitize($customer['email']); ?></td>
                        <td><?= sanitize($customer['phone']); ?></td>
                        <td><?= (int) $customer['total_orders']; ?></td>
                        <td><?= format_currency($customer['total_spent']); ?></td>
                        <td><?= $customer['last_order'] ? sanitize(date('d M Y', strtotime($customer['last_order']))) : '-'; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

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