<?php
// reports.php — Relatórios
$title = 'Relatórios';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

/* --------------------------------------------------------------------------
   Helpers locais (nomes exclusivos para não colidir)
---------------------------------------------------------------------------*/
function rep_has_table(PDO $pdo, string $tbl): bool {
  static $cache = [];
  if (isset($cache[$tbl])) return $cache[$tbl];
  $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.TABLES
                       WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
  $st->execute([$tbl]);
  return $cache[$tbl] = (bool)$st->fetchColumn();
}
function rep_has_col(PDO $pdo, string $tbl, string $col): bool {
  static $cache = [];
  $k = "$tbl.$col";
  if (isset($cache[$k])) return $cache[$k];
  $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS
                       WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
  $st->execute([$tbl,$col]);
  return $cache[$k] = (bool)$st->fetchColumn();
}
function rep_br_to_sql_date(?string $s): ?string {
  $s = trim((string)$s);
  if ($s==='') return null;
  if (!preg_match('/^(?<d>\d{2})\/(?<m>\d{2})\/(?<y>\d{4})$/', $s, $m)) return null;
  $d=(int)$m['d']; $mo=(int)$m['m']; $y=(int)$m['y'];
  if (!checkdate($mo,$d,$y)) return null;
  return sprintf('%04d-%02d-%02d',$y,$mo,$d);
}
function rep_get_br_date_filter(string $key, array &$warnings): array {
  $br  = trim($_GET[$key] ?? '');
  $sql = rep_br_to_sql_date($br);
  if ($br!=='' && $sql===null) $warnings[] = "Data inválida em '".htmlspecialchars($key,ENT_QUOTES)."'";
  return [$br,$sql];
}
function rep_whitelist(string $val, array $allowed): string {
  return in_array($val,$allowed,true)?$val:'';
}
function rep_safe_like_input(string $s, int $max=80): string {
  $s = trim($s);
  if ($s==='') return '';
  return mb_substr($s,0,$max);
}

/* --------------------------------------------------------------------------
   Tabs
---------------------------------------------------------------------------*/
$tab   = $_GET['tab'] ?? 'loans';
$alias = ['equipment'=>'stock','logs'=>'moves'];
if (isset($alias[$tab])) $tab = $alias[$tab];
$valid_tabs = ['loans','stock','returns','moves'];
if (!in_array($tab,$valid_tabs,true)) $tab = 'loans';

$warnings = [];
$export   = (int)($_GET['export'] ?? 0) === 1;

/* ==========================================================================

   EMPRÉSTIMOS

============================================================================*/
if ($tab==='loans') {
  $status_values = [];
  foreach ($pdo->query("SELECT DISTINCT status FROM loans") as $r) {
    if ($r['status']!==null && $r['status']!=='') $status_values[]=$r['status'];
  }
  if (!$status_values) $status_values=['DISPONIBILIZADO','DEVOLVIDO','CANCELADO'];

  $status = rep_whitelist($_GET['status'] ?? '', array_merge([''],$status_values));

  [$d_from_br,$d_from_sql] = rep_get_br_date_filter('delivered_from',$warnings);
  [$d_to_br,  $d_to_sql]   = rep_get_br_date_filter('delivered_to',  $warnings);
  $q = rep_safe_like_input($_GET['q'] ?? '');

  $hasCreated = rep_has_col($pdo,'loans','created_at');
  $hasUpdated = rep_has_col($pdo,'loans','updated_at');
  $hasPrevDev = rep_has_col($pdo,'loans','prev_devolucao');

  $where=[]; $bind=[];
  if ($status!==''){ $where[]='l.status=?'; $bind[]=$status; }
  if ($d_from_sql){ $where[]='l.data_entrega>=?'; $bind[]=$d_from_sql; }
  if ($d_to_sql)  { $where[]='l.data_entrega<DATE_ADD(?,INTERVAL 1 DAY)'; $bind[]=$d_to_sql; }
  if ($q!=='')    { $where[]='(e.matricula LIKE ? OR e.nome LIKE ?)'; $bind[]="%$q%"; $bind[]="%$q%"; }

  $cols="l.id,l.status,l.data_entrega,e.matricula,e.nome,COUNT(li.equipment_id) AS itens";
  if ($hasPrevDev) $cols.=",l.prev_devolucao";
  if ($hasCreated) $cols.=",l.created_at";
  if ($hasUpdated) $cols.=",l.updated_at";

  $sql="SELECT $cols
          FROM loans l
     LEFT JOIN loan_items li ON li.loan_id=l.id
     LEFT JOIN employees e   ON e.id=l.employee_id";
  if ($where) $sql.=" WHERE ".implode(' AND ',$where);
  $sql.=" GROUP BY l.id ORDER BY l.id DESC";

  $st=$pdo->prepare($sql); $st->execute($bind);
  $rows=$st->fetchAll();

  if ($export) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=relatorio_emprestimos.csv');
    $out=fopen('php://output','w');
    fputcsv($out,['#','Matrícula','Nome','Status','Entrega','Prev. devolução','Itens','Criado','Atualizado'],';');
    foreach($rows as $r){
      fputcsv($out,[
        $r['id'],$r['matricula'],$r['nome'],$r['status'],
        $r['data_entrega'],$hasPrevDev?($r['prev_devolucao']??''):'',$r['itens'],
        $hasCreated?($r['created_at']??''):'',$hasUpdated?($r['updated_at']??''):''
      ],';');
    }
    exit;
  }
}

/* ==========================================================================

   ESTOQUE

============================================================================*/
if ($tab==='stock') {
  $st_vals = [];
  foreach ($pdo->query("SELECT DISTINCT status FROM equipment") as $r) {
    if ($r['status']!==null && $r['status']!=='') $st_vals[]=$r['status'];
  }
  if (!$st_vals) $st_vals = ['EM_ESTOQUE','EMPRESTADO','MANUTENCAO','DEFEITO','BAIXADO','FURTO'];

  $status = rep_whitelist($_GET['status'] ?? '', array_merge([''],$st_vals));
  $type   = (int)($_GET['type'] ?? 0);
  $loc    = (int)($_GET['location'] ?? 0);

  [$gar_from_br,$gar_from_sql] = rep_get_br_date_filter('gar_from',$warnings);
  [$gar_to_br,  $gar_to_sql]   = rep_get_br_date_filter('gar_to',  $warnings);

  $where=[]; $bind=[];
  if ($status!==''){ $where[]='e.status=?'; $bind[]=$status; }
  if ($type>0)     { $where[]='e.type_id=?'; $bind[]=$type; }
  if ($loc>0)      { $where[]='e.location_id=?'; $bind[]=$loc; }
  if ($gar_from_sql && rep_has_col($pdo,'equipment','garantia_ate')) { $where[]='e.garantia_ate>=?'; $bind[]=$gar_from_sql; }
  if ($gar_to_sql   && rep_has_col($pdo,'equipment','garantia_ate')) { $where[]='e.garantia_ate<DATE_ADD(?,INTERVAL 1 DAY)'; $bind[]=$gar_to_sql; }

  $hasGar = rep_has_col($pdo,'equipment','garantia_ate');

  $sql="SELECT e.id, e.modelo, e.status, t.name AS tipo, l.name AS local_name".
       ($hasGar?", e.garantia_ate":"").
       " FROM equipment e
         LEFT JOIN equipment_types t ON t.id=e.type_id
         LEFT JOIN locations l       ON l.id=e.location_id";
  if ($where) $sql.=" WHERE ".implode(' AND ',$where);
  $sql.=" ORDER BY e.id DESC";

  $st=$pdo->prepare($sql); $st->execute($bind); $rows=$st->fetchAll();

  if ($export) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=relatorio_estoque.csv');
    $out=fopen('php://output','w');
    $header=['#','Tipo/Modelo','Local','Status'];
    if ($hasGar) $header[]='Garantia até';
    fputcsv($out,$header,';');
    foreach($rows as $r){
      $line=[
        $r['id'],
        trim(($r['tipo']??'').' • '.($r['modelo']??'')),
        $r['local_name'] ?? '',
        $r['status'],
      ];
      if ($hasGar) $line[]=$r['garantia_ate'] ?? '';
      fputcsv($out,$line,';');
    }
    exit;
  }

  $types = $pdo->query("SELECT id,name FROM equipment_types ORDER BY name")->fetchAll();
  $locs  = $pdo->query("SELECT id,name FROM locations ORDER BY name")->fetchAll();
}

/* ==========================================================================

   DEVOLUÇÕES

============================================================================*/
if ($tab==='returns') {
  $status_vals=[];
  if (rep_has_table($pdo,'return_requests')) {
    foreach ($pdo->query("SELECT DISTINCT status FROM return_requests") as $r) {
      if ($r['status']!==null && $r['status']!=='') $status_vals[]=$r['status'];
    }
  }
  if (!$status_vals) $status_vals=['ABERTA','EM_COBRANCA','CONCLUIDA'];

  $status  = rep_whitelist($_GET['status'] ?? '', array_merge([''],$status_vals));
  $overdue = rep_whitelist($_GET['overdue'] ?? '', ['','SIM','NAO']);
  [$from_br,$from_sql] = rep_get_br_date_filter('created_from',$warnings);
  [$to_br,  $to_sql]   = rep_get_br_date_filter('created_to',  $warnings);
  $q = rep_safe_like_input($_GET['q'] ?? '');

  $hasEmpId  = rep_has_col($pdo,'return_requests','employee_id');
  $hasLoanId = rep_has_col($pdo,'return_requests','loan_id');
  $hasDue    = rep_has_col($pdo,'return_requests','due_at');
  $hasUpd    = rep_has_col($pdo,'return_requests','updated_at');

  $cols="rr.id,rr.status,rr.created_at,e.matricula,e.nome";
  if ($hasDue) $cols.=",rr.due_at";
  if ($hasUpd) $cols.=",rr.updated_at";

  $joinEmp = "JOIN employees e ON e.id=rr.employee_id";
  if (!$hasEmpId && $hasLoanId) $joinEmp="JOIN loans l ON l.id=rr.loan_id JOIN employees e ON e.id=l.employee_id";

  if ($hasEmpId) {
    $itemsSub="(SELECT COUNT(*) FROM loan_items li JOIN loans l2 ON l2.id=li.loan_id
                WHERE l2.employee_id=rr.employee_id AND l2.status='DISPONIBILIZADO')";
  } elseif ($hasLoanId) {
    $itemsSub="(SELECT COUNT(*) FROM loan_items li WHERE li.loan_id=rr.loan_id)";
  } else {
    $itemsSub="0";
  }
  $cols.=", $itemsSub AS itens";

  $where=[]; $bind=[];
  if ($status!==''){ $where[]='rr.status=?'; $bind[]=$status; }
  if ($from_sql)  { $where[]='rr.created_at>=?'; $bind[]=$from_sql; }
  if ($to_sql)    { $where[]='rr.created_at<DATE_ADD(?,INTERVAL 1 DAY)'; $bind[]=$to_sql; }
  if ($q!=='')    { $where[]='(e.matricula LIKE ? OR e.nome LIKE ?)'; $bind[]="%$q%"; $bind[]="%$q%"; }
  if ($overdue==='SIM' && $hasDue) { $where[]='rr.due_at IS NOT NULL AND rr.due_at<NOW() AND rr.status<>"CONCLUIDA"'; }
  if ($overdue==='NAO' && $hasDue) { $where[]='(rr.due_at IS NULL OR rr.due_at>=NOW() OR rr.status="CONCLUIDA")'; }

  $rows=[];
  if (rep_has_table($pdo,'return_requests')) {
    $sql="SELECT $cols FROM return_requests rr $joinEmp";
    if ($where) $sql.=" WHERE ".implode(' AND ',$where);
    $sql.=" ORDER BY rr.id DESC";
    $st=$pdo->prepare($sql); $st->execute($bind); $rows=$st->fetchAll();
  }

  if ($export) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=relatorio_devolucoes.csv');
    $out=fopen('php://output','w');
    fputcsv($out,['#','Matrícula','Nome','Status','Prazo','Itens','Abertura','Atualização'],';');
    foreach($rows as $r){
      fputcsv($out,[
        $r['id'],$r['matricula'],$r['nome'],$r['status'],
        $hasDue?($r['due_at']??''):'',$r['itens'],$r['created_at']??'',$hasUpd?($r['updated_at']??''):''
      ],';');
    }
    exit;
  }
}

/* ==========================================================================

   MOVIMENTAÇÕES

============================================================================*/
if ($tab==='moves') {
  $logTbl = rep_has_table($pdo,'equipment_log') ? 'equipment_log' :
            (rep_has_table($pdo,'asset_log') ? 'asset_log' : '');

  $action_vals = ['CREATE','LOANED','WRITE_OFF','STATUS_CHANGE','RETURN_REQUEST_OPENED','MOVE','OTHER'];
  $action = rep_whitelist($_GET['action'] ?? '', array_merge([''],$action_vals));
  [$from_br,$from_sql] = rep_get_br_date_filter('from',$warnings);
  [$to_br,  $to_sql]   = rep_get_br_date_filter('to',$warnings);
  $q = rep_safe_like_input($_GET['q'] ?? '');

  $rows=[];
  $hasUser=$hasNotes=$hasLoan=$hasEmp=$hasFrom=$hasTo=false;

  if ($logTbl) {
    $hasUser = rep_has_col($pdo,$logTbl,'user_id');
    $hasNotes= rep_has_col($pdo,$logTbl,'notes');
    $hasLoan = rep_has_col($pdo,$logTbl,'loan_id');
    $hasEmp  = rep_has_col($pdo,$logTbl,'employee_id');
    $hasFrom = rep_has_col($pdo,$logTbl,'from_status');
    $hasTo   = rep_has_col($pdo,$logTbl,'to_status');

    $cols = "lg.id, lg.action, lg.created_at";
    if ($hasFrom) $cols .= ", lg.from_status";
    if ($hasTo)   $cols .= ", lg.to_status";
    if ($hasLoan) $cols .= ", lg.loan_id";
    if ($hasEmp)  $cols .= ", lg.employee_id";
    if ($hasUser) $cols .= ", u.name AS user_name";
    if ($hasNotes)$cols .= ", lg.notes";

    $sql = "SELECT $cols FROM $logTbl lg";
    if ($hasUser) $sql .= " LEFT JOIN users u ON u.id=lg.user_id";

    $where=[]; $bind=[];
    if ($action!==''){ $where[]='lg.action=?'; $bind[]=$action; }
    if ($from_sql)  { $where[]='lg.created_at>=?'; $bind[]=$from_sql; }
    if ($to_sql)    { $where[]='lg.created_at<DATE_ADD(?,INTERVAL 1 DAY)'; $bind[]=$to_sql; }
    if ($q!==''){
      if ($hasNotes)      { $where[]='( '.($hasUser?'u.name LIKE ? OR ':''). 'lg.notes LIKE ? )'; if ($hasUser) $bind[]="%$q%"; $bind[]="%$q%"; }
      else if ($hasUser)  { $where[]='u.name LIKE ?'; $bind[]="%$q%"; }
    }
    if ($where) $sql.=" WHERE ".implode(' AND ',$where);
    $sql.=" ORDER BY lg.id DESC";

    $st=$pdo->prepare($sql); $st->execute($bind); $rows=$st->fetchAll();
  }

  if ($export) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename=relatorio_movimentacoes.csv');
    $out=fopen('php://output','w');
    $head=['#','Ação'];
    if ($hasFrom) $head[]='De';
    if ($hasTo)   $head[]='Para';
    if ($hasLoan) $head[]='Empréstimo';
    if ($hasEmp)  $head[]='Colaborador';
    if ($hasUser) $head[]='Usuário';
    $head[]='Quando';
    if ($hasNotes)$head[]='Notas';
    fputcsv($out,$head,';');

    foreach($rows as $r){
      $line = [
        $r['id'], $r['action']
      ];
      if ($hasFrom) $line[] = $r['from_status'] ?? '';
      if ($hasTo)   $line[] = $r['to_status'] ?? '';
      if ($hasLoan) $line[] = $r['loan_id'] ?? '';
      if ($hasEmp)  $line[] = $r['employee_id'] ?? '';
      if ($hasUser) $line[] = $r['user_name'] ?? '';
      $line[] = $r['created_at'] ?? '';
      if ($hasNotes) $line[] = $r['notes'] ?? '';
      fputcsv($out,$line,';');
    }
    exit;
  }
}

/* --------------------------------------------------------------------------
   VIEW
---------------------------------------------------------------------------*/
include __DIR__ . '/header.php';
?>
<style>
/* Abas um pouco mais estilosas */
.nav-tabs .nav-link {
  border: 0;
  border-bottom: 2px solid transparent;
  font-weight: 600;
  color: #495057;
}
.nav-tabs .nav-link.active {
  color: #0d6efd;
  border-bottom-color: #0d6efd;
}

/* Datepicker pop */
.rep-dp {
  position: absolute;
  z-index: 1085; /* acima do sidebar */
  width: 280px;
  background: #fff;
  border: 1px solid #dee2e6;
  border-radius: .5rem;
  box-shadow: 0 .5rem 1rem rgba(0,0,0,.15);
  padding: .5rem;
  display: none;
}
.rep-dp header {
  display:flex; align-items:center; justify-content:space-between; margin-bottom:.25rem;
}
.rep-dp header button { border:0; background:transparent; padding:.25rem .5rem; }
.rep-dp .grid {
  display:grid; grid-template-columns: repeat(7, 1fr); gap:.25rem;
}
.rep-dp .dow { text-align:center; font-size:.75rem; color:#6c757d; }
.rep-dp .day {
  text-align:center; border-radius:.375rem; line-height:2rem; height:2rem; cursor:pointer;
}
.rep-dp .day:hover { background:#f1f3f5; }
.rep-dp .day.is-today { outline:1px dashed #adb5bd; }
.rep-dp .day.is-sel { background:#0d6efd; color:#fff; }
.input-group .btn-calendar { border-color:#ced4da; }
</style>

<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="h5 m-0">Relatórios</h2>
    <a class="btn btn-outline-secondary" href="<?= base_url('index.php') ?>">Voltar</a>
  </div>

  <ul class="nav nav-tabs mb-3">
    <li class="nav-item"><a class="nav-link <?= $tab==='loans'?'active':'' ?>" href="<?= base_url('reports.php?tab=loans') ?>">Empréstimos</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab==='stock'?'active':'' ?>" href="<?= base_url('reports.php?tab=stock') ?>">Estoque</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab==='returns'?'active':'' ?>" href="<?= base_url('reports.php?tab=returns') ?>">Devoluções</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab==='moves'?'active':'' ?>" href="<?= base_url('reports.php?tab=moves') ?>">Movimentações</a></li>
  </ul>

  <?php if (!empty($warnings)): ?>
    <div class="alert alert-warning"><?= implode('<br>', array_map('h',$warnings)) ?></div>
  <?php endif; ?>

  <?php if ($tab==='loans'): ?>
    <!-- filtros loans -->
    <form class="row g-2 align-items-end mb-3" method="get" novalidate>
      <input type="hidden" name="tab" value="loans">
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">(todos)</option>
          <?php foreach ($status_values as $s): ?>
            <option value="<?= h($s) ?>" <?= ($status??'')===$s?'selected':'' ?>><?= h($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Entregues de</label>
        <input type="text" name="delivered_from" value="<?= h($d_from_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-2">
        <label class="form-label">Entregues até</label>
        <input type="text" name="delivered_to" value="<?= h($d_to_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-3">
        <label class="form-label">Matrícula / Nome</label>
        <input type="text" name="q" value="<?= h($q ?? '') ?>" class="form-control" maxlength="80">
      </div>
      <div class="col-md-1 d-grid"><button class="btn btn-primary" id="btnApply">Aplicar</button></div>
      <div class="col-md-1 d-grid"><a class="btn btn-outline-secondary" href="<?= base_url('reports.php?tab=loans') ?>">Limpar</a></div>
      <div class="col-md-2 d-grid"><a class="btn btn-success" href="<?= base_url('reports.php?tab=loans&'.http_build_query($_GET+['export'=>1])) ?>">Exportar CSV</a></div>
    </form>

    <div class="card border-0 shadow-sm">
      <div class="table-responsive">
        <table class="table table-striped align-middle mb-0">
          <thead>
            <tr>
              <th>Matrícula</th><th>Nome</th><th>Status</th>
              <th>Entrega</th><th>Prev. devolução</th><th>Itens</th>
              <?php if ($hasCreated): ?><th>Abertura</th><?php endif; ?>
              <?php if ($hasUpdated): ?><th>Atualização</th><?php endif; ?>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?= h($r['matricula']) ?></td>
                <td><?= h($r['nome']) ?></td>
                <td><span class="badge bg-secondary"><?= h($r['status']) ?></span></td>
                <td><?= h($r['data_entrega']) ?></td>
                <td><?= $hasPrevDev ? h($r['prev_devolucao'] ?? '—') : '—' ?></td>
                <td><?= (int)$r['itens'] ?></td>
                <?php if ($hasCreated): ?><td><?= h($r['created_at'] ?? '—') ?></td><?php endif; ?>
                <?php if ($hasUpdated): ?><td><?= h($r['updated_at'] ?? '—') ?></td><?php endif; ?>
              </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?><tr><td colspan="8" class="text-muted">Sem registros.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab==='stock'): ?>
    <!-- filtros stock -->
    <form class="row g-2 align-items-end mb-3" method="get">
      <input type="hidden" name="tab" value="stock">
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">(todos)</option>
          <?php foreach ($st_vals as $s): ?>
            <option value="<?= h($s) ?>" <?= ($status??'')===$s?'selected':'' ?>><?= h($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Tipo</label>
        <select name="type" class="form-select">
          <option value="0">(todos)</option>
          <?php foreach ($types as $t): ?>
            <option value="<?= (int)$t['id'] ?>" <?= ($type??0)==$t['id']?'selected':'' ?>><?= h($t['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Local</label>
        <select name="location" class="form-select">
          <option value="0">(todos)</option>
          <?php foreach ($locs as $l): ?>
            <option value="<?= (int)$l['id'] ?>" <?= ($loc??0)==$l['id']?'selected':'' ?>><?= h($l['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Garantia de</label>
        <input type="text" name="gar_from" value="<?= h($gar_from_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-2">
        <label class="form-label">Garantia até</label>
        <input type="text" name="gar_to" value="<?= h($gar_to_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-1 d-grid"><button class="btn btn-primary">Aplicar</button></div>
      <div class="col-md-1 d-grid"><a class="btn btn-outline-secondary" href="<?= base_url('reports.php?tab=stock') ?>">Limpar</a></div>
      <div class="col-md-2 d-grid"><a class="btn btn-success" href="<?= base_url('reports.php?tab=stock&'.http_build_query($_GET+['export'=>1])) ?>">Exportar CSV</a></div>
    </form>

    <div class="card border-0 shadow-sm">
      <div class="table-responsive">
        <table class="table table-striped align-middle mb-0">
          <thead><tr><th>Tipo/Modelo</th><th>Local</th><th>Status</th><th>Garantia até</th></tr></thead>
          <tbody>
            <?php foreach($rows as $r): ?>
              <tr>
                <td><?= h(trim(($r['tipo']??'').' • '.($r['modelo']??''))) ?></td>
                <td><?= h($r['local_name'] ?? '—') ?></td>
                <td><span class="badge bg-secondary"><?= h($r['status']) ?></span></td>
                <td><?= isset($r['garantia_ate']) ? h($r['garantia_ate'] ?: '—') : '—' ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if(!$rows): ?><tr><td colspan="4" class="text-muted">Sem registros.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab==='returns'): ?>
    <!-- filtros returns -->
    <form class="row g-2 align-items-end mb-3" method="get">
      <input type="hidden" name="tab" value="returns">
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">(todos)</option>
          <?php foreach ($status_vals as $s): ?>
            <option value="<?= h($s) ?>" <?= ($status??'')===$s?'selected':'' ?>><?= h($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Vencidas?</label>
        <select name="overdue" class="form-select">
          <option value="">(indiferente)</option>
          <option value="SIM" <?= ($overdue??'')==='SIM'?'selected':'' ?>>Sim</option>
          <option value="NAO" <?= ($overdue??'')==='NAO'?'selected':'' ?>>Não</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Criadas de</label>
        <input type="text" name="created_from" value="<?= h($from_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-2">
        <label class="form-label">Criadas até</label>
        <input type="text" name="created_to" value="<?= h($to_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-3">
        <label class="form-label">Matrícula / Nome</label>
        <input type="text" name="q" value="<?= h($q ?? '') ?>" class="form-control" maxlength="80">
      </div>
      <div class="col-md-1 d-grid"><button class="btn btn-primary">Aplicar</button></div>
      <div class="col-md-1 d-grid"><a class="btn btn-outline-secondary" href="<?= base_url('reports.php?tab=returns') ?>">Limpar</a></div>
      <div class="col-md-2 d-grid"><a class="btn btn-success" href="<?= base_url('reports.php?tab=returns&'.http_build_query($_GET+['export'=>1])) ?>">Exportar CSV</a></div>
    </form>

    <div class="card border-0 shadow-sm">
      <div class="table-responsive">
        <table class="table table-striped align-middle mb-0">
          <thead><tr><th>Matrícula</th><th>Nome</th><th>Status</th><th>Prazo</th><th>Itens</th><th>Abertura</th><th>Atualização</th></tr></thead>
          <tbody>
            <?php foreach($rows as $r): ?>
              <tr>
                <td><?= h($r['matricula']) ?></td>
                <td><?= h($r['nome']) ?></td>
                <td><span class="badge bg-secondary"><?= h($r['status']) ?></span></td>
                <td><?= isset($r['due_at']) ? h($r['due_at'] ?: '—') : '—' ?></td>
                <td><?= (int)($r['itens'] ?? 0) ?></td>
                <td><?= h($r['created_at'] ?? '—') ?></td>
                <td><?= h($r['updated_at'] ?? '—') ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if(!$rows): ?><tr><td colspan="7" class="text-muted">Sem registros.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab==='moves'): ?>
    <!-- filtros moves -->
    <form class="row g-2 align-items-end mb-3" method="get">
      <input type="hidden" name="tab" value="moves">
      <div class="col-md-2">
        <label class="form-label">Ação</label>
        <select name="action" class="form-select">
          <option value="">(todas)</option>
          <option value="CREATE" <?= ($action??'')==='CREATE'?'selected':'' ?>>CREATE</option>
          <option value="LOANED" <?= ($action??'')==='LOANED'?'selected':'' ?>>LOANED</option>
          <option value="WRITE_OFF" <?= ($action??'')==='WRITE_OFF'?'selected':'' ?>>WRITE_OFF</option>
          <option value="STATUS_CHANGE" <?= ($action??'')==='STATUS_CHANGE'?'selected':'' ?>>STATUS_CHANGE</option>
          <option value="RETURN_REQUEST_OPENED" <?= ($action??'')==='RETURN_REQUEST_OPENED'?'selected':'' ?>>RETURN_REQUEST_OPENED</option>
          <option value="MOVE" <?= ($action??'')==='MOVE'?'selected':'' ?>>MOVE</option>
          <option value="OTHER" <?= ($action??'')==='OTHER'?'selected':'' ?>>OTHER</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">De</label>
        <input type="text" name="from" value="<?= h($from_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-2">
        <label class="form-label">Até</label>
        <input type="text" name="to" value="<?= h($to_br ?? '') ?>" class="form-control js-date"
               inputmode="numeric" placeholder="dd/mm/aaaa" maxlength="10" pattern="\d{2}/\d{2}/\d{4}">
      </div>
      <div class="col-md-4">
        <label class="form-label">Usuário / Notas</label>
        <input type="text" name="q" value="<?= h($q ?? '') ?>" class="form-control" maxlength="80">
      </div>
      <div class="col-md-1 d-grid"><button class="btn btn-primary">Aplicar</button></div>
      <div class="col-md-1 d-grid"><a class="btn btn-outline-secondary" href="<?= base_url('reports.php?tab=moves') ?>">Limpar</a></div>
      <div class="col-md-2 d-grid"><a class="btn btn-success" href="<?= base_url('reports.php?tab=moves&'.http_build_query($_GET+['export'=>1])) ?>">Exportar CSV</a></div>
    </form>

    <?php if (!$logTbl): ?>
      <div class="alert alert-info">Tabela de log de movimentações não encontrada.</div>
    <?php else: ?>
      <div class="card border-0 shadow-sm">
        <div class="table-responsive">
          <table class="table table-striped align-middle mb-0">
            <thead>
              <tr>
                <th>Ação</th>
                <?php if ($hasFrom): ?><th>De</th><?php endif; ?>
                <?php if ($hasTo):   ?><th>Para</th><?php endif; ?>
                <?php if ($hasLoan): ?><th>Empréstimo</th><?php endif; ?>
                <?php if ($hasEmp):  ?><th>Colaborador</th><?php endif; ?>
                <?php if ($hasUser): ?><th>Usuário</th><?php endif; ?>
                <th>Quando</th>
                <?php if ($hasNotes):?><th>Notas</th><?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach($rows as $r): ?>
                <tr>
                  <td><?= h($r['action']) ?></td>
                  <?php if ($hasFrom): ?><td><?= h($r['from_status'] ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasTo):   ?><td><?= h($r['to_status']   ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasLoan): ?><td><?= h($r['loan_id']     ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasEmp):  ?><td><?= h($r['employee_id'] ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasUser): ?><td><?= h($r['user_name']   ?? '—') ?></td><?php endif; ?>
                  <td><?= h($r['created_at'] ?? '—') ?></td>
                  <?php if ($hasNotes):?><td><?= h($r['notes'] ?? '—') ?></td><?php endif; ?>
                </tr>
              <?php endforeach; ?>
              <?php if(!$rows): ?><tr><td colspan="9" class="text-muted">Sem registros.</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endif; ?>
  <?php endif; ?>
</div>

<!-- Máscara + Datepicker ancorado -->
<script>
(function(){
  /* --------- util máscara BR --------- */
  function onlyDigits(s){ return s.replace(/\D+/g,''); }
  function formatBR(v){
    v = onlyDigits(v).slice(0,8);
    if (v.length >= 5) return v.slice(0,2)+'/'+v.slice(2,4)+'/'+v.slice(4);
    if (v.length >= 3) return v.slice(0,2)+'/'+v.slice(2);
    return v;
  }
  function isValidDateBR(s){
    if(!/^\d{2}\/\d{2}\/\d{4}$/.test(s)) return false;
    const [d,m,y] = s.split('/').map(Number);
    const dt = new Date(y, m-1, d);
    return dt.getFullYear()===y && (dt.getMonth()+1)===m && dt.getDate()===d;
  }

  /* ---- injeta botão calendário automaticamente ---- */
  document.querySelectorAll('input.js-date').forEach(function(inp){
    // já dentro de input-group? então só adiciona botão se não houver
    if (!inp.closest('.input-group')) {
      const wrap = document.createElement('div');
      wrap.className = 'input-group';
      inp.parentNode.insertBefore(wrap, inp);
      wrap.appendChild(inp);
      const btn = document.createElement('button');
      btn.type='button'; btn.className='btn btn-outline-secondary btn-calendar'; btn.innerHTML='<i class="bi bi-calendar-event"></i>';
      wrap.appendChild(btn);
      btn.addEventListener('click', function(){ openPicker(inp); });
    }
    // máscara/validação
    inp.addEventListener('input', function(e){
      const cur = e.target.value;
      const f = formatBR(cur);
      if (cur !== f) e.target.value = f;
    });
    inp.addEventListener('blur', function(e){
      const v = e.target.value.trim();
      if (v!=='' && !isValidDateBR(v)) {
        e.target.classList.add('is-invalid');
        e.target.setCustomValidity('Data inválida (use dd/mm/aaaa)');
      } else {
        e.target.classList.remove('is-invalid');
        e.target.setCustomValidity('');
      }
    });
    // abrir no foco (mais prático)
    inp.addEventListener('focus', function(){ openPicker(inp); });
  });

  /* -------------- datepicker -------------- */
  const dp = document.createElement('div');
  dp.className = 'rep-dp';
  dp.innerHTML = `
    <header>
      <button type="button" data-nav="-1" title="Mês anterior">&lt;</button>
      <div class="title fw-semibold"></div>
      <button type="button" data-nav="1" title="Próximo mês">&gt;</button>
    </header>
    <div class="grid grid-headers"></div>
    <div class="grid grid-days"></div>
  `;
  document.body.appendChild(dp);

  const headers = ['D','S','T','Q','Q','S','S'];
  const gridH = dp.querySelector('.grid-headers');
  headers.forEach(h=>{
    const el=document.createElement('div');
    el.className='dow'; el.textContent=h; gridH.appendChild(el);
  });

  let currentInput=null, curYear=0, curMonth=0; // month 0..11
  const titleEl = dp.querySelector('.title');
  const gridD = dp.querySelector('.grid-days');

  function positionPop(inp){
    const r = inp.getBoundingClientRect();
    dp.style.left = (window.scrollX + r.left) + 'px';
    dp.style.top  = (window.scrollY + r.bottom + 6) + 'px';
  }
  function show(){ dp.style.display='block'; }
  function hide(){ dp.style.display='none'; currentInput=null; }

  function parseBR(str){
    if (!isValidDateBR(str)) return null;
    const [d,m,y]=str.split('/').map(Number);
    return new Date(y,m-1,d);
  }
  function formatBRdate(d){
    const dd=('0'+d.getDate()).slice(-2);
    const mm=('0'+(d.getMonth()+1)).slice(-2);
    const yy=d.getFullYear();
    return `${dd}/${mm}/${yy}`;
  }

  function build(){
    gridD.innerHTML='';
    const first = new Date(curYear, curMonth, 1);
    const startDay = first.getDay(); // 0..6
    const last = new Date(curYear, curMonth+1, 0);
    const today = new Date();
    titleEl.textContent = first.toLocaleDateString('pt-BR', {month:'long', year:'numeric'});

    // pre blanks
    for(let i=0;i<startDay;i++){
      const s=document.createElement('div'); gridD.appendChild(s);
    }
    for(let d=1; d<=last.getDate(); d++){
      const el=document.createElement('div');
      el.textContent=d;
      el.className='day';
      const dt=new Date(curYear,curMonth,d);
      if (today.toDateString()===dt.toDateString()) el.classList.add('is-today');
      const sel = parseBR(currentInput?.value||'');
      if (sel && sel.toDateString()===dt.toDateString()) el.classList.add('is-sel');
      el.addEventListener('click', function(){
        if (currentInput){
          currentInput.value = formatBRdate(dt);
          currentInput.dispatchEvent(new Event('input', {bubbles:true}));
          currentInput.dispatchEvent(new Event('change', {bubbles:true}));
        }
        hide();
      });
      gridD.appendChild(el);
    }
  }

  dp.addEventListener('click', function(e){
    const b = e.target.closest('button[data-nav]');
    if (b){
      curMonth += parseInt(b.dataset.nav,10);
      if (curMonth<0){ curMonth=11; curYear--; }
      if (curMonth>11){ curMonth=0; curYear++; }
      build(); positionPop(currentInput);
    }
  });

  function openPicker(inp){
    currentInput = inp;
    const base = parseBR(inp.value) || new Date();
    curYear = base.getFullYear(); curMonth = base.getMonth();
    build(); positionPop(inp); show();
  }

  // fechar ao clicar fora / ESC / scroll
  document.addEventListener('mousedown', (e)=>{
    if (dp.style.display!=='none' && !dp.contains(e.target) && !e.target.closest('.input-group')) hide();
  });
  window.addEventListener('keydown', (e)=>{ if(e.key==='Escape') hide(); });
  window.addEventListener('scroll', ()=>{ if(currentInput) positionPop(currentInput); }, true);
  window.addEventListener('resize', ()=>{ if(currentInput) positionPop(currentInput); });

  // validação global dos forms (impede aplicar se data inválida)
  document.querySelectorAll('form').forEach(function(f){
    f.addEventListener('submit', function(ev){
      let invalid=false;
      f.querySelectorAll('input.js-date').forEach(function(i){
        const v=i.value.trim();
        if(v!=='' && !isValidDateBR(v)){ i.classList.add('is-invalid'); invalid=true; }
      });
      if(invalid){ ev.preventDefault(); alert('Corrija as datas (dd/mm/aaaa) antes de aplicar.'); }
    });
  });
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>

