<?php
$r = $row;
$st = (string) $r['status'];
$amt = (float) $r['amount'];
$paid = (float) $r['paid_amount'];
$left = max(0, $amt - $paid);
$pct = $amt > 0 ? min(100, round(($paid / $amt) * 100)) : ($st === 'paid' ? 100 : 0);
$labels = [
    'unpaid' => 'Unpaid',
    'partial' => 'Partial',
    'paid' => 'Paid',
    'void' => 'Void',
];
$chip = commerce_status_label($st, $labels[$st] ?? null);
$stLabel = $chip['text'];
$due = due_label($r['due_date'] ?? null, $st === 'paid' ? 'completed' : ($st === 'void' ? 'cancelled' : 'open'));
$overdue = ($due['class'] ?? '') === 'due-overdue';
$dueNote = $overdue ? ' · Overdue' : (($due['text'] ?? '') === 'Today' ? ' · Today' : '');
$nextCopy = match ($st) {
    'paid' => ['Paid in full', 'This bill is closed. The customer can still see it on the Customer Portal.'],
    'void' => ['Void', 'This invoice is void.'],
    'partial' => ['Balance left', 'Record the rest of the payment when it comes in.'],
    default => ['Waiting for payment', 'Mark it paid when the customer pays, or record a partial amount.'],
};
$steps = [
    ['label' => 'Unpaid'],
    ['label' => 'Partial'],
    ['label' => 'Paid'],
];
$currentIdx = match ($st) {
    'paid' => 2,
    'partial' => 1,
    'void' => 2,
    default => 0,
};
$canEdit = can_edit('invoices');
$canPay = $canEdit && $st !== 'paid' && $st !== 'void';
$hasPdf = !empty($r['file_name']);
$owner = trim((string) ($r['owner_name'] ?? ''));
$recTone = $overdue ? 'lost' : $chip['rec'];
?>
<div class="rec-page vis-page">
  <a class="rec-back" href="<?= e(url('invoices')) ?>"><i class="bi bi-arrow-left"></i> All invoices</a>

  <div class="rec-hero rec-tone-<?= e($recTone) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar doc-hero-<?= e($recTone) ?>"><i class="bi bi-receipt"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker">Invoice · <?= e((string) ($r['number'] ?? '')) ?></p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($r['title']) ?></h1>
          <span class="due-pill <?= e($overdue ? 'due-overdue' : $chip['class']) ?>"><?= e($overdue ? 'Overdue' : $stLabel) ?></span>
        </div>
        <div class="rec-hero-sub">
          <a href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></a>
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php endif; ?>
          <?php if (!empty($r['order_number'])): ?><span><i class="bi bi-bag-check"></i> <?= e($r['order_number']) ?></span><?php endif; ?>
          <span><i class="bi bi-calendar3"></i> Due <?= e(dt_fmt($r['due_date'])) ?></span>
        </div>
      </div>
    </div>
    <div class="rec-hero-actions">
      <div class="rec-hero-amt">
        <strong><?= e(money_fmt($st === 'paid' ? $amt : $left)) ?></strong>
        <span><?= $st === 'paid' ? 'Paid in full' : ($st === 'void' ? 'Void' : 'Still due') ?></span>
      </div>
      <a class="btn btn-outline-primary" href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> Customer</a>
    </div>
  </div>

  <ol class="quo-steps" style="grid-template-columns: repeat(3, minmax(0, 1fr))">
    <?php foreach ($steps as $i => $step):
        $state = $i < $currentIdx ? 'is-done' : ($i === $currentIdx ? 'is-now' : '');
    ?>
      <li class="quo-step <?= e($state) ?>">
        <span class="quo-step-dot"><?php if ($i < $currentIdx): ?><i class="bi bi-check"></i><?php else: ?><?= $i + 1 ?><?php endif; ?></span>
        <span><?= e($step['label']) ?></span>
      </li>
    <?php endforeach; ?>
  </ol>

  <?php if ($overdue): ?>
    <div class="quo-reject"><i class="bi bi-exclamation-triangle-fill"></i> This bill is past due. Remaining <?= e(money_fmt($left)) ?>.</div>
  <?php endif; ?>

  <div class="row g-3">
    <div class="col-lg-7">
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-pie-chart',
            'title' => 'Payment progress',
            'hint' => (int) $pct . '% paid · ' . money_fmt($paid) . ' of ' . money_fmt($amt),
        ]); ?>
        <div class="inv-bar inv-bar-lg inv-bar-<?= e($st) ?>" aria-hidden="true"><span style="width: <?= (int) $pct ?>%"></span></div>
        <?php if (!empty($r['paid_at']) && $st === 'paid'): ?>
          <p class="rec-section-hint mt-2 mb-0">Marked paid <?= e(dt_fmt($r['paid_at'], 'M j, Y g:i A')) ?>.</p>
        <?php endif; ?>
      </div>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-file-earmark-pdf',
            'title' => 'Invoice PDF',
            'hint' => $hasPdf ? (string) $r['file_name'] : 'No PDF attached.',
        ]); ?>
        <p class="rec-section-hint"><?= $hasPdf ? 'Opens in a new tab. The customer can open it on the Customer Portal too.' : 'Upload the invoice PDF so staff and the customer can open it.' ?></p>
        <?php if ($hasPdf): ?>
          <a class="btn btn-primary" href="<?= e(url('invoices/' . $r['id'] . '/file')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right"></i> Open PDF</a>
        <?php endif; ?>
      </div>
      <?php if ($canEdit && !$hasPdf): ?>
      <form class="card-soft rec-card p-3 ajax-form" action="<?= e(url('invoices/' . $r['id'] . '/file')) ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-upload',
            'title' => 'Add PDF',
            'hint' => 'Attach the invoice for staff and the customer.',
        ]); ?>
        <label class="form-label">Invoice PDF *</label>
        <input class="form-control mb-3" type="file" name="pdf" accept="application/pdf,.pdf" required>
        <button class="btn btn-outline-primary" type="submit">Save PDF</button>
      </form>
      <?php endif; ?>
    </div>
    <div class="col-lg-5">
      <?php \App\Core\View::partial('record_facts', [
          'title' => 'About this invoice',
          'hint' => 'What was billed.',
          'icon' => 'bi-receipt',
          'facts' => [
              ['label' => 'Number', 'value' => (string) ($r['number'] ?? '')],
              ['label' => 'Customer', 'value' => (string) ($r['account_name'] ?? ''), 'href' => url('accounts/' . (int) $r['account_id'])],
              ['label' => 'Billed', 'value' => money_fmt($amt)],
              ['label' => 'Paid', 'value' => money_fmt($paid)],
              ['label' => 'Remaining', 'value' => money_fmt($left)],
              ['label' => 'Due', 'value' => dt_fmt($r['due_date']) . $dueNote],
              ['label' => 'Status', 'value' => $stLabel],
              ['label' => 'Owner', 'value' => $owner !== '' ? $owner : 'Unassigned'],
          ],
      ]); ?>
      <section class="svc-req quo-next">
        <div class="svc-req-head">
          <span class="svc-req-icon"><i class="bi bi-lightning-charge"></i></span>
          <div>
            <div class="svc-req-kicker">Next step</div>
            <h2><?= e($nextCopy[0]) ?></h2>
            <p><?= e($nextCopy[1]) ?></p>
          </div>
        </div>
        <div class="svc-req-body">
          <?php if ($canPay): ?>
            <form class="ajax-form" action="<?= e(url('invoices/' . $r['id'] . '/pay')) ?>" method="post">
              <?= csrf_field() ?>
              <label class="form-label">Amount to record</label>
              <input class="form-control mb-2" name="amount" type="number" step="0.01" min="0.01" max="<?= e((string) $left) ?>" value="<?= e((string) $left) ?>">
              <p class="quo-wait mb-3">Leave the full remaining amount to mark it paid. Enter less for a partial payment.</p>
              <button class="btn btn-primary w-100" type="submit">Record payment</button>
            </form>
          <?php else: ?>
            <p class="quo-wait mb-0"><?= $st === 'paid' ? 'Nothing left to collect.' : 'You can view this invoice.' ?></p>
          <?php endif; ?>
        </div>
      </section>
    </div>
  </div>
</div>
