<?php
// Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
// Dashboard central de backups com DETALHES expansíveis por linha.

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

session_start();
if (!empty($_POST['senha']) && hash_equals((string)($cfg['senha_admin'] ?? ''), (string)$_POST['senha'])) {
    $_SESSION['painel_logado'] = true;
}
if (!empty($_GET['sair'])) { session_destroy(); header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; }
if (empty($_SESSION['painel_logado'])) {
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Painel Central de Backups — Master Automação</title>
    <style>body{font-family:system-ui;background:#0f172a;color:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}
    .card{background:#1e293b;padding:2rem;border-radius:12px;max-width:380px;width:90%}
    h1{margin:0 0 1rem;font-size:1.4rem}
    input{width:100%;padding:.7rem;border-radius:6px;border:1px solid #475569;background:#0f172a;color:#fff;box-sizing:border-box}
    button{margin-top:.7rem;width:100%;padding:.7rem;background:#6366f1;color:#fff;border:none;border-radius:6px;font-weight:700;cursor:pointer}</style>
    </head><body><div class="card">
    <h1>🛡️ Painel Central de Backups — Master Automação</h1>
    <form method="post"><input type="password" name="senha" placeholder="Senha admin" autofocus required><button>Entrar</button></form>
    </div></body></html>';
    exit;
}

$dirStorage = __DIR__ . '/storage';
$clientes = [];
foreach (glob($dirStorage . '/*.json') ?: [] as $f) {
    $j = @json_decode((string)@file_get_contents($f), true);
    if (is_array($j)) {
        $j['_arquivo_json'] = basename($f);
        $clientes[] = $j;
    }
}

// Calcula limite por cliente: backup diario vira ATRASADO em 28h,
// 12h em 14h, semanal em 8 dias, etc. Cliente sem dica de frequencia
// nos metadados usa 28h como default (cobre o caso comum diario).
function _limiteAtrasoSeg(array $c): int {
    $intervalo = (int)($c['intervalo_esperado_horas'] ?? 0);
    if ($intervalo > 0) return ($intervalo + 4) * 3600;  // +4h tolerancia
    return 28 * 3600;                                      // default diario + tolerancia
}

$totOk = $totFalha = $totAtraso = 0;
foreach ($clientes as $c) {
    $em = strtotime((string)($c['em'] ?? 'now'));
    if (($c['status'] ?? '') === 'falha')           $totFalha++;
    elseif ((time() - $em) > _limiteAtrasoSeg($c))  $totAtraso++;
    else                                             $totOk++;
}
usort($clientes, function ($a, $b) {
    $em_a = strtotime((string)($a['em'] ?? 'now'));
    $em_b = strtotime((string)($b['em'] ?? 'now'));
    return $em_b - $em_a;  // mais recente primeiro
});

function fmtMB(int $b): string {
    if ($b < 1024)              return $b . ' B';
    if ($b < 1048576)           return number_format($b/1024, 0, ',', '.') . ' KB';
    if ($b < 1073741824)        return number_format($b/1048576, 1, ',', '.') . ' MB';
    return number_format($b/1073741824, 2, ',', '.') . ' GB';
}
function ago(int $em): string {
    $d = time() - $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';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Painel Central de Backups — Master Automação</title>
<meta http-equiv="refresh" content="60">
<style>
body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; color: #0f172a; margin: 0; padding: 1.5rem; }
h1 { margin: 0 0 1rem; font-size: 1.5rem; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: .7rem; margin-bottom: 1.5rem; }
.kpi { background: #fff; border-left: 4px solid #94a3b8; border-radius: 8px; padding: .9rem; box-shadow: 0 1px 3px rgba(0,0,0,.05); }
.kpi.ok { border-color: #16a34a; background: #dcfce7; }
.kpi.falha { border-color: #dc2626; background: #fee2e2; }
.kpi.atraso { border-color: #f59e0b; background: #fef3c7; }
.kpi .lbl { font-size: .78rem; font-weight: 700; opacity: .8; }
.kpi .num { font-size: 2rem; font-weight: 800; }
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: .6rem .8rem; text-align: left; font-size: .87rem; border-top: 1px solid #f1f5f9; }
th { background: #f8fafc; font-size: .72rem; color: #475569; text-transform: uppercase; }
tr.linha { cursor: pointer; }
tr.linha:hover { background: #f8fafc; }
tr.detalhes td { background: #fafafa; padding: 1rem; }
tr.detalhes pre { background: #1e293b; color: #e2e8f0; padding: 1rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; line-height: 1.5; }
.tag { display: inline-block; padding: .2rem .65rem; border-radius: 12px; font-size: .72rem; font-weight: 800; }
.tag.ok    { background: #dcfce7; color: #166534; }
.tag.falha { background: #fee2e2; color: #991b1b; }
.tag.atraso{ background: #fef3c7; color: #854d0e; }
.detalhe-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 1rem; margin-bottom: 1rem; }
.detalhe-grid div { background: #fff; padding: .7rem 1rem; border-radius: 6px; border: 1px solid #e2e8f0; }
.detalhe-grid div small { color: #64748b; font-size: .72rem; font-weight: 700; text-transform: uppercase; display: block; margin-bottom: .2rem; }
.detalhe-grid div strong { font-size: .9rem; word-break: break-all; }
.erro-bloco { background: #fee2e2; color: #991b1b; padding: .7rem 1rem; border-radius: 6px; font-family: monospace; font-size: .8rem; margin-bottom: 1rem; word-break: break-word; white-space: pre-wrap; }
</style>
</head>
<body>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem">
  <h1>🛡️ Painel Central de Backups — <span style="color:#6366f1">Master Automação</span></h1>
  <div><small style="color:#94a3b8">atualiza a cada 60s · clique numa linha pra ver detalhes</small> · <a href="?sair=1" style="color:#6366f1">Sair</a></div>
</div>

<div class="cards">
  <div class="kpi ok"><div class="lbl">✅ EM DIA</div><div class="num"><?= $totOk ?></div></div>
  <div class="kpi falha"><div class="lbl">❌ FALHA</div><div class="num"><?= $totFalha ?></div></div>
  <div class="kpi atraso"><div class="lbl">⚠ ATRASADO</div><div class="num"><?= $totAtraso ?></div></div>
  <div class="kpi"><div class="lbl">📊 TOTAL</div><div class="num"><?= count($clientes) ?></div></div>
</div>

<table>
  <thead>
    <tr>
      <th></th>
      <th>Cliente</th>
      <th>Status</th>
      <th>Último</th>
      <th>Tamanho</th>
      <th>Modo</th>
      <th>Máquina</th>
      <th>IP</th>
    </tr>
  </thead>
  <tbody>
    <?php if (empty($clientes)): ?>
      <tr><td colspan="8" style="text-align:center;padding:3rem;color:#94a3b8">Nenhum cliente reportou ainda.</td></tr>
    <?php endif; ?>
    <?php foreach ($clientes as $i => $c):
      $em = strtotime((string)($c['em'] ?? 'now'));
      if (($c['status'] ?? '')==='falha')                 { $cls='falha'; $lbl='FALHA'; }
      elseif ((time()-$em) > _limiteAtrasoSeg($c))        { $cls='atraso'; $lbl='ATRASADO'; }
      else                                                { $cls='ok'; $lbl='OK'; }
    ?>
      <tr class="linha" onclick="document.getElementById('d<?= $i ?>').style.display = document.getElementById('d<?= $i ?>').style.display === 'table-row' ? 'none' : 'table-row'">
        <td>▸</td>
        <td><strong><?= htmlspecialchars($c['cliente'] ?? '?') ?></strong></td>
        <td><span class="tag <?= $cls ?>"><?= $lbl ?></span></td>
        <td><?= date('d/m/Y H:i', $em) ?><br><small style="color:#94a3b8"><?= ago($em) ?></small></td>
        <td><?= fmtMB((int)($c['tamanho'] ?? 0)) ?></td>
        <td style="color:#64748b;font-size:.78rem"><?= htmlspecialchars($c['modo'] ?? '?') ?><?= !empty($c['comprimido']) ? ' + .tar.gz' : '' ?></td>
        <td style="color:#475569"><?= htmlspecialchars($c['host_cliente'] ?? '?') ?></td>
        <td style="color:#94a3b8;font-family:monospace;font-size:.75rem"><?= htmlspecialchars($c['ip_remoto'] ?? '?') ?></td>
      </tr>
      <tr id="d<?= $i ?>" class="detalhes" style="display:none">
        <td colspan="8">
          <div class="detalhe-grid">
            <div><small>Cliente</small><strong><?= htmlspecialchars($c['cliente'] ?? '?') ?></strong></div>
            <div><small>Job ID</small><strong style="font-family:monospace"><?= htmlspecialchars($c['job_id'] ?? '?') ?></strong></div>
            <div><small>Data/hora exata</small><strong><?= htmlspecialchars($c['em'] ?? '?') ?></strong></div>
            <div><small>Duração</small><strong><?= number_format((float)($c['duracao_seg'] ?? 0), 1, ',', '.') ?> segundos</strong></div>
            <div><small>Tamanho final</small><strong><?= fmtMB((int)($c['tamanho'] ?? 0)) ?></strong></div>
            <div><small>Modo backup</small><strong><?= htmlspecialchars($c['modo'] ?? '?') ?> <?= !empty($c['comprimido']) ? ' (com tar.gz)' : '(sem compressão)' ?></strong></div>
            <div><small>Versão BI</small><strong><?= htmlspecialchars($c['versao_bi'] ?? '?') ?></strong></div>
            <div><small>Recebido em</small><strong><?= htmlspecialchars($c['recebido_em'] ?? '?') ?></strong></div>
          </div>
          <?php if (!empty($c['erro'])): ?>
            <div class="erro-bloco">❌ <strong>Erro:</strong> <?= htmlspecialchars($c['erro']) ?></div>
          <?php endif; ?>
          <details>
            <summary style="cursor:pointer;color:#475569;font-size:.85rem;font-weight:700">🔬 JSON completo</summary>
            <pre><?= htmlspecialchars(json_encode($c, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?></pre>
          </details>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<p style="margin-top:1.5rem;color:#94a3b8;font-size:.78rem">💡 Cada arquivo em <code>storage/</code> é 1 job de cliente. Cliques na linha pra abrir/fechar detalhes.</p>
</body>
</html>
