<?php $this->start('body'); ?>
<?php $customerId = (int)$this->data['customer_id']; $inv = $this->data['open_invoices']; ?>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-hand-holding-usd me-2 text-muted"></i>Record Customer Receipt</h5>
  <a href="<?= PROOT; ?>CustomerReceipts" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= flashHtml(); ?>

<div class="card border-0 shadow-sm mb-3">
  <div class="card-body">
    <h6 class="text-uppercase text-muted small mb-3">Step 1 · Customer</h6>
    <form method="GET" action="<?= PROOT; ?>CustomerReceipts/record">
      <select name="customer_id" class="form-select" onchange="this.form.submit()">
        <option value="0">— select a customer with open invoices —</option>
        <?php foreach ($this->data['customers'] as $c): ?>
          <option value="<?= (int)$c['c0d']; ?>" <?= $customerId === (int)$c['c0d'] ? 'selected' : ''; ?>>
            <?= htmlspecialchars($c['customer_name']); ?> · <?= (int)$c['open_count']; ?> open · TZS <?= number_format((float)$c['outstanding'], 0); ?>
          </option>
        <?php endforeach; ?>
      </select>
    </form>
  </div>
</div>

<?php if ($customerId > 0 && !empty($inv)): ?>
  <form method="POST" action="<?= PROOT; ?>CustomerReceipts/save" onsubmit="return validateSave();">
    <?= csrf_field(); ?>
    <input type="hidden" name="customer_id" value="<?= $customerId; ?>">

    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Step 2 · Payment</h6>
        <div class="row g-3">
          <div class="col-md-3"><label class="form-label">Receipt date</label>
            <input type="date" name="receipt_date" class="form-control" value="<?= date('Y-m-d'); ?>"></div>
          <div class="col-md-3"><label class="form-label">Amount received <span class="text-danger">*</span></label>
            <input type="number" step="0.01" min="0" name="amount" id="rcAmt" class="form-control" required oninput="recalc();"></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','petty_cash'=>'Petty cash','cheque'=>'Cheque'] as $k=>$v): ?>
                <option value="<?= $k; ?>"><?= $v; ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="col-md-3"><label class="form-label">Reference</label>
            <input type="text" name="reference" class="form-control" placeholder="Txn # · cheque # · mobile ref"></div>
          <div class="col-12"><label class="form-label">Notes (optional)</label>
            <textarea name="notes" rows="2" class="form-control"></textarea></div>
        </div>
      </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between mb-3">
          <h6 class="text-uppercase text-muted small mb-0">Step 3 · Apply to invoices</h6>
          <button type="button" class="btn btn-sm btn-outline-primary" onclick="autoApply()">Auto-apply oldest-first</button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
              <tr><th>Invoice #</th><th>Date</th><th>Due</th><th class="money">Total</th><th class="money">Outstanding</th><th class="money" style="width:180px;">Apply</th></tr>
            </thead>
            <tbody>
              <?php foreach ($inv as $i): ?>
                <tr>
                  <td class="small font-monospace"><?= htmlspecialchars($i['invoice_no']); ?><input type="hidden" name="alloc_invoice_id[]" value="<?= (int)$i['invoice_id']; ?>"></td>
                  <td class="small text-muted"><?= humanDate($i['invoice_date']); ?></td>
                  <td class="small text-muted"><?= $i['due_date'] ? humanDate($i['due_date']) : '—'; ?></td>
                  <td class="money small"><?= number_format((float)$i['total_amount'], 2, '.', ','); ?></td>
                  <td class="money small text-danger" data-out="<?= (float)$i['outstanding']; ?>"><?= number_format((float)$i['outstanding'], 2, '.', ','); ?></td>
                  <td><input type="number" step="0.01" min="0" max="<?= (float)$i['outstanding']; ?>" name="alloc_amount[]" class="form-control form-control-sm js-alloc money" value="0" oninput="recalc();"></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot class="table-light">
              <tr><th colspan="5" class="text-end">Total allocated</th><th class="money"><span id="totAlloc">0.00</span></th></tr>
              <tr><th colspan="5" class="text-end">Unallocated (goes on account — TODO Iter 4.2)</th><th class="money"><span id="totUnalloc">0.00</span></th></tr>
            </tfoot>
          </table>
        </div>
      </div>
      <div class="card-footer bg-white d-flex justify-content-end gap-2 py-3">
        <a href="<?= PROOT; ?>CustomerReceipts" class="btn btn-outline-secondary">Cancel</a>
        <button class="btn btn-primary"><i class="fas fa-save me-1"></i>Record receipt</button>
      </div>
    </div>
  </form>
<?php elseif ($customerId > 0): ?>
  <div class="card border-0 shadow-sm"><div class="card-body text-center text-muted py-5">This customer has no open invoices.</div></div>
<?php endif; ?>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const rcAmt = document.getElementById('rcAmt');
const allocs = document.querySelectorAll('.js-alloc');
function recalc() {
    let sum = 0;
    allocs.forEach(a => sum += parseFloat(a.value || 0));
    document.getElementById('totAlloc').textContent = sum.toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2});
    const amt = parseFloat(rcAmt.value || 0);
    document.getElementById('totUnalloc').textContent = Math.max(0, amt - sum).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2});
}
function autoApply() {
    let remaining = parseFloat(rcAmt.value || 0);
    if (!remaining) { alert('Enter the amount received first.'); return; }
    allocs.forEach(a => {
        if (remaining <= 0) { a.value = 0; return; }
        const out = parseFloat(a.closest('tr').querySelector('[data-out]').dataset.out || 0);
        const use = Math.min(out, remaining);
        a.value = use.toFixed(2);
        remaining -= use;
    });
    recalc();
}
function validateSave() {
    const amt = parseFloat(rcAmt.value || 0);
    if (amt <= 0) { alert('Enter an amount.'); return false; }
    let sum = 0;
    allocs.forEach(a => sum += parseFloat(a.value || 0));
    if (sum <= 0)    { alert('Allocate the receipt to at least one invoice.'); return false; }
    if (sum > amt + 0.005) { alert('Allocations exceed the receipt amount.'); return false; }
    return true;
}
recalc();
</script>
<?php $this->end(); ?>
