0.01 AND i.invoice_date <= :as_of_date ORDER BY s.name, i.invoice_date; SQL; $stmt = $pdo->prepare($sql); $stmt->execute([':as_of_date' => $as_of_date]); $details = $stmt->fetchAll(PDO::FETCH_ASSOC); // Bucket the outstanding balances $buckets = [ 'current' => 0, '1-30' => 0, '31-60' => 0, '61-90' => 0, '91+' => 0 ]; $total_outstanding = 0; foreach ($details as $detail) { $total_outstanding += $detail['outstanding_balance']; if ($detail['days_overdue'] <= 0) { $buckets['current'] += $detail['outstanding_balance']; } elseif ($detail['days_overdue'] <= 30) { $buckets['1-30'] += $detail['outstanding_balance']; } elseif ($detail['days_overdue'] <= 60) { $buckets['31-60'] += $detail['outstanding_balance']; } elseif ($detail['days_overdue'] <= 90) { $buckets['61-90'] += $detail['outstanding_balance']; } else { $buckets['91+'] += $detail['outstanding_balance']; } } echo json_encode([ 'success' => true, 'report_name' => 'Accounts Receivable Aging', 'generated_at' => date('c'), 'filters' => ['as_of_date' => $as_of_date], 'summary' => [ 'total_outstanding' => $total_outstanding, 'buckets' => $buckets ], 'details' => $details ]); } catch (PDOException $e) { http_response_code(500); echo json_encode([ 'success' => false, 'error' => 'Database error: ' . $e->getMessage() ]); }