<?php $this->start('body'); ?>
<?php $f = $this->data['form']; $suppliers = $this->data['suppliers']; $bills = $this->data['bills']; $vendorId = (int)$this->data['vendor_id']; ?>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-money-bill-transfer me-2 text-muted"></i>Record Supplier Payment</h5>
  <a href="<?= PROOT; ?>SupplierPayments" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= $this->raw('fb_msg'); ?>

<!-- Vendor picker (GETs to reload the open-bills list) -->
<form method="GET" action="<?= PROOT; ?>SupplierPayments/record" class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-end">
    <div class="flex-grow-1">
      <label class="form-label small mb-1 text-uppercase text-muted">Supplier</label>
      <select name="vendor_id" class="form-select form-select-sm">
        <option value="">— pick to load open bills —</option>
        <?php foreach ($suppliers as $s): ?>
          <option value="<?= (int)$s['c0d']; ?>" <?= $vendorId === (int)$s['c0d'] ? 'selected' : ''; ?>><?= htmlspecialchars($s['vendor_name']); ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-sync me-1"></i>Load bills</button>
  </div>
</form>

<?php if ($vendorId === 0): ?>
  <div class="alert alert-info small">Pick a supplier above to load their open bills and record a payment.</div>
<?php else: ?>

<form method="POST" action="<?= PROOT; ?>SupplierPayments/save" class="card border-0 shadow-sm">
  <?= csrf_field(); ?>
  <input type="hidden" name="vendor_id" value="<?= $vendorId; ?>">
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-2"><label class="form-label">Date</label><input type="date" name="payment_date" class="form-control" value="<?= htmlspecialchars($f['payment_date'] ?? date('Y-m-d')); ?>"></div>
      <div class="col-md-3"><label class="form-label">Amount <span class="text-danger">*</span></label><input type="number" step="0.01" min="0" id="fAmt" name="amount" class="form-control text-end" value="<?= htmlspecialchars($f['amount'] ?? '0.00'); ?>" required></div>
      <div class="col-md-3">
        <label class="form-label">Method</label>
        <select name="payment_method" class="form-select">
          <?php foreach (['bank_transfer'=>'Bank transfer','mobile_money'=>'Mobile money','cash'=>'Cash','cheque'=>'Cheque','fuel_card'=>'Fuel card'] as $k => $v): ?>
            <option value="<?= $k; ?>" <?= ($f['payment_method'] ?? 'bank_transfer') === $k ? 'selected' : ''; ?>><?= $v; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4"><label class="form-label">Reference</label><input type="text" name="reference" class="form-control" value="<?= htmlspecialchars($f['reference'] ?? ''); ?>" placeholder="Bank ref / cheque no"></div>
      <div class="col-md-12"><label class="form-label">Notes</label><textarea name="notes" rows="2" class="form-control"><?= htmlspecialchars($f['notes'] ?? ''); ?></textarea></div>
    </div>

    <h6 class="text-uppercase text-muted small mt-4 mb-2">Allocate to bills</h6>
    <?php if (empty($bills)): ?>
      <div class="text-muted small">This supplier has no open bills. The payment will land as an unallocated payment on account.</div>
    <?php else: ?>
      <table class="table table-sm align-middle">
        <thead class="table-light">
          <tr><th>Bill</th><th>Date</th><th>Due</th><th class="money">Total</th><th class="money">Balance</th><th class="money" style="width:140px;">Apply</th></tr>
        </thead>
        <tbody>
          <?php foreach ($bills as $b): ?>
            <tr>
              <td class="font-monospace small"><?= htmlspecialchars($b['bill_no']); ?><?php if ($b['supplier_ref']): ?><div class="text-muted small"><?= htmlspecialchars($b['supplier_ref']); ?></div><?php endif; ?></td>
              <td class="small"><?= humanDate($b['bill_date']); ?></td>
              <td class="small"><?= $b['due_date'] ? humanDate($b['due_date']) : '—'; ?></td>
              <td class="money font-monospace small"><?= number_format((float)$b['total_amount'], 2); ?></td>
              <td class="money font-monospace small fw-semibold"><?= number_format((float)$b['balance_due'], 2); ?></td>
              <td>
                <input type="hidden" name="alloc_bill_id[]" value="<?= (int)$b['c0d']; ?>">
                <input type="number" step="0.01" min="0" max="<?= (float)$b['balance_due']; ?>" name="alloc_amount[]" class="form-control form-control-sm text-end js-alloc" value="0.00" data-max="<?= (float)$b['balance_due']; ?>">
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot class="table-light">
          <tr class="fw-bold">
            <th colspan="5" class="text-uppercase small">Allocated</th>
            <th class="money font-monospace" id="fAllocTotal">0.00</th>
          </tr>
          <tr>
            <th colspan="5" class="small">Unallocated (on account)</th>
            <th class="money font-monospace" id="fUnalloc">0.00</th>
          </tr>
        </tfoot>
      </table>
    <?php endif; ?>
  </div>
  <div class="card-footer bg-white d-flex justify-content-between py-3">
    <?php if (!empty($bills)): ?><button type="button" class="btn btn-outline-primary btn-sm" id="btnAutoAlloc"><i class="fas fa-magic me-1"></i>Auto-allocate (oldest first)</button><?php else: ?><span></span><?php endif; ?>
    <div class="d-flex gap-2">
      <a href="<?= PROOT; ?>SupplierPayments" class="btn btn-outline-secondary">Cancel</a>
      <button class="btn btn-primary"><i class="fas fa-save me-1"></i>Record payment</button>
    </div>
  </div>
</form>

<?php endif; ?>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
function refreshAlloc() {
    let sum = 0;
    document.querySelectorAll('.js-alloc').forEach(el => { sum += parseFloat(el.value) || 0; });
    const amt = parseFloat(document.getElementById('fAmt').value) || 0;
    const at = document.getElementById('fAllocTotal'); if (at) at.textContent = sum.toFixed(2);
    const un = document.getElementById('fUnalloc');    if (un) un.textContent = Math.max(0, amt - sum).toFixed(2);
}
document.querySelectorAll('.js-alloc').forEach(el => el.addEventListener('input', refreshAlloc));
document.getElementById('fAmt')?.addEventListener('input', refreshAlloc);
document.getElementById('btnAutoAlloc')?.addEventListener('click', () => {
    let remaining = parseFloat(document.getElementById('fAmt').value) || 0;
    document.querySelectorAll('.js-alloc').forEach(el => {
        const max = parseFloat(el.dataset.max) || 0;
        const apply = Math.min(remaining, max);
        el.value = apply.toFixed(2);
        remaining -= apply;
    });
    refreshAlloc();
});
refreshAlloc();
</script>
<?php $this->end(); ?>
