function recordInvoicePayment(int $invoiceId, float $amount, array $meta = []): array { if ($amount <= 0.0) { return [ 'success' => false, 'message' => 'Nominal pembayaran harus lebih besar dari 0.' ]; } $amount = round($amount, 2); $startedTransaction = false; if (!$this->db->inTransaction()) { $this->db->beginTransaction(); $startedTransaction = true; } try { // Row lock on invoice to prevent concurrent overpayments $stmt = $this->db->prepare("SELECT * FROM billing_invoices WHERE id = :id FOR UPDATE"); $stmt->execute([':id' => $invoiceId]); $invoice = $stmt->fetch(PDO::FETCH_ASSOC); if (!$invoice) { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} tidak ditemukan."]; } if ($invoice['status'] === 'cancelled') { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} telah dibatalkan, pembayaran ditolak."]; } $currentPaid = (float)($invoice['paid_amount'] ?? 0.0); $totalAmount = (float)$invoice['amount']; $currentOutstanding = max(0.0, round($totalAmount - $currentPaid, 2)); if ($currentOutstanding <= 0.0 || $invoice['status'] === 'paid') { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} sudah lunas sebelumnya."]; } // Overpayment check if ($amount > $currentOutstanding) { if ($startedTransaction) $this->db->rollBack(); return [ 'success' => false, 'message' => "Nominal pembayaran (Rp " . number_format($amount, 0, ',', '.') . ") melebihi sisa tagihan (Rp " . number_format($currentOutstanding, 0, ',', '.') . ")." ]; } // Reference check for idempotency & du