<?php
require_once __DIR__ . '/_db.php';

$msg = '';
$pdo = db();

// Pesquisa
$search = trim($_GET['q'] ?? '');
$where  = $search ? "WHERE c.name LIKE ? OR c.email LIKE ? OR c.company LIKE ?" : '';
$params = $search ? ["%$search%", "%$search%", "%$search%"] : [];

$customers = $pdo->prepare("
    SELECT c.*,
           COUNT(l.id)                                    AS total_licenses,
           SUM(l.active = 1 AND l.expires_at >= CURDATE()) AS active_licenses
    FROM customers c
    LEFT JOIN licenses l ON l.customer_id = c.id
    $where
    GROUP BY c.id
    ORDER BY c.created_at DESC
");
$customers->execute($params);
$customers = $customers->fetchAll();

// Resumo
$totals = $pdo->query("
    SELECT
      (SELECT COUNT(*) FROM customers WHERE active=1) AS total_customers,
      (SELECT COUNT(*) FROM licenses WHERE active=1 AND expires_at >= CURDATE()) AS active_lic,
      (SELECT COUNT(*) FROM licenses WHERE active=1 AND expires_at < CURDATE() AND expires_at >= DATE_SUB(CURDATE(), INTERVAL " . GRACE_DAYS . " DAY)) AS grace_lic,
      (SELECT COUNT(*) FROM licenses WHERE active=1 AND expires_at < DATE_SUB(CURDATE(), INTERVAL " . GRACE_DAYS . " DAY)) AS blocked_lic
")->fetch();

$page_title   = 'Clientes';
$current_nav  = 'customers';
require __DIR__ . '/_layout.php';
?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem;flex-wrap:wrap;gap:.5rem">
  <h1 style="margin:0">Clientes</h1>
  <a href="customer_form.php" class="btn btn-blue">+ Novo Cliente</a>
</div>

<!-- Resumo -->
<div style="display:flex;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap">
  <?php foreach ([
    ['Clientes', $totals['total_customers'], '#0ea5e9'],
    ['Licenças Ativas', $totals['active_lic'], '#22c55e'],
    ['Em Carência', $totals['grace_lic'], '#f59e0b'],
    ['Bloqueadas', $totals['blocked_lic'], '#ef4444'],
  ] as [$label, $val, $color]): ?>
  <div class="card" style="flex:1;min-width:140px;text-align:center;border-color:<?= $color ?>33">
    <div style="font-size:1.8rem;font-weight:700;color:<?= $color ?>"><?= (int)$val ?></div>
    <div style="font-size:.8rem;color:#94a3b8;margin-top:.2rem"><?= $label ?></div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Pesquisa -->
<form method="get" style="margin-bottom:1rem;display:flex;gap:.5rem">
  <input type="text" name="q" placeholder="Buscar por nome, e-mail ou empresa..." value="<?= h($search) ?>" style="flex:1">
  <button type="submit" class="btn btn-blue">Buscar</button>
  <?php if ($search): ?><a href="index.php" class="btn btn-gray">Limpar</a><?php endif; ?>
</form>

<?php if (!empty($msg)): ?><div class="alert alert-ok"><?= $msg ?></div><?php endif; ?>

<div class="card" style="padding:0;overflow:hidden">
<table>
  <thead>
    <tr>
      <th>Cliente</th><th>Empresa</th><th>E-mail</th><th>Telefone</th>
      <th style="text-align:center">Licenças</th><th>Cadastro</th><th>Ações</th>
    </tr>
  </thead>
  <tbody>
  <?php if (empty($customers)): ?>
    <tr><td colspan="7" class="empty">Nenhum cliente encontrado.</td></tr>
  <?php endif; ?>
  <?php foreach ($customers as $c): ?>
  <tr>
    <td>
      <a href="customer_view.php?id=<?= $c['id'] ?>" style="font-weight:600;color:#e2e8f0">
        <?= h($c['name']) ?>
      </a>
      <?php if (!$c['active']): ?><span class="badge badge-revoked" style="margin-left:.3rem">Inativo</span><?php endif; ?>
    </td>
    <td><?= h($c['company'] ?? '—') ?></td>
    <td><?= h($c['email']) ?></td>
    <td><?= h($c['phone'] ?? '—') ?></td>
    <td style="text-align:center">
      <span style="color:#<?= (int)$c['active_licenses'] > 0 ? '4ade80' : '94a3b8' ?>;font-weight:600">
        <?= (int)$c['active_licenses'] ?> ativa<?= (int)$c['active_licenses'] !== 1 ? 's' : '' ?>
      </span>
      <?php if ($c['total_licenses'] > 0): ?>
        <span style="color:#475569"> / <?= (int)$c['total_licenses'] ?> total</span>
      <?php endif; ?>
    </td>
    <td><?= date('d/m/Y', strtotime($c['created_at'])) ?></td>
    <td>
      <a href="customer_view.php?id=<?= $c['id'] ?>" class="btn btn-blue btn-sm">Ver</a>
      <a href="customer_form.php?id=<?= $c['id'] ?>" class="btn btn-gray btn-sm">Editar</a>
    </td>
  </tr>
  <?php endforeach; ?>
  </tbody>
</table>
</div>

</div></body></html>
