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

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

try {
    $pdo = hw_db();

    // Sales metrics
    $stmt = $pdo->query('SELECT COUNT(*) as count FROM orders');
    $totalOrders = (int)($stmt->fetch()['count'] ?? 0);

    $stmt = $pdo->query('SELECT COALESCE(SUM(CAST(total_amount AS DECIMAL(10,2))), 0) as total FROM orders WHERE DATE(created_at) = CURDATE()');
    $todayRevenue = (float)($stmt->fetch()['total'] ?? 0);

    $stmt = $pdo->query('SELECT COALESCE(AVG(CAST(total_amount AS DECIMAL(10,2))), 0) as avg FROM orders');
    $avgOrderValue = (float)($stmt->fetch()['avg'] ?? 0);

    hw_json([
        'success' => true,
        'data' => [
            'total_orders' => $totalOrders,
            'today_revenue' => $todayRevenue,
            'avg_order_value' => $avgOrderValue,
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
