0) { $result = $inv->getInvoiceById($id); if (!$result) { http_response_code(404); $answer['message'] = 'Invoice not found.'; exit(json_encode($answer)); } $answer['output'] = $result; // Fetch linked credit notes for invoice detail page if ($result['doc_type'] === 'invoice') { $sth = $pdo2->prepare( "SELECT * FROM td_invoice WHERE company_id = :company_id AND ref_invoice_id = :ref_id AND doc_type = 'credit_note' ORDER BY id DESC" ); $sth->execute([':company_id' => $company_id, ':ref_id' => $id]); $answer['credit_notes'] = $sth->fetchAll(PDO::FETCH_ASSOC); } } else { $order_id = (int)($data['order_id'] ?? 0); $doc_type = $data['doc_type'] ?? ''; $answer['output'] = $inv->getInvoiceList($order_id, $doc_type); // For credit note tab — join ref invoice number if ($doc_type === 'credit_note') { $rows = $answer['output']; foreach ($rows as &$row) { if ((int)$row['ref_invoice_id'] > 0) { $sth = $pdo2->prepare( "SELECT invoice_number FROM td_invoice WHERE id = :id AND company_id = :company_id" ); $sth->execute([':id' => $row['ref_invoice_id'], ':company_id' => $company_id]); $row['ref_invoice_number'] = $sth->fetchColumn() ?: '—'; } else { $row['ref_invoice_number'] = '—'; } } unset($row); $answer['output'] = $rows; } } $answer['success'] = 1; exit(json_encode($answer)); ?>