<?php $this->start('body'); ?>
<?php $inv = $this->data['inv']; $lines = $this->data['lines']; $receipts = $this->data['receipts'];
$out = (float)$inv['total_amount'] - (float)$inv['amount_paid'];
$bg = ['draft'=>'secondary','issued'=>'primary','partially_paid'=>'warning','paid'=>'success','void'=>'dark'][$inv['status']] ?? 'secondary';
$overdue = in_array($inv['status'], ['issued','partially_paid'], true) && $inv['due_date'] && strtotime($inv['due_date']) < time();
?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-file-invoice-dollar me-2 text-muted"></i><span class="font-monospace"><?= htmlspecialchars($inv['invoice_no']); ?></span>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_', ' ', $inv['status'])); ?></span>
      <?php if ($overdue): ?><span class="badge bg-danger ms-1" style="font-size:.65em;vertical-align:middle;">OVERDUE</span><?php endif; ?>
    </h5>
    <div class="text-muted small">
      <a href="<?= PROOT; ?>Customers/view/<?= (int)$inv['customer_id']; ?>"><?= htmlspecialchars($inv['customer_name']); ?></a>
      · <?= humanDate($inv['invoice_date']); ?>
      <?php if ($inv['due_date']): ?> · due <?= humanDate($inv['due_date']); ?><?php endif; ?>
      <?php if ($inv['issued_by_name']): ?> · issued by <?= htmlspecialchars($inv['issued_by_name']); ?><?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>CustomerInvoices" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <a href="<?= PROOT; ?>CustomerInvoices/pdf/<?= (int)$inv['c0d']; ?>" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-pdf me-1"></i>PDF</a>
    <a href="<?= PROOT; ?>CustomerInvoices/pdf/<?= (int)$inv['c0d']; ?>?dl=1" class="btn btn-sm btn-outline-secondary" title="Download"><i class="fas fa-download"></i></a>
    <?php if ($inv['status'] === 'draft'): ?>
      <form method="POST" action="<?= PROOT; ?>CustomerInvoices/issue/<?= (int)$inv['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
        <button class="btn btn-sm btn-success"><i class="fas fa-paper-plane me-1"></i>Issue</button>
      </form>
    <?php endif; ?>
    <?php if (in_array($inv['status'], ['issued','partially_paid'], true) && $out > 0): ?>
      <a href="<?= PROOT; ?>CustomerReceipts/record?customer_id=<?= (int)$inv['customer_id']; ?>" class="btn btn-sm btn-warning text-white"><i class="fas fa-hand-holding-usd me-1"></i>Record payment</a>
    <?php endif; ?>
  </div>
</div>

<?= flashHtml(); ?>

<?php if ($inv['status'] === 'void' && $inv['void_reason']): ?>
  <div class="alert alert-dark py-2 small"><i class="fas fa-ban me-1"></i><strong>Void:</strong> <?= htmlspecialchars($inv['void_reason']); ?><?php if ($inv['void_at']): ?> · <?= humanDateTime($inv['void_at']); ?><?php endif; ?></div>
<?php endif; ?>

<div class="row g-3">
  <!-- Left: lines -->
  <div class="col-lg-8">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Lines</h6>
        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="table-light">
              <tr><th>#</th><th>Description</th><th class="money">Qty</th><th class="money">Unit price</th><th class="money">Net</th><th class="money">VAT</th><th class="money">Total</th></tr>
            </thead>
            <tbody>
              <?php foreach ($lines as $ln): ?>
                <tr>
                  <td class="small text-muted"><?= (int)$ln['line_no']; ?></td>
                  <td class="small"><?= htmlspecialchars($ln['description']); ?><?php if ($ln['trip_id']): ?><div class="small text-muted"><i class="fas fa-truck-loading fa-xs me-1"></i><a href="<?= PROOT; ?>Trips/view/<?= (int)$ln['trip_id']; ?>"><?= htmlspecialchars($ln['trip_no'] ?? 'Trip'); ?></a></div><?php endif; ?></td>
                  <td class="money"><?= number_format((float)$ln['quantity'], 0); ?></td>
                  <td class="money"><?= number_format((float)$ln['unit_price'], 2, '.', ','); ?></td>
                  <td class="money"><?= number_format((float)$ln['net_amount'], 2, '.', ','); ?></td>
                  <td class="money small"><?= number_format((float)$ln['vat_amount'], 2, '.', ','); ?> <span class="text-muted">(<?= number_format((float)$ln['vat_rate'], 0); ?>%)</span></td>
                  <td class="money fw-semibold"><?= number_format((float)$ln['total_amount'], 2, '.', ','); ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot class="table-light">
              <tr><th colspan="4" class="text-end">Subtotal</th><th class="money"><?= number_format((float)$inv['subtotal'], 2, '.', ','); ?></th><th class="money"><?= number_format((float)$inv['vat_amount'], 2, '.', ','); ?></th><th class="money"><?= number_format((float)$inv['total_amount'], 2, '.', ','); ?></th></tr>
              <tr><th colspan="6" class="text-end text-success">Amount paid</th><th class="money text-success"><?= number_format((float)$inv['amount_paid'], 2, '.', ','); ?></th></tr>
              <tr><th colspan="6" class="text-end fs-5">Outstanding</th><th class="money fs-5 <?= $out > 0 ? 'text-danger' : 'text-success'; ?>"><?= number_format($out, 2, '.', ','); ?></th></tr>
            </tfoot>
          </table>
        </div>
        <?php if ($inv['footer_note']): ?>
          <div class="small text-muted border-top mt-3 pt-2"><em><?= nl2br(htmlspecialchars($inv['footer_note'])); ?></em></div>
        <?php endif; ?>
      </div>
    </div>

    <?php if (!empty($receipts)): ?>
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-hand-holding-usd me-1"></i>Receipts applied</h6>
          <table class="table table-sm mb-0">
            <thead class="table-light"><tr><th>Receipt #</th><th>Date</th><th>Method</th><th>Reference</th><th class="money">Applied</th><th>Status</th></tr></thead>
            <tbody>
              <?php foreach ($receipts as $rc): ?>
                <tr>
                  <td class="small"><a href="<?= PROOT; ?>CustomerReceipts/view/<?= (int)$rc['receipt_id']; ?>" class="font-monospace"><?= htmlspecialchars($rc['receipt_no']); ?></a></td>
                  <td class="small text-muted"><?= humanDate($rc['receipt_date']); ?></td>
                  <td class="small" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_', ' ', $rc['payment_method'])); ?></td>
                  <td class="small text-muted"><?= htmlspecialchars($rc['reference'] ?: '—'); ?></td>
                  <td class="money"><?= number_format((float)$rc['amount_applied'], 2, '.', ','); ?></td>
                  <td><span class="badge bg-<?= $rc['status'] === 'void' ? 'dark' : 'success'; ?>"><?= htmlspecialchars($rc['status']); ?></span></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- Right: meta + actions -->
  <div class="col-lg-4">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Invoice</h6>
        <dl class="row mb-0 small">
          <dt class="col-5 text-muted fw-normal">Invoice date</dt><dd class="col-7"><?= humanDate($inv['invoice_date']); ?></dd>
          <dt class="col-5 text-muted fw-normal">Due date</dt><dd class="col-7"><?= $inv['due_date'] ? humanDate($inv['due_date']) : '—'; ?></dd>
          <dt class="col-5 text-muted fw-normal">Terms</dt><dd class="col-7"><?= htmlspecialchars($inv['payment_terms'] ?: '—'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Currency</dt><dd class="col-7"><?= htmlspecialchars($inv['currency']); ?></dd>
          <?php if ($inv['issued_at']): ?><dt class="col-5 text-muted fw-normal">Issued at</dt><dd class="col-7"><?= humanDateTime($inv['issued_at']); ?></dd><?php endif; ?>
          <?php if ($inv['journal_entry_id']): ?><dt class="col-5 text-muted fw-normal">Journal</dt><dd class="col-7"><a href="<?= PROOT; ?>Journals/view/<?= (int)$inv['journal_entry_id']; ?>" class="font-monospace">JE #<?= (int)$inv['journal_entry_id']; ?></a></dd><?php endif; ?>
        </dl>
        <?php if ($inv['notes']): ?><hr class="my-2"><div class="text-uppercase text-muted small">Notes</div><div class="small"><?= nl2br(htmlspecialchars($inv['notes'])); ?></div><?php endif; ?>
      </div>
    </div>

    <?php if ($inv['status'] !== 'void' && (float)$inv['amount_paid'] <= 0): ?>
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <h6 class="text-uppercase text-muted small mb-3 text-danger">Danger zone</h6>
          <?php if ($inv['status'] === 'draft'): ?>
            <button class="btn btn-sm btn-outline-danger w-100 mb-2" onclick="doDel()"><i class="fas fa-trash me-1"></i>Delete draft</button>
          <?php else: ?>
            <button class="btn btn-sm btn-outline-danger w-100" onclick="doVoid()"><i class="fas fa-ban me-1"></i>Void invoice</button>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<form id="voidForm" method="POST" action="<?= PROOT; ?>CustomerInvoices/void/<?= (int)$inv['c0d']; ?>" class="d-none"><?= csrf_field(); ?><input type="hidden" name="reason" id="voidReason"></form>
<form id="delForm"  method="POST" action="<?= PROOT; ?>CustomerInvoices/delete/<?= (int)$inv['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
function doVoid() {
    $.confirm({
        title: 'Void this invoice?',
        content: '<div class="mb-2 small">Reverses the journal entry and marks the invoice void. Cannot be un-done.</div>' +
                 '<label class="form-label small">Reason <span class="text-danger">*</span></label>' +
                 '<textarea id="rn" class="form-control form-control-sm" rows="3" placeholder="Duplicate, wrong customer, cancelled trip..."></textarea>',
        type: 'red',
        buttons: {
            go: { text: 'Void', btnClass: 'btn-danger', action: function() {
                const r = document.getElementById('rn').value.trim();
                if (!r) { $.alert('Please enter a reason.'); return false; }
                document.getElementById('voidReason').value = r;
                document.getElementById('voidForm').submit();
            }},
            back: function(){}
        }
    });
}
function doDel() {
    $.confirm({ title: 'Delete this draft?', content: 'Soft-deletes the draft invoice. No journal impact.', type: 'red',
        buttons: { remove: { text: 'Delete', btnClass: 'btn-danger', action: () => document.getElementById('delForm').submit() }, back: function(){} } });
}
</script>
<?php $this->end(); ?>
