getStockContext($warehouse_id, $id); $table = $warehouse['table']; // ── Always last 12 months ──────────────────────────────────────────── $now = new DateTime(); $start = (clone $now)->modify('-12 months')->format('Y-m-d 00:00:00'); $end = $now->format('Y-m-d 23:59:59'); // ── Query: group by month ──────────────────────────────────────────── $sql = "SELECT DATE_FORMAT(a.date, '%b') AS `label`, DATE_FORMAT(a.date, '%Y-%m') AS `sort_key`, ROUND(SUM(a.`in`), 2) AS `stock_in`, ROUND(SUM(a.`out`), 2) AS `stock_out` FROM `{$table}` a WHERE a.company_id = {$company_id} and a.date >= '{$start}' and a.date <= '{$end}' GROUP BY `sort_key`, `label` ORDER BY `sort_key` ASC"; $sth = $pdo2->prepare($sql); $sth->execute(); $rows = $sth->fetchAll(PDO::FETCH_ASSOC); // ── Index DB results by sort_key (YYYY-MM) ────────────────────────── $dataByMonth = []; foreach ($rows as $row) { $dataByMonth[$row['sort_key']] = $row; } // ── Always build 12 months, fill zeros where no data ──────────────── $labels = []; $stock_in = []; $stock_out = []; for ($i = 11; $i >= 0; $i--) { $dt = (clone $now)->modify("-{$i} months"); $key = $dt->format('Y-m'); // e.g. "2025-04" $label = $dt->format('M'); // e.g. "Apr" $labels[] = $label; $stock_in[] = isset($dataByMonth[$key]) ? round((float)$dataByMonth[$key]['stock_in'], 2) : 0; $stock_out[] = isset($dataByMonth[$key]) ? round((float)$dataByMonth[$key]['stock_out'], 2) : 0; } // ── Response ───────────────────────────────────────────────────────── $output = [ 'labels' => $labels, 'stock_in' => $stock_in, 'stock_out' => $stock_out, ]; $answer["output"] = $output; $answer["success"] = 1; exit(json_encode($answer)); ?>