<?php $this->start('body'); ?>
<?php $b = $this->data['bill']; $payments = $this->data['payments'];
$bg = ['draft'=>'secondary','posted'=>'warning text-dark','paid'=>'success','void'=>'dark'][$b['status']] ?? 'light';
$balance = (float)$b['total_amount'] - (float)$b['amount_paid'];
$overdue = $b['status'] === 'posted' && $b['due_date'] && strtotime($b['due_date']) < strtotime('today');
?>

<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 me-2 text-muted"></i>
      <span class="font-monospace"><?= htmlspecialchars($b['bill_no']); ?></span>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($b['status']); ?></span>
      <?php if ($overdue): ?><span class="badge bg-danger ms-1">Overdue</span><?php endif; ?>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars($b['vendor_name'] ?? '—'); ?>
      <?php if ($b['supplier_ref']): ?> · supplier ref <?= htmlspecialchars($b['supplier_ref']); ?><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>SupplierBills" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Bills</a>
</div>

<?= flashHtml(); ?>

<?php if ($b['status'] === 'void'): ?>
  <div class="alert alert-dark py-2 small"><strong>Void:</strong> <?= htmlspecialchars($b['void_reason'] ?: '(no reason)'); ?></div>
<?php endif; ?>

<!-- KPI strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Subtotal</div>
    <div class="fs-5 fw-bold">TZS <?= number_format((float)$b['subtotal'], 2); ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">VAT</div>
    <div class="fs-5 fw-bold">TZS <?= number_format((float)$b['vat_amount'], 2); ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Total</div>
    <div class="fs-4 fw-bold text-primary">TZS <?= number_format((float)$b['total_amount'], 2); ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Balance due</div>
    <div class="fs-4 fw-bold <?= $balance > 0.005 ? 'text-danger' : 'text-success'; ?>">TZS <?= number_format($balance, 2); ?></div>
    <div class="small text-muted">paid <?= number_format((float)$b['amount_paid'], 2); ?></div>
  </div></div></div>
</div>

<!-- Actions -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>
    <?php if ($b['status'] === 'draft'): ?>
      <form method="POST" action="<?= PROOT; ?>SupplierBills/post/<?= (int)$b['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
        <button class="btn btn-sm btn-warning"><i class="fas fa-file-signature me-1"></i>Post to ledger</button>
      </form>
    <?php endif; ?>
    <?php if ($b['status'] === 'posted' && $balance > 0.005): ?>
      <a href="<?= PROOT; ?>SupplierPayments/record?vendor_id=<?= (int)$b['vendor_id']; ?>" class="btn btn-sm btn-success"><i class="fas fa-money-bill-transfer me-1"></i>Record payment</a>
    <?php endif; ?>
    <?php if ($b['journal_entry_id']): ?>
      <a href="<?= PROOT; ?>Journals/view/<?= (int)$b['journal_entry_id']; ?>" class="btn btn-sm btn-outline-primary ms-auto"><i class="fas fa-file-alt me-1"></i>Journal</a>
    <?php endif; ?>
    <?php if ($b['status'] !== 'void' && (float)$b['amount_paid'] < 0.005): ?>
      <button type="button" class="btn btn-sm btn-outline-danger <?= $b['journal_entry_id'] ? '' : 'ms-auto'; ?>" onclick="doVoid()"><i class="fas fa-ban me-1"></i>Void</button>
    <?php endif; ?>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100"><div class="card-body">
      <h6 class="text-uppercase text-muted small mb-3">Bill details</h6>
      <dl class="row mb-0 small">
        <dt class="col-5 text-muted fw-normal">Supplier</dt><dd class="col-7"><a href="<?= PROOT; ?>Suppliers/view/<?= (int)$b['vendor_id']; ?>" class="text-decoration-none"><?= htmlspecialchars($b['vendor_name'] ?: '—'); ?></a></dd>
        <?php if ($b['vendor_tin']): ?><dt class="col-5 text-muted fw-normal">Vendor TIN</dt><dd class="col-7 font-monospace"><?= htmlspecialchars($b['vendor_tin']); ?></dd><?php endif; ?>
        <dt class="col-5 text-muted fw-normal">Bill date</dt><dd class="col-7"><?= humanDate($b['bill_date']); ?></dd>
        <dt class="col-5 text-muted fw-normal">Due date</dt><dd class="col-7"><?= $b['due_date'] ? humanDate($b['due_date']) : '—'; ?></dd>
        <dt class="col-5 text-muted fw-normal">Terms</dt><dd class="col-7"><?= htmlspecialchars(str_replace('_', ' ', (string)$b['payment_terms'])); ?></dd>
        <dt class="col-5 text-muted fw-normal">Expense account</dt><dd class="col-7"><?= htmlspecialchars(($b['expense_code'] ?? '') . ' · ' . ($b['expense_name'] ?? '—')); ?></dd>
        <?php if ($b['notes']): ?><dt class="col-5 text-muted fw-normal">Notes</dt><dd class="col-7"><?= nl2br(htmlspecialchars($b['notes'])); ?></dd><?php endif; ?>
      </dl>
    </div></div>
  </div>
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100"><div class="card-body">
      <h6 class="text-uppercase text-muted small mb-3">Payments · <?= count($payments); ?></h6>
      <?php if (empty($payments)): ?>
        <div class="text-center text-muted small py-4">No payments yet.</div>
      <?php else: ?>
        <table class="table table-sm mb-0">
          <thead class="table-light"><tr><th>Payment</th><th>Date</th><th>Method</th><th class="money">Applied</th></tr></thead>
          <tbody>
            <?php foreach ($payments as $p): ?>
              <tr>
                <td class="small"><a href="<?= PROOT; ?>SupplierPayments/view/<?= (int)$p['c0d']; ?>" class="font-monospace text-decoration-none"><?= htmlspecialchars($p['payment_no']); ?></a></td>
                <td class="small"><?= humanDate($p['payment_date']); ?></td>
                <td class="small text-muted"><?= htmlspecialchars(str_replace('_', ' ', $p['payment_method'])); ?></td>
                <td class="money font-monospace small"><?= number_format((float)$p['amount_applied'], 2); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div></div>
  </div>
</div>

<form id="voidForm" method="POST" action="<?= PROOT; ?>SupplierBills/voidBill/<?= (int)$b['c0d']; ?>" class="d-none"><?= csrf_field(); ?><input type="hidden" name="reason" id="fReason"></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
function doVoid() {
    $.confirm({
        title: 'Void this bill?', type: 'red',
        content: '<label class="form-label small">Reason <span class="text-danger">*</span></label><textarea id="rn" class="form-control form-control-sm" rows="3"></textarea>',
        buttons: {
            go: { text: 'Void', btnClass: 'btn-danger', action: function() {
                const r = document.getElementById('rn').value.trim();
                if (!r) { $.alert('Reason required.'); return false; }
                document.getElementById('fReason').value = r;
                document.getElementById('voidForm').submit();
            }},
            back: function(){}
        }
    });
}
</script>
<?php $this->end(); ?>
