<?php
declare(strict_types=1);

require __DIR__ . '/auth.php';
admin_require_login();

/* ---------- filtros ---------- */
$today = gmdate('Y-m-d');
$defaultFrom = gmdate('Y-m-d', strtotime('-29 days'));

function q_date(string $key, string $fallback): string
{
    $v = (string) ($_GET[$key] ?? '');
    return preg_match('/^\d{4}-\d{2}-\d{2}$/', $v) === 1 ? $v : $fallback;
}

$filters = [
    'from' => q_date('from', $defaultFrom),
    'to' => q_date('to', $today),
    'q' => trim((string) ($_GET['q'] ?? '')),
    'status' => in_array($_GET['status'] ?? '', ['ok', 'failed', 'duplicate'], true) ? (string) $_GET['status'] : '',
    'ftd' => in_array($_GET['ftd'] ?? '', ['0', '1'], true) ? (string) $_GET['ftd'] : '',
    'origin' => in_array($_GET['origin'] ?? '', ['landing', 'crm'], true) ? (string) $_GET['origin'] : '',
];

$perPage = 50;
$page = max(1, (int) ($_GET['page'] ?? 1));

/* ---------- ação: sincronizar com o CRM ---------- */
$flash = null;
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && ($_POST['action'] ?? '') === 'sync') {
    if (!admin_csrf_check($_POST['_csrf'] ?? null)) {
        $flash = ['error', 'Sessão expirada — recarregue a página e tente de novo.'];
    } else {
        $sync = admin_run_sync($filters['from'], $filters['to']);
        $flash = [$sync['ok'] ? 'ok' : 'error', $sync['message']];
    }
}

// Retorno do reenvio manual (resend.php redireciona para cá com o resultado).
if ($flash === null && isset($_GET['resend'])) {
    $flash = [$_GET['resend'] === 'ok' ? 'ok' : 'error', (string) ($_GET['msg'] ?? '')];
}

/* ---------- dados ---------- */
$dbUp = store_db() !== null;
$stats = store_stats($filters);
$total = store_count($filters);
$pages = max(1, (int) ceil($total / $perPage));
$page = min($page, $pages);
$leads = store_list_leads($filters, $perPage, ($page - 1) * $perPage);
$badCountry = store_bad_country($filters);
$daily = store_daily($filters, 45);
$countries = store_by_country($filters, 8);
$lastSync = store_meta_get('last_sync_at');

$maxDay = 1;
foreach ($daily as $d) {
    $maxDay = max($maxDay, $d['leads']);
}

/** Preserva os filtros ao trocar de página / exportar. */
function qs(array $overrides = []): string
{
    global $filters, $page;
    return http_build_query(array_filter(
        array_merge($filters, ['page' => $page], $overrides),
        static fn($v): bool => $v !== '' && $v !== null
    ));
}

function fmt_dt(?string $iso): string
{
    if (!is_string($iso) || $iso === '') {
        return '—';
    }
    $ts = strtotime($iso);
    return $ts === false ? $iso : gmdate('d/m/Y H:i', $ts);
}
?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>Leads &amp; FTDs · <?= h(BRAND_NAME) ?></title>
<?php require __DIR__ . '/styles.php'; ?>
</head>
<body>

<header class="top">
  <div class="wrap top-in">
    <div class="logo"><span class="dot"></span><?= h(BRAND_NAME) ?> <span class="muted" style="font-weight:500">Leads</span></div>
    <div class="top-sp"></div>
    <span class="xs muted" title="Última sincronização com o CRM">
      Sync: <?= $lastSync ? h(fmt_dt($lastSync)) . ' UTC' : 'nunca' ?>
    </span>
    <form method="post" style="display:inline">
      <input type="hidden" name="action" value="sync">
      <input type="hidden" name="_csrf" value="<?= h(admin_csrf_token()) ?>">
      <?php foreach ($filters as $k => $v): ?>
        <input type="hidden" name="<?= h($k) ?>" value="<?= h($v) ?>">
      <?php endforeach; ?>
      <button class="btn btn-pri btn-sm" type="submit">↻ Sincronizar CRM</button>
    </form>
    <a class="btn btn-sm" href="logout.php">Sair</a>
  </div>
</header>

<main class="wrap" style="padding-bottom:48px">

  <?php if (!$dbUp): ?>
    <div class="flash flash-err">
      SQLite indisponível neste servidor (extensão <span class="mono">pdo_sqlite</span>).
      Os leads continuam sendo enviados ao CRM e registrados em
      <span class="mono">data/leads.jsonl</span>, mas o painel não consegue exibi-los.
    </div>
  <?php endif; ?>

  <?php if ($flash !== null): ?>
    <div class="flash flash-<?= $flash[0] === 'ok' ? 'ok' : 'err' ?>"><?= h($flash[1]) ?></div>
  <?php endif; ?>

  <?php if ($badCountry['count'] > 0): ?>
    <div class="flash flash-err">
      <strong><?= number_format($badCountry['count'], 0, ',', '.') ?> lead(s) recusados por país não habilitado</strong>
      — <?= h(implode(', ', $badCountry['countries'])) ?>.
      A conta de afiliado só aceita <span class="mono"><?= h(implode(', ', PARTNER_ALLOWED_COUNTRIES)) ?></span>.
      Peça ao gerente de afiliados para liberar esses GEOs e depois use <strong>Reenviar</strong> nesses leads —
      os dados estão guardados aqui e nada se perdeu.
    </div>
  <?php endif; ?>

  <!-- KPIs -->
  <div class="grid-kpi">
    <div class="kpi">
      <div class="lb">Leads no período</div>
      <div class="vl"><?= number_format($stats['total'], 0, ',', '.') ?></div>
      <div class="sub"><?= h($filters['from']) ?> → <?= h($filters['to']) ?></div>
    </div>
    <div class="kpi">
      <div class="lb">Enviados ao CRM</div>
      <div class="vl c-gr"><?= number_format($stats['sent'], 0, ',', '.') ?></div>
      <div class="sub"><?= $stats['total'] > 0 ? round($stats['sent'] * 100 / $stats['total'], 1) : 0 ?>% do total</div>
    </div>
    <div class="kpi">
      <div class="lb">Falhas de envio</div>
      <div class="vl <?= $stats['failed'] > 0 ? 'c-rd' : '' ?>"><?= number_format($stats['failed'], 0, ',', '.') ?></div>
      <div class="sub"><?= $stats['failed'] > 0 ? 'Filtre por “Falhou” para revisar' : 'Nenhuma falha' ?></div>
    </div>
    <div class="kpi">
      <div class="lb">Duplicados</div>
      <div class="vl"><?= number_format($stats['dup'], 0, ',', '.') ?></div>
      <div class="sub">Já existiam no CRM</div>
    </div>
    <div class="kpi">
      <div class="lb">FTDs</div>
      <div class="vl c-yl"><?= number_format($stats['ftd'], 0, ',', '.') ?></div>
      <div class="sub">Primeiros depósitos</div>
    </div>
    <div class="kpi">
      <div class="lb">Conversão FTD</div>
      <div class="vl"><?= number_format($stats['conv'], 1, ',', '.') ?>%</div>
      <div class="sub">FTD ÷ leads aceitos</div>
    </div>
    <div class="kpi">
      <div class="lb">Países</div>
      <div class="vl c-bl"><?= number_format($stats['countries'], 0, ',', '.') ?></div>
      <div class="sub">Origens distintas</div>
    </div>
  </div>

  <!-- Filtros -->
  <div class="card">
    <div class="card-b">
      <form class="filters" method="get">
        <div class="fld"><label for="from">De</label><input type="date" id="from" name="from" value="<?= h($filters['from']) ?>"></div>
        <div class="fld"><label for="to">Até</label><input type="date" id="to" name="to" value="<?= h($filters['to']) ?>"></div>
        <div class="fld">
          <label for="q">Busca</label>
          <input type="search" id="q" name="q" value="<?= h($filters['q']) ?>" placeholder="nome, email, telefone, uid" style="min-width:210px">
        </div>
        <div class="fld">
          <label for="status">Envio</label>
          <select id="status" name="status">
            <option value="">Todos</option>
            <option value="ok" <?= $filters['status'] === 'ok' ? 'selected' : '' ?>>Enviado</option>
            <option value="duplicate" <?= $filters['status'] === 'duplicate' ? 'selected' : '' ?>>Duplicado</option>
            <option value="failed" <?= $filters['status'] === 'failed' ? 'selected' : '' ?>>Falhou</option>
          </select>
        </div>
        <div class="fld">
          <label for="ftd">FTD</label>
          <select id="ftd" name="ftd">
            <option value="">Todos</option>
            <option value="1" <?= $filters['ftd'] === '1' ? 'selected' : '' ?>>Depositou</option>
            <option value="0" <?= $filters['ftd'] === '0' ? 'selected' : '' ?>>Sem depósito</option>
          </select>
        </div>
        <div class="fld">
          <label for="origin">Origem</label>
          <select id="origin" name="origin">
            <option value="">Todas</option>
            <option value="landing" <?= $filters['origin'] === 'landing' ? 'selected' : '' ?>>Landing</option>
            <option value="crm" <?= $filters['origin'] === 'crm' ? 'selected' : '' ?>>Só no CRM</option>
          </select>
        </div>
        <button class="btn btn-pri" type="submit">Filtrar</button>
        <a class="btn" href="index.php">Limpar</a>
        <a class="btn" href="export.php?<?= h(qs(['page' => ''])) ?>">↓ CSV</a>
      </form>
    </div>
  </div>

  <div class="cols2" style="margin-top:16px">
    <!-- Volume diário -->
    <div class="card" style="margin-top:0">
      <div class="card-h">
        <span class="card-t">Volume diário</span>
        <span class="top-sp"></span>
        <span class="xs muted"><span style="color:var(--gr)">■</span> leads &nbsp; <span style="color:var(--yl)">■</span> FTD</span>
      </div>
      <div class="card-b">
        <?php if ($daily === []): ?>
          <div class="empty" style="padding:24px">Sem dados no período.</div>
        <?php else: ?>
          <div class="bars">
            <?php foreach ($daily as $d): ?>
              <?php
                $hLead = (int) round($d['leads'] * 92 / $maxDay);
                $hFtd = $d['ftd'] > 0 ? max(3, (int) round($d['ftd'] * 92 / $maxDay)) : 0;
              ?>
              <div class="bar-col" title="<?= h($d['d']) ?> · <?= $d['leads'] ?> leads · <?= $d['ftd'] ?> FTD">
                <?php if ($hFtd > 0): ?><div class="bar-ftd" style="height:<?= $hFtd ?>px"></div><?php endif; ?>
                <div class="bar" style="height:<?= max(2, $hLead - $hFtd) ?>px"></div>
              </div>
            <?php endforeach; ?>
          </div>
          <div class="axis">
            <span><?= h($daily[0]['d']) ?></span>
            <span><?= h($daily[count($daily) - 1]['d']) ?></span>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Países -->
    <div class="card" style="margin-top:0">
      <div class="card-h"><span class="card-t">Top países</span></div>
      <?php if ($countries === []): ?>
        <div class="empty" style="padding:24px">Sem dados.</div>
      <?php else: ?>
        <table>
          <thead><tr><th>País</th><th style="text-align:right">Leads</th><th style="text-align:right">FTD</th><th style="text-align:right">Conv.</th></tr></thead>
          <tbody>
          <?php foreach ($countries as $c): ?>
            <tr>
              <td class="mono"><?= h($c['country']) ?></td>
              <td style="text-align:right"><?= $c['leads'] ?></td>
              <td style="text-align:right" class="c-yl"><?= $c['ftd'] ?></td>
              <td style="text-align:right" class="muted"><?= $c['leads'] > 0 ? number_format($c['ftd'] * 100 / $c['leads'], 1, ',', '.') : '0,0' ?>%</td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>

  <!-- Tabela de leads -->
  <div class="card">
    <div class="card-h">
      <span class="card-t">Leads</span>
      <span class="xs muted"><?= number_format($total, 0, ',', '.') ?> registro(s)</span>
    </div>

    <?php if ($leads === []): ?>
      <div class="empty">Nenhum lead encontrado com esses filtros.</div>
    <?php else: ?>
      <div class="tbl-scroll">
        <table>
          <thead>
            <tr>
              <th>Data</th><th>Nome</th><th>Contato</th><th>País</th>
              <th>Envio</th><th>Status CRM</th><th>FTD</th><th>UID</th><th>Origem</th><th></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($leads as $l): ?>
            <tr>
              <td class="nowrap mono xs"><?= h(fmt_dt((string) ($l['crm_created_at'] ?: $l['created_at']))) ?></td>
              <td>
                <?= h((string) $l['name']) ?>
                <?php if (($l['message'] ?? '') !== ''): ?>
                  <div class="xs muted" style="margin-top:3px;max-width:260px"><?= h(mb_substr((string) $l['message'], 0, 90)) ?></div>
                <?php endif; ?>
              </td>
              <td class="xs">
                <div><?= h((string) $l['email']) ?></div>
                <div class="mono muted" style="margin-top:3px">+<?= h(ltrim((string) $l['phone'], '+')) ?></div>
              </td>
              <td class="mono"><?= h((string) $l['country'] ?: '—') ?></td>
              <td>
                <?php if ($l['send_status'] === 'ok'): ?>
                  <span class="tag t-ok">Enviado</span>
                <?php elseif ($l['send_status'] === 'duplicate'): ?>
                  <span class="tag t-neu" title="<?= h((string) $l['error']) ?>">Duplicado</span>
                <?php else: ?>
                  <span class="tag t-err" title="<?= h((string) $l['error']) ?>">Falhou<?= $l['http_code'] ? ' · ' . (int) $l['http_code'] : '' ?></span>
                <?php endif; ?>
              </td>
              <td><span class="tag t-neu"><?= h((string) ($l['status_title'] ?: '—')) ?></span></td>
              <td class="nowrap">
                <?php if ((int) $l['ftd'] === 1): ?>
                  <span class="tag t-ftd">FTD</span>
                  <?php if ($l['ftd_time']): ?><div class="xs muted mono" style="margin-top:3px"><?= h(fmt_dt((string) $l['ftd_time'])) ?></div><?php endif; ?>
                <?php else: ?>
                  <span class="muted">—</span>
                <?php endif; ?>
              </td>
              <td class="mono xs"><?= h((string) ($l['uid'] ?: '—')) ?></td>
              <td class="xs muted"><?= $l['origin'] === 'crm' ? 'CRM' : 'Landing' ?></td>
              <td class="nowrap">
                <?php if ($l['send_status'] === 'failed'): ?>
                  <form method="post" action="resend.php" style="display:inline">
                    <input type="hidden" name="_csrf" value="<?= h(admin_csrf_token()) ?>">
                    <input type="hidden" name="id" value="<?= (int) $l['id'] ?>">
                    <input type="hidden" name="return" value="index.php?<?= h(qs()) ?>">
                    <button class="btn btn-sm" type="submit" title="Reenviar este lead ao CRM">↻ Reenviar</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php if ($pages > 1): ?>
        <div class="pager">
          <?php if ($page > 1): ?><a class="btn btn-sm" href="?<?= h(qs(['page' => $page - 1])) ?>">← Anterior</a><?php endif; ?>
          <span class="small muted">Página <?= $page ?> de <?= $pages ?></span>
          <?php if ($page < $pages): ?><a class="btn btn-sm" href="?<?= h(qs(['page' => $page + 1])) ?>">Próxima →</a><?php endif; ?>
        </div>
      <?php endif; ?>
    <?php endif; ?>
  </div>

  <p class="xs muted" style="margin-top:18px;line-height:1.6">
    Os leads são enviados para <span class="mono"><?= h(PARTNER_API_BASE) ?>/lead/register</span> no momento do cadastro.
    Status e FTD vêm de <span class="mono">/lead/external-leads</span> — clique em <strong>Sincronizar CRM</strong>
    ou agende <span class="mono">admin/cron_sync.php?token=…</span> no cron para atualizar sozinho.
    Datas em UTC.
  </p>
</main>
</body>
</html>
