<?php
$rows = $rows ?? [];
$counts = $counts ?? [];
$q = $q ?? '';
$status = $status ?? 'open';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$accountId = (int) ($accountId ?? 0);
$accounts = $accounts ?? [];
$owners = $owners ?? [];
$page = (int) ($page ?? 1);
$pages = (int) ($pages ?? 1);
$statusLabels = [
    'open' => 'Open',
    'fulfilled' => 'Fulfilled',
    'cancelled' => 'Cancelled',
];
?>
<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">Orders</h1>
      <p class="page-sub mb-0">Real order history on the customer — not only a sales note.</p>
    </div>
    <?php if (can_edit('orders') && $accounts !== []): ?>
      <a class="btn btn-primary" href="#order-create"><i class="bi bi-plus-lg"></i> New order</a>
    <?php endif; ?>
  </div>
  <div class="task-summary mb-3">
    <?php foreach ([['Open', $counts['open'] ?? 0, 'bi-bag-fill', '#2563eb', '#eff6ff'], ['Fulfilled', $counts['fulfilled'] ?? 0, 'bi-check-circle-fill', '#16a34a', '#f0fdf4'], ['Cancelled', $counts['cancelled'] ?? 0, 'bi-x-circle-fill', '#ef4444', '#fef2f2'], ['All', $counts['all'] ?? 0, 'bi-collection-fill', '#0f766e', '#f0fdfa']] 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="ord-q">Search</label>
      <input class="form-control" id="ord-q" name="q" value="<?= e($q) ?>" placeholder="Search title, order number, or account" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="ord-assigned">Assigned to</label>
      <select class="form-select" id="ord-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="ord-account"><?= e(noun('account', 'Account')) ?></label>
      <select class="form-select" id="ord-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="ord-status">Status</label>
      <select class="form-select" id="ord-status" name="status">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All</option>
        <option value="open" <?= $status === 'open' ? 'selected' : '' ?>>Open</option>
        <option value="fulfilled" <?= $status === 'fulfilled' ? 'selected' : '' ?>>Fulfilled</option>
        <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelled</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-bag"></i></div><h2>No orders</h2><p>Try another filter, or log an order on a customer.</p></div>
      <?php else: foreach ($rows as $r):
          $st = commerce_status_label((string) $r['status'], $statusLabels[$r['status']] ?? null);
      ?>
        <div class="svc-visit svc-tone-<?= e($st['tone']) ?>">
          <div class="svc-visit-main">
            <div class="svc-visit-icon"><i class="bi bi-bag-check"></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'])): ?>
                  <a href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></a>
                <?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['ordered_at'])): ?><span><i class="bi bi-calendar3"></i> <?= e(dt_fmt($r['ordered_at'])) ?></span><?php endif; ?>
              </div>
            </div>
            <div class="task-meta">
              <div class="svc-visit-amt"><strong><?= e(money_fmt($r['amount'])) ?></strong><span>Amount</span></div>
              <span class="due-pill <?= e($st['class']) ?>"><?= e($st['text']) ?></span>
            </div>
          </div>
          <?php if (can_edit('orders') && $r['status'] === 'open'): ?>
            <form class="ajax-form svc-attend" action="<?= e(url('orders/' . $r['id'] . '/status')) ?>" method="post"><?= csrf_field() ?><input type="hidden" name="status" value="fulfilled"><button class="btn btn-sm btn-outline-success" type="submit"><i class="bi bi-check2-circle"></i> Fulfill</button></form>
          <?php endif; ?>
        </div>
      <?php endforeach; endif; ?>
      <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
    </div>
    <?php if (can_edit('orders')): ?>
    <div class="col-lg-5" id="order-create">
      <form class="svc-req ajax-form" action="<?= e(url('orders')) ?>" method="post">
        <?= 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">New order</div><h2>Log what they bought</h2><p>Saved on the customer. Marketing lists can use this date.</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">
          <label class="form-label">Order date</label><input class="form-control mb-2" type="date" name="ordered_at" value="<?= e(date('Y-m-d')) ?>">
          <div class="svc-req-foot">
            <div class="svc-wait-chips"><span class="lst-chip">Saved on customer</span></div>
            <button class="btn btn-primary" type="submit"><i class="bi bi-check2"></i> Save order</button>
          </div>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
