prepare(" SELECT COUNT(DISTINCT c.id) as total_companies, COUNT(i.id) as total_invoices, SUM(i.grand_total) as total_amount, SUM(i.tax_amount) as total_tax FROM companies c LEFT JOIN invoices i ON c.id = i.company_id AND i.deleted_at IS NULL WHERE c.tenant_id = ? AND c.deleted_at IS NULL "); $stmt->execute([$tenantId]); $summary = $stmt->fetch(); // 2. Monthly breakdown $stmt = $db->prepare(" SELECT DATE_FORMAT(i.invoice_date, '%Y-%m') as month, COUNT(*) as total_invoices, SUM(i.tax_amount) as total_tax, SUM(i.grand_total) as total_amount FROM invoices i WHERE i.tenant_id = ? AND i.deleted_at IS NULL GROUP BY month ORDER BY month DESC LIMIT 12 "); $stmt->execute([$tenantId]); $monthly = $stmt->fetchAll(); json_success([ 'summary' => $summary, 'monthly' => $monthly ]); } catch (\Exception $e) { safe_error($e, 'tenants/stats'); }