<?php
$pageActive = 'clientes';
$pageTitle  = 'Clientes';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$busca  = trim($_GET['busca'] ?? '');
$status = $_GET['status'] ?? 'todos';
$cidade = $_GET['cidade']  ?? '';
$erroDb = '';

$filtros = [];
if ($busca)  $filtros['busca']  = $busca;
if ($cidade) $filtros['cidade'] = $cidade;
if ($status === 'ativo')     { $filtros['ativo'] = 1; $filtros['bloqueado'] = 0; }
if ($status === 'bloqueado') { $filtros['bloqueado'] = 1; }

$clientes = [];
try { $clientes = getClientes($filtros); }
catch (Throwable $e) { $erroDb = $e->getMessage(); }

$cidades = [];
try { $cidades = pdo()->query("SELECT DISTINCT endereco_cidade FROM clientes WHERE endereco_cidade IS NOT NULL AND endereco_cidade <> '' ORDER BY endereco_cidade")->fetchAll(PDO::FETCH_COLUMN); }
catch (Throwable $e) { $cidades = []; }

$isAdmin = usuarioLogado()['perfil'] === 'ADMIN';
require_once __DIR__ . '/includes/header.php';
?>
<div class="topbar">
  <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
  <div>
    <div class="page-title">Clientes</div>
    <div class="page-sub"><?= count($clientes) ?> encontrado(s)</div>
  </div>
  <div class="topbar-actions">
    <a href="cliente_form.php" class="btn btn-primary">+ Cadastrar</a>
  </div>
</div>

<div class="content">

<?php if ($erroDb): ?>
<div class="alert alert-danger">⚠ <?= e($erroDb) ?> — Importe o <b>mkt_2026.sql</b> e execute as migrations.</div>
<?php endif; ?>

<form method="get" class="filter-bar">
  <div class="search-wrap">
    <span class="search-icon">⌕</span>
    <input type="text" name="busca" placeholder="Nome, CPF, telefone..." value="<?= e($busca) ?>" oninput="this.form.submit()"/>
  </div>
  <select class="filter-select" name="status" onchange="this.form.submit()">
    <option value="todos"    <?= $status==='todos'    ?'selected':'' ?>>Todos</option>
    <option value="ativo"    <?= $status==='ativo'    ?'selected':'' ?>>Ativos</option>
    <option value="bloqueado"<?= $status==='bloqueado'?'selected':'' ?>>Bloqueados</option>
  </select>
  <?php if ($cidades): ?>
  <select class="filter-select" name="cidade" onchange="this.form.submit()">
    <option value="">Todas as cidades</option>
    <?php foreach ($cidades as $c): ?>
    <option value="<?= e($c) ?>" <?= $cidade===$c?'selected':'' ?>><?= e($c) ?></option>
    <?php endforeach; ?>
  </select>
  <?php endif; ?>
  <?php if ($busca || $cidade || $status!=='todos'): ?>
  <a href="clientes.php" class="btn btn-ghost btn-sm">✕ Limpar</a>
  <?php endif; ?>
</form>

<!-- ── DESKTOP: tabela ── -->
<div class="table-wrap">
  <table>
    <thead><tr>
      <th>NOME</th><th>TELEFONE</th><th>CIDADE</th><th>PLANO</th>
      <th class="col-hide-mobile">ROTEADOR</th><th>OS</th><th>STATUS</th><th></th>
    </tr></thead>
    <tbody>
    <?php if (empty($clientes)): ?>
      <tr class="empty-row"><td colspan="8">
        <?= $busca||$cidade||$status!=='todos' ? 'Nenhum resultado. <a href="clientes.php" style="color:var(--cyan)">Limpar filtros</a>' : 'Nenhum cliente. <a href="cliente_form.php" style="color:var(--cyan)">+ Cadastrar</a>' ?>
      </td></tr>
    <?php else: foreach ($clientes as $c):
      $osAb = (int)($c['os_abertas'] ?? 0); ?>
    <tr class="clickable" onclick="location.href='cliente_detalhe.php?id=<?= $c['id'] ?>'">
      <td class="td-nome"><b><?= e($c['nome']) ?></b><small><?= e($c['documento'] ?? '') ?></small></td>
      <td class="mono"><?= e($c['telefone'] ?: '—') ?></td>
      <td class="mono"><?= e($c['endereco_cidade'] ?: '—') ?></td>
      <td class="mono"><?= e($c['plano'] ?: '—') ?></td>
      <td class="col-hide-mobile"><?= e($c['modelo_roteador'] ?: '—') ?></td>
      <td><?= $osAb>0 ? "<span class=\"badge badge-amber\">{$osAb} OS</span>" : '<span style="color:var(--muted);font-size:10px">—</span>' ?></td>
      <td><?= badgeAtivo((bool)($c['bloqueado'] ?? 0)) ?></td>
      <td style="white-space:nowrap">
        <button onclick="event.stopPropagation();abrirFicha(<?= $c['id'] ?>)" class="btn btn-ghost btn-xs">⚡</button>
        <a href="cliente_detalhe.php?id=<?= $c['id'] ?>" class="btn btn-ghost btn-xs" onclick="event.stopPropagation()">Ver</a>
        <a href="cliente_form.php?id=<?= $c['id'] ?>" class="btn btn-ghost btn-xs" onclick="event.stopPropagation()">✎</a>
        <?php if ($isAdmin): ?>
        <a href="excluir_cliente.php?id=<?= $c['id'] ?>" class="btn btn-danger btn-xs" onclick="event.stopPropagation()">✕</a>
        <?php endif; ?>
      </td>
    </tr>
    <?php endforeach; endif; ?>
    </tbody>
  </table>
</div>

<!-- ── MOBILE: cards ── -->
<div class="card-list" id="card-list-clientes">
<?php if (empty($clientes)): ?>
  <div style="text-align:center;padding:24px;color:var(--muted);font-size:13px">
    <?= $busca||$cidade||$status!=='todos' ? 'Nenhum resultado.' : 'Nenhum cliente cadastrado.' ?>
  </div>
<?php else: foreach ($clientes as $c):
  $osAb  = (int)($c['os_abertas'] ?? 0);
  $bloq  = (bool)($c['bloqueado'] ?? 0);
  $cor   = $bloq ? 'var(--red)' : 'var(--green)'; ?>
<div class="cli-card" onclick="location.href='cliente_detalhe.php?id=<?= $c['id'] ?>'">
  <div class="cli-card-body">
    <div class="cli-card-top">
      <div>
        <div class="cli-card-name"><?= e($c['nome']) ?></div>
        <div class="cli-card-doc"><?= e($c['documento'] ?? '') ?></div>
      </div>
      <div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px">
        <?= badgeAtivo($bloq) ?>
        <?php if ($osAb>0): ?><span class="badge badge-amber"><?= $osAb ?> OS</span><?php endif; ?>
      </div>
    </div>
    <div class="cli-card-meta">
      <?php if ($c['telefone']): ?><span>📞 <?= e($c['telefone']) ?></span><?php endif; ?>
      <?php if ($c['endereco_cidade']): ?><span>📍 <?= e($c['endereco_cidade']) ?></span><?php endif; ?>
      <?php if ($c['plano']): ?><span>📶 <?= e($c['plano']) ?></span><?php endif; ?>
    </div>
  </div>
  <div class="cli-card-actions">
    <a class="cli-card-btn" href="cliente_detalhe.php?id=<?= $c['id'] ?>" onclick="event.stopPropagation()">
      <span class="ico">👁</span>Ver
    </a>
    <a class="cli-card-btn" href="cliente_form.php?id=<?= $c['id'] ?>" onclick="event.stopPropagation()">
      <span class="ico">✎</span>Editar
    </a>
    <a class="cli-card-btn" href="geocalizacao.php?id=<?= $c['id'] ?>" onclick="event.stopPropagation()">
      <span class="ico">◉</span>GPS
    </a>
    <a class="cli-card-btn" href="os_form.php?cliente_id=<?= $c['id'] ?>" onclick="event.stopPropagation()">
      <span class="ico">+</span>OS
    </a>
  </div>
</div>
<?php endforeach; endif; ?>
</div>

</div><!-- /content -->

<!-- Modal Ficha Rápida -->
<div class="modal-overlay" id="modal-ficha" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal" style="width:780px">
    <div class="modal-header">
      <div class="modal-title">◎ Resumo do Cliente</div>
      <button class="modal-close" onclick="document.getElementById('modal-ficha').classList.remove('open')">✕</button>
    </div>
    <div id="conteudo-ficha" style="min-height:120px"></div>
  </div>
</div>
<script>
function abrirFicha(id) {
  const el = document.getElementById('conteudo-ficha');
  el.innerHTML = '<div style="padding:40px;text-align:center;color:var(--muted)">Carregando...</div>';
  document.getElementById('modal-ficha').classList.add('open');
  fetch('get_cliente_detalhes.php?id=' + id)
    .then(r => r.text()).then(h => { el.innerHTML = h; })
    .catch(() => { el.innerHTML = '<div style="padding:24px;color:var(--red)">Erro ao carregar.</div>'; });
}
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
