<?php
// Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
// Painel Central — aba USO. Mostra se cada cliente está abrindo o BI:
// acessos por dia/semana/mês, por usuário, última abertura e alerta de
// cliente inativo (risco de churn). Fonte: storage/uso/<host>.jsonl
// (alimentado por api.php tipo='uso', enviado no login de cada BI).
// So metadado de acesso (quem/quando), nunca conteudo.

date_default_timezone_set('America/Sao_Paulo');

$cfgFile = __DIR__ . '/config.php';
if (!is_file($cfgFile)) { echo '<h1>config.php não existe</h1>'; exit; }
$cfg = include $cfgFile;

session_start();
if (!empty($_GET['sair'])) { session_destroy(); header('Location: index.php'); exit; }
if (empty($_SESSION['painel_logado'])) { header('Location: index.php'); exit; }

// Parametros de negocio (churn)
const DIAS_INATIVO = 7;   // não abre há mais que isso = inativo (vermelho)
const DIAS_ATENCAO = 2;   // abriu nos últimos 2 dias = ativo (verde); entre isso e 7 = atenção

// ---- Coleta eventos -----------------------------------------------------
$dirUso = __DIR__ . '/storage/uso';
$eventos = [];
foreach (glob($dirUso . '/*.jsonl*') ?: [] as $f) {
    foreach (file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $ln) {
        $j = json_decode($ln, true);
        if (!is_array($j)) continue;
        $ts = strtotime((string)($j['em'] ?? '')) ?: strtotime((string)($j['recebido_em'] ?? ''));
        if (!$ts) continue;
        $eventos[] = [
            'cliente' => trim((string)($j['cliente'] ?? '')) ?: '(sem nome)',
            'usuario' => trim((string)($j['usuario'] ?? '')) ?: '(sem usuário)',
            'ts'      => $ts,
            'versao'  => (string)($j['versao_bi'] ?? ''),
        ];
    }
}

$now        = time();
$hojeInicio = strtotime('today');
$ini7       = $now - 7 * 86400;
$ini30      = $now - 30 * 86400;

// ---- Agrega por cliente e por usuário -----------------------------------
$clientes = [];      // nome => agregados
$diarioGlobal = [];  // 'Y-m-d' => total de acessos
for ($d = 29; $d >= 0; $d--) $diarioGlobal[date('Y-m-d', $now - $d * 86400)] = 0;

foreach ($eventos as $e) {
    $nome = $e['cliente'];
    if (!isset($clientes[$nome])) {
        $clientes[$nome] = [
            'nome' => $nome, 'ultima' => 0, 'versao' => '',
            'hoje' => 0, 'a7' => 0, 'a30' => 0, 'total' => 0,
            'usuarios' => [],
        ];
    }
    $c = &$clientes[$nome];
    $c['total']++;
    if ($e['ts'] > $c['ultima']) { $c['ultima'] = $e['ts']; if ($e['versao'] !== '') $c['versao'] = $e['versao']; }
    if ($e['ts'] >= $hojeInicio) $c['hoje']++;
    if ($e['ts'] >= $ini7)       $c['a7']++;
    if ($e['ts'] >= $ini30)      $c['a30']++;

    $u = $e['usuario'];
    if (!isset($c['usuarios'][$u])) $c['usuarios'][$u] = ['nome' => $u, 'ultima' => 0, 'hoje' => 0, 'a7' => 0, 'a30' => 0, 'total' => 0];
    $cu = &$c['usuarios'][$u];
    $cu['total']++;
    if ($e['ts'] > $cu['ultima']) $cu['ultima'] = $e['ts'];
    if ($e['ts'] >= $hojeInicio) $cu['hoje']++;
    if ($e['ts'] >= $ini7)       $cu['a7']++;
    if ($e['ts'] >= $ini30)      $cu['a30']++;
    unset($cu);
    unset($c);

    $dia = date('Y-m-d', $e['ts']);
    if (isset($diarioGlobal[$dia])) $diarioGlobal[$dia]++;
}

// ---- Classificação de cada cliente --------------------------------------
function statusCliente(int $ultima, int $now): array {
    if ($ultima === 0) return ['inativo', 'SEM ACESSO', 'vermelho'];
    $dias = (int)floor(($now - $ultima) / 86400);
    if ($dias <= DIAS_ATENCAO) return ['ativo',   'ATIVO',   'verde'];
    if ($dias <= DIAS_INATIVO) return ['atencao', 'ATENÇÃO', 'amarelo'];
    return ['inativo', 'INATIVO', 'vermelho'];
}

// KPIs executivos
$kAtivosHoje = $kAtivos7 = $kInativos = $kAcessosHoje = 0;
$usuariosHojeSet = [];
$inativosLista = [];
foreach ($clientes as $c) {
    [$slug] = statusCliente($c['ultima'], $now);
    if ($c['ultima'] >= $hojeInicio) $kAtivosHoje++;
    if ($c['ultima'] >= $ini7)       $kAtivos7++;
    if ($slug === 'inativo') { $kInativos++; $inativosLista[] = $c; }
    $kAcessosHoje += $c['hoje'];
    foreach ($c['usuarios'] as $u) if ($u['ultima'] >= $hojeInicio) $usuariosHojeSet[$c['nome'] . '|' . $u['nome']] = true;
}
$kUsuariosHoje = count($usuariosHojeSet);
$kTotalClientes = count($clientes);

// Ordena: quem abriu mais recente primeiro (inativos afundam pra chamar atenção via cor)
uasort($clientes, fn($a, $b) => $b['ultima'] <=> $a['ultima']);
usort($inativosLista, fn($a, $b) => $a['ultima'] <=> $b['ultima']); // mais tempo sem abrir primeiro

// Ranking por acessos no mês (top 12)
$ranking = $clientes;
uasort($ranking, fn($a, $b) => $b['a30'] <=> $a['a30']);
$ranking = array_slice(array_values($ranking), 0, 12);
$rankMax = 0; foreach ($ranking as $r) $rankMax = max($rankMax, $r['a30']);

// ---- Exportação CSV -----------------------------------------------------
if (!empty($_GET['csv'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="uso-clientes-' . date('Ymd') . '.csv"');
    $out = fopen('php://output', 'w');
    fwrite($out, "\xEF\xBB\xBF"); // BOM p/ Excel PT-BR
    fputcsv($out, ['Cliente', 'Status', 'Ultima abertura', 'Dias sem abrir', 'Acessos hoje', 'Acessos 7d', 'Acessos 30d', 'Usuarios', 'Versao'], ';');
    foreach ($clientes as $c) {
        [, $lbl] = statusCliente($c['ultima'], $now);
        $dias = $c['ultima'] ? (int)floor(($now - $c['ultima']) / 86400) : '';
        fputcsv($out, [
            $c['nome'], $lbl,
            $c['ultima'] ? date('d/m/Y H:i', $c['ultima']) : '-',
            $dias, $c['hoje'], $c['a7'], $c['a30'], count($c['usuarios']), $c['versao'],
        ], ';');
    }
    fclose($out);
    exit;
}

function ago2(int $em, int $now): string {
    if ($em === 0) return 'nunca';
    $d = $now - $em;
    if ($d < 60) return 'agora';
    if ($d < 3600) return floor($d / 60) . ' min atrás';
    if ($d < 86400) return floor($d / 3600) . 'h atrás';
    return floor($d / 86400) . 'd atrás';
}

// SVG de tendência (área) — 30 dias, self-contained (sem CDN)
$serie = array_values($diarioGlobal);
$labels = array_keys($diarioGlobal);
$maxDia = max(1, max($serie));
$W = 900; $H = 160; $pad = 24;
$n = count($serie);
$px = fn($i) => $pad + ($n <= 1 ? 0 : $i * ($W - 2 * $pad) / ($n - 1));
$py = fn($v) => $H - $pad - ($v / $maxDia) * ($H - 2 * $pad);
$linha = ''; $areaPts = '';
foreach ($serie as $i => $v) {
    $x = round($px($i), 1); $y = round($py($v), 1);
    $linha  .= ($i ? ' L ' : 'M ') . $x . ' ' . $y;
    $areaPts .= $x . ',' . $y . ' ';
}
$area = 'M ' . round($px(0), 1) . ' ' . ($H - $pad) . ' L ' . trim(str_replace(' L ', ' L ', $linha), 'M ') ;
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Uso dos clientes — Painel Central — Master Automação</title>
<style>
body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; color: #0f172a; margin: 0; padding: 1.5rem; }
a { color: #6366f1; }
.top { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:.5rem; margin-bottom:1rem; }
h1 { margin: 0; font-size: 1.4rem; }
h2 { font-size: 1rem; color:#475569; margin: 1.6rem 0 .6rem; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: .7rem; margin-bottom: 1rem; }
.kpi { background: #fff; border-left: 4px solid #94a3b8; border-radius: 8px; padding: .9rem; box-shadow: 0 1px 3px rgba(0,0,0,.05); }
.kpi.verde   { border-color: #16a34a; background: #dcfce7; }
.kpi.azul    { border-color: #2563eb; background: #dbeafe; }
.kpi.amarelo { border-color: #f59e0b; background: #fef3c7; }
.kpi.vermelho{ border-color: #dc2626; background: #fee2e2; }
.kpi .lbl { font-size: .74rem; font-weight: 800; opacity: .85; }
.kpi .num { font-size: 2rem; font-weight: 800; line-height: 1.1; }
.kpi .sub { font-size: .72rem; opacity:.7; }
.painel { background:#fff; border:1px solid #e2e8f0; border-radius:10px; padding:1rem 1.2rem; box-shadow:0 1px 3px rgba(0,0,0,.05); }
.alerta { background:#fef2f2; border:1px solid #fecaca; border-radius:10px; padding:.9rem 1.1rem; margin-bottom:1rem; }
.alerta b { color:#991b1b; }
.alerta ul { margin:.5rem 0 0; padding-left:1.1rem; }
.alerta li { font-size:.86rem; margin:.15rem 0; }
table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,.05); }
th, td { padding: .55rem .8rem; text-align: left; font-size: .86rem; border-top: 1px solid #f1f5f9; }
th { background: #f8fafc; font-size: .7rem; color: #475569; text-transform: uppercase; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
tr.linha { cursor: pointer; } tr.linha:hover { background: #f8fafc; }
tr.det td { background:#fafafa; padding: .8rem 1.2rem; }
.tag { display:inline-block; padding:.18rem .6rem; border-radius:12px; font-size:.7rem; font-weight:800; }
.tag.verde{ background:#dcfce7; color:#166534; } .tag.amarelo{ background:#fef3c7; color:#854d0e; } .tag.vermelho{ background:#fee2e2; color:#991b1b; }
.bar { background:#eef2ff; border-radius:5px; height:22px; position:relative; }
.bar > span { position:absolute; inset:0; display:flex; align-items:center; padding-left:.5rem; font-size:.78rem; font-weight:700; color:#1e293b; }
.bar > i { display:block; height:100%; background:linear-gradient(90deg,#6366f1,#818cf8); border-radius:5px; }
.rank td { border:none; padding:.28rem .5rem; }
.hint { color:#94a3b8; font-size:.72rem; }
</style>
</head>
<body>

<div class="top">
  <h1>📈 Uso dos clientes — <span style="color:#6366f1">Master Automação</span></h1>
  <div class="hint">
    <a href="index.php">🛡️ Backups</a> ·
    <a href="atualizacoes.php" style="color:#10b981">🔄 Atualizações</a> ·
    <a href="?csv=1" style="color:#0891b2">⬇ Exportar CSV</a> ·
    <a href="?sair=1">Sair</a>
  </div>
</div>

<?php if ($kTotalClientes === 0): ?>
  <div class="painel">
    <p><b>Ainda não há registros de uso.</b></p>
    <p class="hint">Os dados aparecem aqui quando os BIs começarem a reportar login (após publicar a versão com telemetria e o cliente abrir o sistema). Só metadado de acesso — quem abriu e quando, nunca conteúdo.</p>
  </div>
<?php else: ?>

<!-- ================= EXECUTIVO ================= -->
<div class="cards">
  <div class="kpi verde"><div class="lbl">🟢 ABRIRAM HOJE</div><div class="num"><?= $kAtivosHoje ?></div><div class="sub">de <?= $kTotalClientes ?> clientes</div></div>
  <div class="kpi azul"><div class="lbl">👥 USUÁRIOS HOJE</div><div class="num"><?= $kUsuariosHoje ?></div><div class="sub"><?= $kAcessosHoje ?> acessos</div></div>
  <div class="kpi azul"><div class="lbl">📅 ATIVOS 7 DIAS</div><div class="num"><?= $kAtivos7 ?></div><div class="sub">abriram na semana</div></div>
  <div class="kpi <?= $kInativos > 0 ? 'vermelho' : 'verde' ?>"><div class="lbl">🔴 INATIVOS (+<?= DIAS_INATIVO ?>d)</div><div class="num"><?= $kInativos ?></div><div class="sub">risco de churn</div></div>
  <div class="kpi"><div class="lbl">🏢 TOTAL CLIENTES</div><div class="num"><?= $kTotalClientes ?></div><div class="sub">já reportaram uso</div></div>
</div>

<?php if (!empty($inativosLista)): ?>
<div class="alerta">
  <b>⚠ <?= count($inativosLista) ?> cliente(s) não abrem o BI há mais de <?= DIAS_INATIVO ?> dias:</b>
  <ul>
    <?php foreach (array_slice($inativosLista, 0, 8) as $c): $dias = $c['ultima'] ? (int)floor(($now - $c['ultima']) / 86400) : null; ?>
      <li><b><?= htmlspecialchars($c['nome']) ?></b> — <?= $dias === null ? 'nunca abriu' : "não abre há {$dias} dias" ?> (última: <?= $c['ultima'] ? date('d/m/Y H:i', $c['ultima']) : '—' ?>)</li>
    <?php endforeach; ?>
  </ul>
</div>
<?php endif; ?>

<!-- ================= VISUAL ================= -->
<h2>Acessos por dia (últimos 30 dias)</h2>
<div class="painel">
  <svg viewBox="0 0 <?= $W ?> <?= $H ?>" width="100%" preserveAspectRatio="xMidYMid meet" style="display:block">
    <defs><linearGradient id="g1" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="#6366f1" stop-opacity="0.35"/><stop offset="100%" stop-color="#6366f1" stop-opacity="0.02"/>
    </linearGradient></defs>
    <path d="<?= $area ?> L <?= round($px($n - 1), 1) ?> <?= $H - $pad ?> Z" fill="url(#g1)"/>
    <path d="<?= $linha ?>" fill="none" stroke="#6366f1" stroke-width="2.5"/>
    <?php foreach ($serie as $i => $v): if ($v > 0): ?>
      <circle cx="<?= round($px($i), 1) ?>" cy="<?= round($py($v), 1) ?>" r="2.5" fill="#4338ca"><title><?= date('d/m', strtotime($labels[$i])) ?>: <?= $v ?> acessos</title></circle>
    <?php endif; endforeach; ?>
    <text x="<?= $pad ?>" y="14" font-size="11" fill="#94a3b8"><?= date('d/m', strtotime($labels[0])) ?></text>
    <text x="<?= $W - $pad - 30 ?>" y="14" font-size="11" fill="#94a3b8"><?= date('d/m', strtotime($labels[$n - 1])) ?></text>
  </svg>
</div>

<h2>Ranking — mais usam o BI (acessos no mês)</h2>
<div class="painel">
  <table class="rank">
    <?php foreach ($ranking as $r): $pct = $rankMax ? round($r['a30'] / $rankMax * 100) : 0; ?>
      <tr>
        <td style="width:32%; font-weight:600"><?= htmlspecialchars($r['nome']) ?></td>
        <td><div class="bar"><i style="width:<?= max(4, $pct) ?>%"></i><span><?= $r['a30'] ?> acessos</span></div></td>
      </tr>
    <?php endforeach; ?>
  </table>
</div>

<!-- ================= DETALHADO ================= -->
<h2>Todos os clientes <span class="hint">(clique numa linha pra ver por usuário)</span></h2>
<table>
  <thead>
    <tr>
      <th>Cliente</th><th>Status</th><th>Última abertura</th>
      <th class="num">Hoje</th><th class="num">7 dias</th><th class="num">Mês</th>
      <th class="num">Usuários</th><th>Versão</th>
    </tr>
  </thead>
  <tbody>
    <?php $idx = 0; foreach ($clientes as $c): [$slug, $lbl, $cor] = statusCliente($c['ultima'], $now); $idx++; ?>
      <tr class="linha" onclick="document.getElementById('d<?= $idx ?>').style.display = (document.getElementById('d<?= $idx ?>').style.display==='table-row'?'none':'table-row')">
        <td><b><?= htmlspecialchars($c['nome']) ?></b></td>
        <td><span class="tag <?= $cor ?>"><?= $lbl ?></span></td>
        <td><?= $c['ultima'] ? date('d/m/Y H:i', $c['ultima']) : '—' ?> <span class="hint"><?= ago2($c['ultima'], $now) ?></span></td>
        <td class="num"><?= $c['hoje'] ?></td>
        <td class="num"><?= $c['a7'] ?></td>
        <td class="num"><?= $c['a30'] ?></td>
        <td class="num"><?= count($c['usuarios']) ?></td>
        <td><?= htmlspecialchars($c['versao'] ?: '—') ?></td>
      </tr>
      <tr class="det" id="d<?= $idx ?>" style="display:none">
        <td colspan="8">
          <table>
            <thead><tr><th>Usuário</th><th>Última abertura</th><th class="num">Hoje</th><th class="num">7 dias</th><th class="num">Mês</th><th class="num">Total</th></tr></thead>
            <tbody>
              <?php $us = $c['usuarios']; uasort($us, fn($a, $b) => $b['ultima'] <=> $a['ultima']); foreach ($us as $u): ?>
                <tr>
                  <td><?= htmlspecialchars($u['nome']) ?></td>
                  <td><?= $u['ultima'] ? date('d/m/Y H:i', $u['ultima']) : '—' ?> <span class="hint"><?= ago2($u['ultima'], $now) ?></span></td>
                  <td class="num"><?= $u['hoje'] ?></td>
                  <td class="num"><?= $u['a7'] ?></td>
                  <td class="num"><?= $u['a30'] ?></td>
                  <td class="num"><?= $u['total'] ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<p class="hint" style="margin-top:1rem">
  Fonte: login de cada BI → <code>api.php</code> (tipo=uso) → <code>storage/uso/&lt;host&gt;.jsonl</code>.
  Cliente = nome da empresa no <code>config/database.php</code>. Horário de Brasília. Só metadado (quem/quando), nunca conteúdo.
</p>

<?php endif; ?>

</body>
</html>
