'That invoice no longer exists.'])); } $client_id = intval($invoice['client_id']); enforceClientAccess(); $state = invoiceState($invoice, invoicePaid($invoice_id)); if (!invoiceCanPay($invoice, $state)) { exit(json_encode(['error' => billingNumber('invoice', $invoice) . ' has nothing owed on it - it is ' . strtolower($invoice['invoice_status']) . '.'])); } // The client's other unpaid invoices, oldest due first $others = []; $others_owed = 0; $others_older = 0; $sql_others = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_due, invoice_currency_code, invoice_amount - COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0) AS balance FROM invoices WHERE invoice_client_id = $client_id AND invoice_id != $invoice_id AND invoice_status IN ('Sent', 'Viewed', 'Partial') ORDER BY invoice_due ASC, invoice_id ASC"); while ($row = mysqli_fetch_assoc($sql_others)) { if (floatval($row['balance']) > 0) { $others[] = $row; $others_owed += floatval($row['balance']); $others_older += $row['invoice_due'] < $invoice['invoice_due'] ? 1 : 0; } } $contact_email = (string) mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_client_id = $client_id AND contact_primary = 1 AND contact_archived_at IS NULL LIMIT 1"))[0]; $pay = [ 'id' => 'payForm' . $invoice_id, 'amount' => $state['balance'], 'owed' => $state['balance'], 'currency' => $invoice['invoice_currency_code'], 'email' => $contact_email, ]; ob_start(); ?>