<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);
hw_require_auth(['admin']);

try {
    $pdo = hw_db();

    // Customer metrics
    $stmt = $pdo->query('SELECT COUNT(*) as count FROM users WHERE id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))');
    $totalCustomers = (int)($stmt->fetch()['count'] ?? 0);

    $stmt = $pdo->query('SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = CURDATE() AND id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))');
    $newToday = (int)($stmt->fetch()['count'] ?? 0);

    $stmt = $pdo->query('SELECT COUNT(*) as count FROM users WHERE status = "active" AND id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))');
    $activeCustomers = (int)($stmt->fetch()['count'] ?? 0);

    hw_json([
        'success' => true,
        'data' => [
            'total_customers' => $totalCustomers,
            'new_today' => $newToday,
            'active_customers' => $activeCustomers,
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
