<?php /** /app/views/admin/pedidos/index.php */ ?>

<form method="get" class="filter-bar">
  <input type="text" name="busca" class="form-control" placeholder="Código, cliente, e-mail..." value="<?= e($filtros['busca'] ?? '') ?>">
  <select name="status" class="form-select">
    <option value="">Todos os status</option>
    <?php foreach (status_pedido() as $key => $st): ?>
      <option value="<?= e($key) ?>" <?= ($filtros['status'] ?? '') === $key ? 'selected' : '' ?>><?= e($st['label']) ?></option>
    <?php endforeach; ?>
  </select>
  <button type="submit" class="btn">Filtrar</button>
  <a href="<?= admin_url('pedidos') ?>" class="btn btn-light">Limpar</a>
</form>

<?php if (empty($pedidos)): ?>
  <div class="card" style="text-align:center;padding:60px">
    <h3>Nenhum pedido encontrado</h3>
  </div>
<?php else: ?>
<table class="table">
  <thead>
    <tr>
      <th>Código</th><th>Cliente</th><th>Contato</th>
      <th>Itens</th><th>Total</th><th>Status</th><th>Data</th><th></th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($pedidos as $p): $st = status_pedido()[$p['status']] ?? null; ?>
    <tr>
      <td><strong><?= e($p['codigo']) ?></strong></td>
      <td>
        <?= e($p['cliente_nome']) ?><br>
        <?php if (!empty($p['cliente_empresa'])): ?>
          <small style="color:var(--admin-muted)"><?= e($p['cliente_empresa']) ?></small>
        <?php endif; ?>
      </td>
      <td>
        <small><?= e($p['cliente_email']) ?></small><br>
        <small><?= e($p['cliente_telefone']) ?></small>
      </td>
      <td><?= (int)$p['total_itens'] ?></td>
      <td><?= $p['total_produtos'] ? price((float)$p['total_produtos']) : '-' ?></td>
      <td><?php if ($st): ?><span class="badge badge-<?= e($st['cor']) ?>"><?= e($st['label']) ?></span><?php endif; ?></td>
      <td><small><?= date_br($p['created_at'], true) ?></small></td>
      <td><a href="<?= admin_url('pedidos/ver/' . $p['id']) ?>" class="btn btn-sm btn-outline">Ver</a></td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<?php if ($pagination['pages'] > 1): ?>
  <div class="pagination">
    <?php
      $params = $_GET; unset($params['page']);
      $base = admin_url('pedidos') . '?' . http_build_query($params);
      $sep = str_contains($base, '?') ? '&' : '?';
      for ($i = 1; $i <= $pagination['pages']; $i++):
    ?>
      <?php if ($i === $pagination['page']): ?>
        <span class="current"><?= $i ?></span>
      <?php else: ?>
        <a href="<?= $base . $sep . 'page=' . $i ?>"><?= $i ?></a>
      <?php endif; ?>
    <?php endfor; ?>
  </div>
<?php endif; ?>
<?php endif; ?>
