<?php
require_once __DIR__ . '/../config.php';
requireLogin();

require_once __DIR__ . '/../lib/logic.php';

$kpis = getDashboardKPIs();

$monthlyStats = $pdo = getDBConnection();
$pdo = getDBConnection();
$stmt = $pdo->query("
    SELECT DATE_FORMAT(PO_Date, '%Y-%m') as month,
           COUNT(*) as orders,
           SUM(Quantity * UnitPrice) as value
    FROM orders
    WHERE PO_Date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(PO_Date, '%Y-%m')
    ORDER BY month
");
$monthlyData = $stmt->fetchAll();

$categoryStats = $pdo->query("
    SELECT source_type as category,
           COUNT(*) as transactions,
           SUM(quantity_in) as qty_in,
           SUM(quantity_out) as qty_out
    FROM inventory_transaction
    GROUP BY source_type
")->fetchAll();

$supplierStats = $pdo->query("
    SELECT s.SupplierName, s.Rating,
           COUNT(o.OrderID) as orders,
           COALESCE(SUM(o.Quantity * o.UnitPrice), 0) as value
    FROM suppliers s
    LEFT JOIN orders o ON s.SupplierID = o.Supplier
    GROUP BY s.SupplierID
    ORDER BY value DESC
    LIMIT 10
")->fetchAll();

jsonResponse([
    'kpis' => $kpis,
    'monthly' => $monthlyData,
    'categories' => $categoryStats,
    'suppliers' => $supplierStats
]);
?>