'That client no longer exists.'])); } // What the batch pays, in the order the batch pays it $open = []; $owed = 0; $sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_due, invoice_amount, 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_status IN ('Sent', 'Viewed', 'Partial') ORDER BY invoice_number ASC"); while ($row = mysqli_fetch_assoc($sql)) { if (floatval($row['balance']) > 0) { $open[] = $row; $owed += floatval($row['balance']); } } $owed = round($owed, 2); if (!$open) { exit(json_encode(['error' => $client['client_name'] . ' has no unpaid invoices.'])); } $currency = (string) ($open[0]['invoice_currency_code'] ?: $client['client_currency_code']); $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' => 'payBatch' . $client_id, 'amount' => $owed, 'owed' => $owed, 'currency' => $currency, 'email' => $contact_email, 'full_text' => count($open) === 1 ? 'Pays it in full.' : 'Pays all ' . count($open) . ' in full.', ]; ob_start(); ?>