{% comment %}
  Shared Split Payment Panel
  Include this inside the POS form after the main payment method selector.
  Context vars needed: none (uses JS for total calculation)
{% endcomment %}

<!-- ── SPLIT PAYMENT TOGGLE ── -->
<div class="mb-2 split-pay-toggle-wrap">
  <div class="form-check form-switch mb-0 d-flex align-items-center gap-2">
    <input class="form-check-input" type="checkbox" role="switch"
           id="splitToggle" name="is_split_payment" value="1"
           style="width:36px;height:20px;cursor:pointer;">
    <label class="form-check-label small fw-semibold d-flex align-items-center gap-1"
           for="splitToggle" style="cursor:pointer;">
      <i class="fas fa-code-branch" style="color:#7c3aed;"></i>
      Split Payment
    </label>
  </div>
</div>

<!-- ── SPLIT PAYMENT PANEL (hidden by default) ── -->
<div id="splitPaymentPanel" class="d-none mb-2 p-2 rounded-3 border"
     style="background:linear-gradient(135deg,rgba(79,70,229,.04),rgba(124,58,237,.04));border-color:#c4b5fd!important;">

  <div class="small fw-bold text-muted mb-2 text-uppercase" style="letter-spacing:.05em;font-size:.7rem;">
    <i class="fas fa-sliders me-1"></i>Split Amount Between 2 Methods
  </div>

  <div class="row gx-2 mb-2">
    <!-- Method 1 -->
    <div class="col-6">
      <label class="form-label mb-1" style="font-size:.75rem;font-weight:600;">Method 1</label>
      <select name="split_method_1" id="splitMethod1" class="form-select form-select-sm"
              style="border-radius:8px;">
        <option value="cash">💵 Cash</option>
        <option value="pos">💳 POS / Card</option>
        <option value="transfer">🏦 Bank Transfer</option>
        <option value="mobile_money">📱 Mobile Money</option>
      </select>
      <input type="number" name="split_amount_1" id="splitAmount1"
             class="form-control form-control-sm mt-1"
             placeholder="₦ Amount" step="0.01" min="0"
             style="border-radius:8px;">
    </div>

    <!-- Method 2 -->
    <div class="col-6">
      <label class="form-label mb-1" style="font-size:.75rem;font-weight:600;">Method 2</label>
      <select name="split_method_2" id="splitMethod2" class="form-select form-select-sm"
              style="border-radius:8px;">
        <option value="pos">💳 POS / Card</option>
        <option value="cash">💵 Cash</option>
        <option value="transfer">🏦 Bank Transfer</option>
        <option value="mobile_money">📱 Mobile Money</option>
      </select>
      <input type="number" name="split_amount_2" id="splitAmount2"
             class="form-control form-control-sm mt-1"
             placeholder="₦ Amount" step="0.01" min="0"
             style="border-radius:8px;">
    </div>
  </div>

  <!-- Real-time validation message -->
  <div id="splitValidationMsg" class="small" style="min-height:18px;font-weight:600;"></div>
</div>

<script>
(function() {
  var toggle  = document.getElementById('splitToggle');
  var panel   = document.getElementById('splitPaymentPanel');
  var a1el    = document.getElementById('splitAmount1');
  var a2el    = document.getElementById('splitAmount2');
  var msgEl   = document.getElementById('splitValidationMsg');

  var SYM = window.swiftposCurrencySymbol || '₦';
  var DP  = window.swiftposDecimalPlaces  || 2;

  function getGrandTotal() {
    // Try all 3 POS total element IDs
    var candidates = ['gpos-total', 'cart-grand-total', 'cart-total'];
    for (var i = 0; i < candidates.length; i++) {
      var el = document.getElementById(candidates[i]);
      if (el) {
        var raw = el.textContent.replace(/[^\d.]/g, '');
        var val = parseFloat(raw);
        if (!isNaN(val) && val > 0) return val;
      }
    }
    return 0;
  }

  function validate() {
    if (!panel || panel.classList.contains('d-none')) return;
    var total = getGrandTotal();
    var amt1  = parseFloat(a1el.value) || 0;
    var amt2  = parseFloat(a2el.value) || 0;
    var sum   = parseFloat((amt1 + amt2).toFixed(DP));
    var tot   = parseFloat(total.toFixed(DP));

    if (a1el.value === '' && a2el.value === '') {
      msgEl.textContent = '';
      return;
    }

    if (Math.abs(sum - tot) < 0.015) {
      msgEl.style.color = '#16a34a';
      msgEl.innerHTML   = '<i class="fas fa-check-circle me-1"></i>' +
                          SYM + amt1.toFixed(DP) + ' + ' + SYM + amt2.toFixed(DP) +
                          ' = ' + SYM + total.toFixed(DP) + ' ✓ Balanced';
    } else {
      msgEl.style.color = '#dc2626';
      var diff = parseFloat((tot - sum).toFixed(DP));
      msgEl.innerHTML   = '<i class="fas fa-exclamation-circle me-1"></i>' +
                          'Sum (' + SYM + sum.toFixed(DP) + ') ≠ Total (' +
                          SYM + tot.toFixed(DP) + ').  ' +
                          (diff > 0 ? 'Remaining: ' + SYM + diff.toFixed(DP) : 'Over by: ' + SYM + Math.abs(diff).toFixed(DP));
    }
  }

  // Toggle show/hide
  if (toggle) {
    toggle.addEventListener('change', function() {
      var active = this.checked;
      if (panel) panel.classList.toggle('d-none', !active);
      var stdRow = document.getElementById('std-payment-row');
      if (stdRow) stdRow.classList.toggle('d-none', active);
      if (!active) { msgEl.textContent = ''; }
      else validate();
    });
  }

  // Real-time validation on both inputs
  if (a1el) a1el.addEventListener('input', validate);
  if (a2el) a2el.addEventListener('input', validate);

  // Revalidate when the cart total changes (Grid POS & Barcode POS)
  var observer = new MutationObserver(validate);
  ['gpos-total', 'cart-grand-total', 'cart-total'].forEach(function(id) {
    var el = document.getElementById(id);
    if (el) observer.observe(el, { childList: true, characterData: true, subtree: true });
  });

  // Block form submission if split is active and amounts don't balance
  // Works for both pos-form (Classic/Grid) and checkout-form (Barcode)
  var form = document.getElementById('pos-form') || document.getElementById('checkout-form');
  if (form) {
    form.addEventListener('submit', function(e) {
      if (!toggle || !toggle.checked) return;
      var total = getGrandTotal();
      var sum   = parseFloat(((parseFloat(a1el.value)||0) + (parseFloat(a2el.value)||0)).toFixed(DP));
      var tot   = parseFloat(total.toFixed(DP));
      if (Math.abs(sum - tot) >= 0.015) {
        e.preventDefault();
        validate();
        msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
        msgEl.style.animation = 'none';
        requestAnimationFrame(function() {
          msgEl.style.animation = 'sp-shake .3s ease';
        });
        return false;
      }
    }, true);
  }
})();
</script>

<style>
@keyframes sp-shake {
  0%,100%{transform:translateX(0)}
  20%,60%{transform:translateX(-5px)}
  40%,80%{transform:translateX(5px)}
}
</style>
