prepare( "SELECT ROUND(COALESCE(SUM(total_in), 0), 2) AS total_in, ROUND(COALESCE(SUM(total_out), 0), 2) AS total_out FROM warehouse_balance WHERE company_id = :company_id" ); $sth->execute([':company_id' => $company_id]); $stock_stats = $sth->fetch(PDO::FETCH_ASSOC); // All-time orders (excluding cancelled) $sth = $pdo2->prepare( "SELECT COUNT(*), COALESCE(SUM(grand_total), 0) FROM td_order WHERE company_id = :company_id AND status != -1" ); $sth->execute([':company_id' => $company_id]); [$total_orders, $total_revenue] = $sth->fetch(PDO::FETCH_NUM); // Unpaid invoices (status=0 draft + status=1 issued + status=3 overdue) $sth = $pdo2->prepare( "SELECT COUNT(*) FROM td_invoice WHERE company_id = :company_id AND doc_type = 'invoice' AND status IN (0, 1, 3)" ); $sth->execute([':company_id' => $company_id]); $unpaid_invoices = (int)$sth->fetchColumn(); // Pending returns (status=0 draft) $sth = $pdo2->prepare( "SELECT COUNT(*) FROM td_return WHERE company_id = :company_id AND status = 0" ); $sth->execute([':company_id' => $company_id]); $pending_returns = (int)$sth->fetchColumn(); // Stock health breakdown for the Overall Information donut chart $low_stock_items = $report->getLowStockItems(); $critical_count = count(array_filter($low_stock_items, fn($i) => $i['status'] === 'critical')); $warning_count = count(array_filter($low_stock_items, fn($i) => $i['status'] === 'warning')); $total_in_stock = (int) $report->getTotalProductInStock(); $healthy_count = max(0, $total_in_stock - $critical_count - $warning_count); $answer['output'] = [ 'total_in' => $stock_stats['total_in'], 'total_out' => $stock_stats['total_out'], 'low_stock' => count($low_stock_items), 'total_orders' => (int)$total_orders, 'total_revenue' => (float)$total_revenue, 'unpaid_invoices' => $unpaid_invoices, 'pending_returns' => $pending_returns, 'stock_movement' => $report->getStockMovementChart(12), 'most_moved' => $report->getMostMovedProducts($month), 'low_stock_items' => $low_stock_items, 'recent_activity' => $report->getRecentActivity(10), 'stock_health' => [ 'healthy' => $healthy_count, 'warning' => $warning_count, 'critical' => $critical_count, 'total' => $total_in_stock, ], 'total_products' => (int) $report->getTotalProduct(), 'total_contacts' => (int) $report->getTotalContact(), 'total_warehouses' => (int) $report->getTotalWarehouse(), ]; $answer['success'] = 1; exit(json_encode($answer)); ?>