<?php
$title = 'Devoluções';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

/*
  Filtros:
  - status: ABERTAS (default), CONCLUIDAS, COBRANCA, CANCELADAS, TODAS
  - q: busca por matrícula/nome
*/
$allowed = ['ABERTAS','CONCLUIDAS','COBRANCA','CANCELADAS','TODAS'];
$st = $_GET['status'] ?? 'ABERTAS';
if (!in_array($st, $allowed, true)) $st = 'ABERTAS';

$q  = trim($_GET['q'] ?? '');

$where = [];
$args  = [];

switch ($st) {
  case 'CONCLUIDAS':
    $where[] = "rr.status='CONCLUIDA'";
    break;
  case 'COBRANCA':
    $where[] = "rr.status='COBRANCA'";
    break;
  case 'CANCELADAS':
    $where[] = "rr.status='CANCELADA'";
    break;
  case 'TODAS':
    // sem filtro por status
    break;
  default: // ABERTAS
    $where[] = "rr.status IN ('ABERTA','EM_ANDAMENTO')";
    $st = 'ABERTAS';
}

if ($q !== '') {
  $where[] = "(e.matricula LIKE ? OR e.nome LIKE ?)";
  $like = "%{$q}%";
  $args[] = $like;
  $args[] = $like;
}

$sql = "SELECT
          rr.id, rr.status, rr.deadline, rr.created_at, rr.updated_at,
          e.matricula, e.nome,
          (SELECT COUNT(*) FROM return_request_items i WHERE i.request_id = rr.id) AS itens
        FROM return_requests rr
        JOIN employees e ON e.id = rr.employee_id";
if ($where) $sql .= " WHERE ".implode(' AND ', $where);
$sql .= " ORDER BY rr.id DESC LIMIT 200";

$rows = $pdo->prepare($sql);
$rows->execute($args);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center mb-3">
    <h2 class="h5 m-0">Solicitações de devolução</h2>

    <form class="d-flex gap-2 ms-auto" method="get" style="max-width:620px; width:100%;">
      <select name="status" class="form-select form-select-sm" style="max-width:220px">
        <?php foreach ($allowed as $opt): ?>
          <option <?= $st===$opt?'selected':'' ?>><?= $opt ?></option>
        <?php endforeach; ?>
      </select>
      <div class="input-group input-group-sm">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input class="form-control" name="q" placeholder="Matrícula ou nome" value="<?= h($q) ?>">
        <button class="btn btn-outline-primary">Filtrar</button>
        <a class="btn btn-outline-secondary" href="<?= base_url('return_requests.php') ?>">Limpar</a>
      </div>
    </form>
  </div>

  <div class="table-responsive">
    <table class="table table-hover table-striped align-middle">
      <thead>
        <tr>
          <!-- ID oculto -->
          <th>Matrícula</th>
          <th>Nome</th>
          <th>Status</th>
          <th>Prazo</th>
          <th>Itens</th>
          <th>Aberta em</th>
          <th>Atualizada</th>
          <th class="text-end">Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <?php
            $isOpen = in_array($r['status'], ['ABERTA','EM_ANDAMENTO'], true);
            $over   = ($isOpen && !empty($r['deadline']) && $r['deadline'] < date('Y-m-d'));
          ?>
          <tr class="<?= $over ? 'table-warning' : '' ?>">
            <td><?= h($r['matricula']) ?></td>
            <td><?= h($r['nome']) ?></td>
            <td><span class="badge bg-secondary"><?= t_rr_status($r['status']) ?></span></td>
            <td><?= br_date($r['deadline'] ?? null) ?></td>
            <td><?= (int)$r['itens'] ?></td>
            <td><?= br_datetime($r['created_at'] ?? null) ?></td>
            <td><?= br_datetime($r['updated_at'] ?? null) ?></td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-primary"
                 href="<?= base_url('return_request_view.php?id='.(int)$r['id']) ?>">
                Abrir
              </a>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?>
          <tr><td colspan="8" class="text-muted">Nenhuma solicitação encontrada.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>

