<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Users';
$db = db();

$users = $db->query("SELECT u.*, (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as order_count, (SELECT COALESCE(SUM(total), 0) FROM orders WHERE user_id = u.id AND status != 'cancelled') as total_spent FROM users u ORDER BY u.created_at DESC")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Name</th><th class="px-4 py-3 font-medium">Email</th><th class="px-4 py-3 font-medium">Role</th><th class="px-4 py-3 font-medium">Orders</th><th class="px-4 py-3 font-medium">Total Spent</th><th class="px-4 py-3 font-medium">Joined</th></tr></thead>
        <tbody>
            <?php foreach ($users as $u): ?>
            <tr class="border-t">
                <td class="px-4 py-3 font-medium text-gray-800"><?= h($u['name']) ?></td>
                <td class="px-4 py-3 text-gray-500"><?= h($u['email']) ?></td>
                <td class="px-4 py-3"><?= $u['is_admin'] ? '<span class="text-primary-600 font-medium">Admin</span>' : '<span class="text-gray-500">Customer</span>' ?></td>
                <td class="px-4 py-3"><?= $u['order_count'] ?></td>
                <td class="px-4 py-3 font-medium"><?= formatPrice($u['total_spent']) ?></td>
                <td class="px-4 py-3 text-gray-500"><?= date('d M Y', strtotime($u['created_at'])) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
