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

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-plus me-2 text-muted"></i>Bill Trips</h5>
  <a href="<?= PROOT; ?>CustomerInvoices" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= flashHtml(); ?>

<div class="alert alert-info small">
  <i class="fas fa-info-circle me-1"></i>
  Only <strong>closed trips</strong> with a non-zero <code>invoice_amount</code> that aren't already on an active invoice are billable.
  Select trips for ONE customer, review VAT + terms, then create the invoice as a draft you can review before issuing.
</div>

<!-- Step 1: pick customer -->
<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; ?>CustomerInvoices/billTrips" class="row g-2 align-items-end">
      <div class="col-md-8"><label class="form-label small mb-1">Customer</label>
        <select name="customer_id" class="form-select" onchange="this.form.submit()">
          <option value="0">— select a customer —</option>
          <?php foreach ($this->data['customers'] as $c): ?>
            <option value="<?= (int)$c['customer_id']; ?>" <?= $customerId === (int)$c['customer_id'] ? 'selected' : ''; ?>>
              <?= htmlspecialchars($c['customer_name']); ?>
              <?php if ((int)$c['trips'] > 0): ?> · <?= (int)$c['trips']; ?> unbilled trips · TZS <?= number_format((float)$c['gross'], 0); ?><?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4"><noscript><button class="btn btn-primary">Load</button></noscript></div>
    </form>
  </div>
</div>

<?php if ($customerId <= 0): ?>
  <div class="card border-0 shadow-sm"><div class="card-body text-center text-muted py-5">Select a customer to see their unbilled trips.</div></div>
<?php elseif (empty($trips)): ?>
  <div class="card border-0 shadow-sm"><div class="card-body text-center text-muted py-5">No unbilled trips for this customer.</div></div>
<?php else: ?>
  <form method="POST" action="<?= PROOT; ?>CustomerInvoices/create" onsubmit="return validateBill();">
    <?= csrf_field(); ?>
    <input type="hidden" name="customer_id" value="<?= $customerId; ?>">

    <!-- Step 2: trips -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="text-uppercase text-muted small mb-0">Step 2 · Select trips</h6>
          <div class="small"><label><input type="checkbox" id="chkAll"> select all</label></div>
        </div>
        <div class="table-responsive">
          <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
              <tr><th style="width:34px;"></th><th>Trip #</th><th>Closed</th><th>Route</th><th>Truck</th><th class="money">Km</th><th class="money">Amount</th></tr>
            </thead>
            <tbody>
              <?php foreach ($trips as $t): ?>
                <tr>
                  <td><input type="checkbox" name="trip_ids[]" value="<?= (int)$t['trip_id']; ?>" class="js-trip" data-amt="<?= (float)$t['invoice_amount']; ?>"></td>
                  <td class="small font-monospace fw-semibold"><?= htmlspecialchars($t['trip_no']); ?></td>
                  <td class="small text-muted"><?= $t['actual_end'] ? humanDate($t['actual_end']) : '—'; ?></td>
                  <td class="small"><?= htmlspecialchars(trim(($t['origin_address'] ?? '') . ' → ' . ($t['destination_address'] ?? ''))); ?></td>
                  <td class="small"><?= htmlspecialchars($t['truck_reg'] ?: '—'); ?><?php if ($t['driver_name']): ?><div class="text-muted small"><?= htmlspecialchars($t['driver_name']); ?></div><?php endif; ?></td>
                  <td class="money small"><?= $t['actual_km'] ? number_format((float)$t['actual_km'], 0) : '—'; ?></td>
                  <td class="money"><?= htmlspecialchars($t['currency']); ?> <?= number_format((float)$t['invoice_amount'], 2, '.', ','); ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot class="table-light">
              <tr><th colspan="6" class="text-end">Selected subtotal</th><th class="money"><span id="selSubtotal">0.00</span></th></tr>
              <tr><th colspan="6" class="text-end">VAT (<span id="vatDisplay">18</span>%)</th><th class="money"><span id="selVat">0.00</span></th></tr>
              <tr><th colspan="6" class="text-end fs-5">Grand total</th><th class="money fs-5"><span id="selTotal">0.00</span></th></tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

    <!-- Step 3: invoice details -->
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Step 3 · Invoice details</h6>
        <div class="row g-3">
          <div class="col-md-3"><label class="form-label">Invoice date</label>
            <input type="date" name="invoice_date" class="form-control" value="<?= date('Y-m-d'); ?>"></div>
          <div class="col-md-3"><label class="form-label">Payment terms</label>
            <input type="text" name="payment_terms" id="terms" class="form-control" value="Net 30" oninput="deriveDue();"></div>
          <div class="col-md-3"><label class="form-label">Due date</label>
            <input type="date" name="due_date" id="dueDate" class="form-control"></div>
          <div class="col-md-3"><label class="form-label">Currency</label>
            <select name="currency" class="form-select"><option value="TZS">TZS</option><option value="USD">USD</option></select></div>

          <div class="col-md-3"><label class="form-label">VAT %</label>
            <input type="number" min="0" max="30" step="0.01" name="vat_rate" id="vatRate" class="form-control" value="18" oninput="recalc();"></div>
          <div class="col-md-3"><label class="form-label">Revenue account</label>
            <select name="revenue_account" class="form-select">
              <option value="4010">4010 · Regional Freight Revenue</option>
              <option value="4020">4020 · In-town Freight Revenue</option>
              <option value="4100">4100 · Other Operating Revenue</option>
            </select></div>
          <div class="col-md-6"><label class="form-label">Billing address (optional)</label>
            <input type="text" name="billing_address" class="form-control" placeholder="Customer billing address"></div>

          <div class="col-md-6"><label class="form-label">Notes (internal)</label>
            <textarea name="notes" rows="2" class="form-control"></textarea></div>
          <div class="col-md-6"><label class="form-label">Footer note (printed on invoice)</label>
            <textarea name="footer_note" rows="2" class="form-control">Please pay by bank transfer. Reference the invoice number.</textarea></div>
        </div>
      </div>
      <div class="card-footer bg-white d-flex justify-content-end gap-2 py-3">
        <a href="<?= PROOT; ?>CustomerInvoices" class="btn btn-outline-secondary">Cancel</a>
        <button class="btn btn-primary"><i class="fas fa-file-invoice me-1"></i>Create draft invoice</button>
      </div>
    </div>
  </form>
<?php endif; ?>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const boxes  = document.querySelectorAll('.js-trip');
const chkAll = document.getElementById('chkAll');
const vatIn  = document.getElementById('vatRate');
const vatDp  = document.getElementById('vatDisplay');
const subEl  = document.getElementById('selSubtotal');
const vatEl  = document.getElementById('selVat');
const totEl  = document.getElementById('selTotal');
const fmt = v => v.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
function recalc() {
    let sub = 0;
    boxes.forEach(b => { if (b.checked) sub += parseFloat(b.dataset.amt); });
    const vr = parseFloat(vatIn?.value || '0') || 0;
    const vat = sub * vr / 100;
    subEl && (subEl.textContent = fmt(sub));
    vatEl && (vatEl.textContent = fmt(vat));
    totEl && (totEl.textContent = fmt(sub + vat));
    vatDp && (vatDp.textContent = vr);
}
chkAll && chkAll.addEventListener('change', () => { boxes.forEach(b => b.checked = chkAll.checked); recalc(); });
boxes.forEach(b => b.addEventListener('change', recalc));
function deriveDue() {
    const t = document.getElementById('terms').value;
    const m = t.match(/(\d+)/);
    if (!m) return;
    const days = parseInt(m[1], 10);
    const dt = document.querySelector('[name="invoice_date"]').value;
    if (!dt) return;
    const d = new Date(dt); d.setDate(d.getDate() + days);
    document.getElementById('dueDate').value = d.toISOString().slice(0, 10);
}
function validateBill() {
    const any = Array.from(boxes).some(b => b.checked);
    if (!any) { alert('Select at least one trip.'); return false; }
    return true;
}
deriveDue();
recalc();
</script>
<?php $this->end(); ?>
