<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$userId = as_int((string)($_GET['user_id'] ?? '0'));
require_user($userId);
$conn = db();
ensure_void_request_table();
$totalItems = (int)($conn->query('SELECT COUNT(*) AS c FROM items')->fetch_assoc()['c'] ?? 0);
$totalStockValue = (float)($conn->query("SELECT COALESCE(SUM(price * quantity), 0) AS v FROM items WHERE item_type = 'sale'")->fetch_assoc()['v'] ?? 0);
$lowStockCount = (int)($conn->query("SELECT COUNT(*) AS c FROM items WHERE item_type = 'sale' AND quantity <= 5")->fetch_assoc()['c'] ?? 0);
$today = $conn->query("SELECT COALESCE(SUM(total_amount), 0) AS total, COUNT(*) AS orders FROM sales WHERE " . sales_active_where_sql('sales') . " AND DATE(sale_datetime) = CURDATE()")->fetch_assoc();
$month = $conn->query("SELECT COALESCE(SUM(total_amount), 0) AS total FROM sales WHERE " . sales_active_where_sql('sales') . " AND YEAR(sale_datetime) = YEAR(CURDATE()) AND MONTH(sale_datetime) = MONTH(CURDATE())")->fetch_assoc();
$pendingVoidRequests = is_admin_role(require_user($userId)) ? (int)($conn->query("SELECT COUNT(*) AS c FROM sale_void_requests WHERE request_status = 'pending'")->fetch_assoc()['c'] ?? 0) : 0;
respond(['success' => true, 'data' => [
    'total_items' => $totalItems,
    'total_stock_value' => $totalStockValue,
    'low_stock_count' => $lowStockCount,
    'today_sales' => (float)($today['total'] ?? 0),
    'today_orders' => (int)($today['orders'] ?? 0),
    'month_sales' => (float)($month['total'] ?? 0),
    'generated_at' => date('Y-m-d H:i:s'),
    'pending_void_requests' => $pendingVoidRequests,
]]);
