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

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

try {
    $pdo = hw_db();

    // Total Revenue (from orders)
    $stmt = $pdo->query('SELECT COALESCE(SUM(CAST(total_amount AS DECIMAL(10,2))), 0) as total FROM orders WHERE status IN ("delivered", "shipped")');
    $totalRevenue = (float)($stmt->fetch()['total'] ?? 0);

    // Total Bookings
    $stmt = $pdo->query('SELECT COUNT(*) as count FROM appointments');
    $totalBookings = (int)($stmt->fetch()['count'] ?? 0);

    // Total Customers
    $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);

    // Pending Orders
    $stmt = $pdo->query('SELECT COUNT(*) as count FROM orders WHERE status = "pending"');
    $pendingOrders = (int)($stmt->fetch()['count'] ?? 0);

    hw_json([
        'success' => true,
        'data' => [
            'total_revenue' => $totalRevenue,
            'total_bookings' => $totalBookings,
            'total_customers' => $totalCustomers,
            'pending_orders' => $pendingOrders,
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
