/* Itemize-card running totals for the quote builder
 * (includes/estimates.php). Reads page config attached via
 * wp_add_inline_script: paintopsQuoteMarkupMultiplier,
 * paintopsTaxPercent, paintopsEstTotalPrefilled. */

function calculateTotal(syncTotalField) {
  let sum = 0;

  // Sum all numeric fields
  document.querySelectorAll('.calc-field').forEach(input => {
	let val = parseFloat(input.value) || 0;
	sum += val;
  });

  // Apply the configured markup (PaintOps > Business > Pricing Rules)
  let total = sum * paintopsQuoteMarkupMultiplier;

  // Sales Tax/VAT applies to the marked-up total (the actual sale
  // price), not the raw pre-markup subtotal, see
  // paintops_calc_tax_amount() in paintops.php for the same logic
  // used server-side. Zero when no rate is configured, so
  // grandTotal just equals total in that case.
  let taxAmount = total * (paintopsTaxPercent / 100);
  let grandTotal = total + taxAmount;

  // Update DOM
  document.getElementById('calc-subtotal').textContent = sum.toFixed(2);
  document.getElementById('calc-total').textContent = total.toFixed(2);
  var taxEl = document.getElementById('calc-tax');
  if (taxEl) taxEl.textContent = taxAmount.toFixed(2);
  var grandEl = document.getElementById('calc-grand-total');
  if (grandEl) grandEl.textContent = grandTotal.toFixed(2);

  // Keep the actual Quote Total field in sync with the line items,
  // previously this only updated the "Total Suggested" readout above,
  // so the itemized costs and the actual quoted/sent total could
  // silently disagree unless someone manually retyped the suggested
  // number into Quote Total. Only syncs while a line item is actively
  // being edited (not on page load), so it never overwrites a total
  // that was already saved or manually typed in, e.g. a negotiated
  // round number, just because the page reloaded. Quote Total now
  // syncs to grandTotal (markup + tax), not just the marked-up
  // subtotal, since that's the actual amount being quoted/charged.
  if (syncTotalField) {
	var totalField = document.getElementById('estTotal');
	if (totalField) totalField.value = Math.round(grandTotal);
	var taxField = document.getElementById('estTax');
	if (taxField) taxField.value = Math.round(taxAmount);
  }
}

// Run whenever inputs change, and sync Quote Total each time.
document.querySelectorAll('.calc-field').forEach(input => {
  input.addEventListener('input', function() { calculateTotal(true); });
});

// Run once on load. Whether that initial run also syncs Quote Total
// depends on whether there's already a real total to protect: a
// brand-new quote (or one where Quote Total is still blank/0, e.g.
// pre-filled labor with nothing typed yet) has nothing to lose by
// syncing immediately, otherwise the labor suggestion shows up in
// [1] Total Labor Cost but Quote Total sits at 0 until the estimator
// happens to touch a line item. An existing quote that already has a
// real (possibly manually-adjusted) total keeps it untouched on load.
calculateTotal(!paintopsEstTotalPrefilled);
