<?php
$rows = $rows ?? [];
$counts = $counts ?? [];
$q = $q ?? '';
$status = $status ?? 'all';
$due = $due ?? 'all';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$accountId = (int) ($accountId ?? 0);
$accounts = $accounts ?? [];
$owners = $owners ?? [];
$orders = $orders ?? [];
$page = (int) ($page ?? 1);
$pages = (int) ($pages ?? 1);
$statusLabels = [
    'unpaid' => 'Unpaid',
    'partial' => 'Partial',
    'paid' => 'Paid',
    'void' => 'Void',
];
?>
<div class="svc-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Invoices &amp; payments</h1>
      <p class="page-sub mb-0">What was billed and what was paid. Open a row to record a payment. Customers see their own bills on the Customer Portal.</p>
    </div>
    <?php if (can_edit('invoices')): ?>
      <a class="btn btn-primary" href="#invoice-create"><i class="bi bi-plus-lg"></i> New invoice</a>
    <?php endif; ?>
  </div>
  <div class="task-summary mb-3">
    <?php foreach ([['Unpaid', $counts['unpaid'] ?? 0, 'bi-exclamation-circle-fill', '#ef4444', '#fef2f2'], ['Partial', $counts['partial'] ?? 0, 'bi-pie-chart-fill', '#ea580c', '#fff7ed'], ['Paid', $counts['paid'] ?? 0, 'bi-check-circle-fill', '#16a34a', '#f0fdf4'], ['All', $counts['all'] ?? 0, 'bi-receipt', '#2563eb', '#eff6ff']] as $s): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div><div class="task-summary-n"><?= (int) $s[1] ?></div><div class="task-summary-l"><?= e($s[0]) ?></div></div>
      </div>
    <?php endforeach; ?>
  </div>

  <form class="task-filters opp-filters card-soft p-3 mb-3" method="get">
    <div class="task-filter-search">
      <label class="form-label" for="inv-q">Search</label>
      <input class="form-control" id="inv-q" name="q" value="<?= e($q) ?>" placeholder="Search title, invoice number, or account" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="inv-assigned">Assigned to</label>
      <select class="form-select" id="inv-assigned" name="assigned">
        <option value="0" <?= $assigned === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($owners as $o): ?>
          <option value="<?= (int) $o['id'] ?>" <?= $assigned === (int) $o['id'] ? 'selected' : '' ?>><?= e(trim($o['first_name'] . ' ' . $o['last_name'])) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php endif; ?>
    <div>
      <label class="form-label" for="inv-account"><?= e(noun('account', 'Account')) ?></label>
      <select class="form-select" id="inv-account" name="account">
        <option value="0" <?= $accountId === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($accounts as $acc): ?>
          <option value="<?= (int) $acc['id'] ?>" <?= $accountId === (int) $acc['id'] ? 'selected' : '' ?>><?= e($acc['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="inv-status">Status</label>
      <select class="form-select" id="inv-status" name="status">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All</option>
        <option value="unpaid" <?= $status === 'unpaid' ? 'selected' : '' ?>>Unpaid</option>
        <option value="partial" <?= $status === 'partial' ? 'selected' : '' ?>>Partial</option>
        <option value="paid" <?= $status === 'paid' ? 'selected' : '' ?>>Paid</option>
        <option value="void" <?= $status === 'void' ? 'selected' : '' ?>>Void</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="inv-due">Due</label>
      <select class="form-select" id="inv-due" name="due">
        <option value="all" <?= $due === 'all' ? 'selected' : '' ?>>All</option>
        <option value="overdue" <?= $due === 'overdue' ? 'selected' : '' ?>>Overdue</option>
        <option value="week" <?= $due === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $due === 'month' ? 'selected' : '' ?>>This month</option>
      </select>
    </div>
    <div class="task-filter-go">
      <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
    </div>
  </form>

  <div class="row g-3">
    <div class="col-lg-7">
      <?php if (!$rows): ?>
        <div class="card-soft task-empty"><div class="task-empty-icon"><i class="bi bi-receipt"></i></div><h2>No invoices</h2><p>Try another filter, or create one from an order or add a bill here.</p></div>
      <?php else: foreach ($rows as $r):
          $stCode = (string) $r['status'];
          $st = commerce_status_label($stCode, $statusLabels[$stCode] ?? null);
          $amt = (float) $r['amount'];
          $paid = (float) $r['paid_amount'];
          $left = max(0, $amt - $paid);
          $pct = $amt > 0 ? min(100, round(($paid / $amt) * 100)) : ($stCode === 'paid' ? 100 : 0);
          $overdue = !in_array($stCode, ['paid', 'void'], true) && !empty($r['due_date']) && date('Y-m-d', strtotime((string) $r['due_date'])) < date('Y-m-d');
          $tone = $overdue ? 'late' : $st['tone'];
      ?>
        <div class="svc-visit svc-tone-<?= e($tone) ?>">
          <a class="svc-visit-main" href="<?= e(url('invoices/' . $r['id'])) ?>">
            <div class="svc-visit-icon"><i class="bi bi-receipt"></i></div>
            <div class="min-w-0 flex-grow-1">
              <div class="svc-visit-name"><?= e($r['title']) ?></div>
              <div class="svc-visit-sub">
                <span><i class="bi bi-hash"></i> <?= e($r['number']) ?></span>
                <?php if (!empty($r['account_name'])): ?><span><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></span><?php endif; ?>
                <?php if (!empty($r['owner_name'])): ?><span><i class="bi bi-person"></i> <?= e($r['owner_name']) ?></span><?php endif; ?>
                <?php if (!empty($r['due_date'])): ?><span><i class="bi bi-calendar3"></i> Due <?= e(dt_fmt($r['due_date'])) ?></span><?php endif; ?>
                <?php if ($overdue): ?><span><i class="bi bi-exclamation-circle"></i> Overdue</span><?php endif; ?>
                <?php if (!empty($r['file_name'])): ?><span><i class="bi bi-file-earmark-pdf"></i> PDF</span><?php endif; ?>
              </div>
              <div class="inv-bar inv-bar-<?= e($stCode) ?>" aria-hidden="true"><span style="width: <?= (int) $pct ?>%"></span></div>
            </div>
            <div class="task-meta">
              <div class="svc-visit-amt">
                <strong><?= e(money_fmt($stCode === 'paid' ? $amt : $left)) ?></strong>
                <span><?= $stCode === 'paid' ? 'Paid' : 'Still due' ?></span>
              </div>
              <span class="due-pill <?= e($overdue ? 'due-overdue' : $st['class']) ?>"><?= e($overdue ? 'Overdue' : $st['text']) ?></span>
            </div>
          </a>
        </div>
      <?php endforeach; endif; ?>
      <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
    </div>
    <?php if (can_edit('invoices')): ?>
    <div class="col-lg-5" id="invoice-create">
      <form class="svc-req ajax-form mb-3" action="<?= e(url('invoices')) ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <div class="svc-req-head"><span class="svc-req-icon"><i class="bi bi-bag-check"></i></span><div><div class="svc-req-kicker">From an order</div><h2>Bill what they bought</h2><p>Upload the invoice PDF. Creates an unpaid bill from a real order.</p></div></div>
        <div class="svc-req-body">
          <label class="form-label">Order *</label>
          <select class="form-select mb-2" name="order_id" required>
            <option value="">Select an order</option>
            <?php foreach ($orders as $o): ?><option value="<?= (int) $o['id'] ?>"><?= e($o['number'] . ' · ' . $o['account_name']) ?></option><?php endforeach; ?>
          </select>
          <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-primary" type="submit">Create invoice</button>
        </div>
      </form>
      <form class="svc-req ajax-form" action="<?= e(url('invoices')) ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <div class="svc-req-head"><span class="svc-req-icon"><i class="bi bi-plus-lg"></i></span><div><div class="svc-req-kicker">Or add a bill</div><h2>Invoice this customer</h2><p>Upload the invoice PDF. Use this when there is no order yet.</p></div></div>
        <div class="svc-req-body">
          <label class="form-label"><?= e(noun('account', 'Account')) ?> *</label>
          <select class="form-select mb-2" name="account_id" required><option value="">Select</option><?php foreach ($accounts as $acc): ?><option value="<?= (int) $acc['id'] ?>"><?= e($acc['name']) ?></option><?php endforeach; ?></select>
          <label class="form-label">Title *</label><input class="form-control mb-2" name="title" required>
          <label class="form-label">Amount</label><input class="form-control mb-2" name="amount" type="number" step="0.01" min="0">
          <label class="form-label">Due</label><input class="form-control mb-2" type="date" name="due_date">
          <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-primary" type="submit">Save invoice</button>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
