prepare("SELECT id, name, tax_identification_number, is_active, (jofotara_client_id_encrypted IS NOT NULL) as is_jofotara_connected, jofotara_income_source_sequence FROM companies WHERE id = ? AND tenant_id = ?"); $stmt->execute([$companyId, $tenantId]); $company = $stmt->fetch(); if (!$company) json_error('Company not found', 404); // 3. Monthly Invoice Stats $stmtStats = $db->prepare(" SELECT DATE_FORMAT(invoice_date, '%Y-%m') as month, COUNT(*) as total_invoices, SUM(CASE WHEN status='approved' THEN 1 ELSE 0 END) as approved_count, SUM(grand_total) as total_amount FROM invoices WHERE company_id = ? AND deleted_at IS NULL GROUP BY month ORDER BY month DESC LIMIT 12 "); $stmtStats->execute([$companyId]); $monthly = $stmtStats->fetchAll(); // 4. Lifetime Totals $stmtTotals = $db->prepare(" SELECT COUNT(*) as total_invoices, SUM(grand_total) as total_amount, SUM(tax_amount) as total_tax, SUM(CASE WHEN status='approved' THEN 1 ELSE 0 END) as approved_count FROM invoices WHERE company_id = ? AND deleted_at IS NULL "); $stmtTotals->execute([$companyId]); $totals = $stmtTotals->fetch(); json_success([ 'company' => $company, 'monthly' => $monthly, 'totals' => $totals ]); } catch (\Exception $e) { error_log("Company Stats Error: " . $e->getMessage()); json_error('Server error', 500); }