<?php
// ── 1. user_logs.php — adiciona botão de exportar no header dos logs ───────
$f1 = "/var/www/html/views/user_logs.php";
$c1 = file_get_contents($f1);

// Ancora: logo após os stats (quedas) e antes do fechamento do div de header
$old1 = '        <?php if ($offlineLogs > 0): ?>
            <div style="border-left:1px solid #cbd5e1; padding-left:16px; text-align:right;">
                <small style="color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.75rem; letter-spacing:0.05em;">Quedas</small>
                <div style="font-size:1.6rem; font-weight:800; color:#dc2626;"><?php echo $offlineLogs; ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>';

$new1 = '        <?php if ($offlineLogs > 0): ?>
            <div style="border-left:1px solid #cbd5e1; padding-left:16px; text-align:right;">
                <small style="color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.75rem; letter-spacing:0.05em;">Quedas</small>
                <div style="font-size:1.6rem; font-weight:800; color:#dc2626;"><?php echo $offlineLogs; ?></div>
            </div>
            <?php endif; ?>
            <!-- Exportar -->
            <div style="position:relative;" id="export-wrap">
                <button onclick="document.getElementById(\'export-menu\').classList.toggle(\'open\')"
                    style="display:inline-flex;align-items:center;gap:8px;padding:10px 18px;background:#fff;border:1px solid #e2e8f0;border-radius:10px;font-weight:700;font-size:0.88rem;color:#475569;cursor:pointer;transition:border-color .15s;"
                    onmouseover="this.style.borderColor=\'#ea580c\';this.style.color=\'#ea580c\'"
                    onmouseout="this.style.borderColor=\'#e2e8f0\';this.style.color=\'#475569\'">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                    Exportar CSV ▾
                </button>
                <div id="export-menu" style="display:none;position:absolute;right:0;top:calc(100% + 6px);background:#fff;border:1px solid #e2e8f0;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.1);min-width:220px;z-index:100;overflow:hidden;">
                    <?php
                    $exportBase = "index.php?page=export_logs&ip_id={$ip['id']}&status={$filterStatus}";
                    foreach ([7 => 'Últimos 7 dias', 30 => 'Últimos 30 dias', 90 => 'Últimos 90 dias'] as $d => $lbl):
                    ?>
                    <a href="<?= h($exportBase . '&days=' . $d) ?>"
                       style="display:flex;align-items:center;gap:10px;padding:12px 18px;color:#374151;font-size:0.88rem;font-weight:600;text-decoration:none;border-bottom:1px solid #f1f5f9;transition:background .12s;"
                       onmouseover="this.style.background=\'#fff7ed\'" onmouseout="this.style.background=\'#fff\'">
                        <svg width="14" height="14" fill="none" stroke="#ea580c" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                        <?= $lbl ?>
                        <?php if ($filterStatus !== 'all'): ?>
                            <span style="margin-left:auto;font-size:0.75rem;background:#f1f5f9;padding:2px 6px;border-radius:6px;color:#64748b;"><?= $filterStatus ?></span>
                        <?php endif; ?>
                    </a>
                    <?php endforeach; ?>
                    <?php if ($filterStatus !== 'all'): ?>
                    <div style="padding:8px 18px;font-size:0.75rem;color:#94a3b8;background:#fafafa;">
                        Filtro ativo: <strong><?= $filterStatus ?></strong> — exportando apenas esses registros
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
<script>
document.addEventListener("click", function(e) {
    var wrap = document.getElementById("export-wrap");
    var menu = document.getElementById("export-menu");
    if (wrap && menu && !wrap.contains(e.target)) {
        menu.classList.remove("open");
        menu.style.display = "none";
    }
});
document.getElementById("export-menu").addEventListener("transitionend", function(){});
// Sobrescreve toggle para usar display
(function() {
    var btn = document.querySelector("#export-wrap button");
    var menu = document.getElementById("export-menu");
    if (!btn || !menu) return;
    btn.onclick = function(e) {
        e.stopPropagation();
        menu.style.display = menu.style.display === "none" ? "block" : "none";
    };
    document.addEventListener("click", function() { menu.style.display = "none"; });
})();
</script>';

if (strpos($c1, 'export-wrap') !== false) {
    echo "SKIP user_logs.php (botao ja existe)\n";
} elseif (strpos($c1, $old1) !== false) {
    file_put_contents($f1, str_replace($old1, $new1, $c1));
    echo "OK user_logs.php\n";
} else {
    echo "FAIL user_logs.php — ancora nao encontrada\n";
}

// ── 2. export_logs.php — suporte ao filtro de status + fuso do usuario ──────
$f2 = "/var/www/html/views/export_logs.php";
$c2 = file_get_contents($f2);

$old2 = '<?php
// #34 Exportação de logs em CSV
require_once __DIR__ . \'/../includes/header.php\';

$pdo   = db();
$ipId  = (int)($_GET[\'ip_id\'] ?? 0);
$days  = max(1, min(90, (int)($_GET[\'days\'] ?? 7)));

if (!$ipId) {
    http_response_code(400);
    echo \'IP não informado.\';
    exit;
}

// Verifica ownership
$ipStmt = $pdo->prepare("SELECT id, label, host FROM monitored_ips WHERE id = ? AND user_id = ?");
$ipStmt->execute([$ipId, $user[\'id\']]);
$ipRow = $ipStmt->fetch();
if (!$ipRow) {
    http_response_code(403);
    echo \'Acesso negado.\';
    exit;
}

$rows = $pdo->prepare("
    SELECT checked_at, status, latency_ms
    FROM ping_logs
    WHERE monitored_ip_id = ?
      AND checked_at >= NOW() - ? * INTERVAL \'1 day\'
    ORDER BY checked_at DESC
");
$rows->execute([$ipId, $days]);

$filename = \'monitorping_\' . preg_replace(\'/[^a-z0-9_-]/i\', \'_\', $ipRow[\'host\']) . \'_\' . date(\'Ymd\') . \'.csv\';

header(\'Content-Type: text/csv; charset=UTF-8\');
header(\'Content-Disposition: attachment; filename="\' . $filename . \'"\');
header(\'Cache-Control: no-cache\');

$out = fopen(\'php://output\', \'w\');
// BOM UTF-8 para Excel abrir corretamente
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, [\'Data/Hora (UTC)\', \'Status\', \'Latência (ms)\'], \';\');

while ($row = $rows->fetch()) {
    fputcsv($out, [
        $row[\'checked_at\'],
        $row[\'status\'],
        $row[\'latency_ms\'] ?? \'\'
    ], \';\');
}
fclose($out);
exit;';

$new2 = '<?php
// #34 Exportação de logs em CSV
require_once __DIR__ . \'/../includes/header.php\';
require_once __DIR__ . \'/../includes/functions.php\';

$pdo    = db();
$ipId   = (int)($_GET[\'ip_id\'] ?? 0);
$days   = max(1, min(90, (int)($_GET[\'days\'] ?? 7)));
$status = in_array($_GET[\'status\'] ?? \'\', [\'online\', \'offline\']) ? $_GET[\'status\'] : \'all\';

if (!$ipId) {
    http_response_code(400);
    echo \'IP não informado.\';
    exit;
}

// Verifica ownership
$ipStmt = $pdo->prepare("SELECT id, label, host FROM monitored_ips WHERE id = ? AND user_id = ?");
$ipStmt->execute([$ipId, $user[\'id\']]);
$ipRow = $ipStmt->fetch();
if (!$ipRow) {
    http_response_code(403);
    echo \'Acesso negado.\';
    exit;
}

// Fuso do usuário
$tz = new DateTimeZone(in_array($user[\'timezone\'] ?? \'\', timezone_identifiers_list(), true) ? $user[\'timezone\'] : \'America/Sao_Paulo\');

$sql = "SELECT checked_at, status, latency_ms FROM ping_logs
        WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL \'1 day\'";
$params = [$ipId, $days];
if ($status !== \'all\') {
    $sql .= " AND status = ?";
    $params[] = $status;
}
$sql .= " ORDER BY checked_at DESC";
$rows = $pdo->prepare($sql);
$rows->execute($params);

$statusSuffix = $status !== \'all\' ? \'_\' . $status : \'\';
$filename = \'monitorping_\' . preg_replace(\'/[^a-z0-9_-]/i\', \'_\', $ipRow[\'host\']) . \'_\' . $days . \'d\' . $statusSuffix . \'_\' . date(\'Ymd\') . \'.csv\';

header(\'Content-Type: text/csv; charset=UTF-8\');
header(\'Content-Disposition: attachment; filename="\' . $filename . \'"\');
header(\'Cache-Control: no-cache\');

$out = fopen(\'php://output\', \'w\');
fwrite($out, "\xEF\xBB\xBF");
$tzLabel = $tz->getName();
fputcsv($out, [\'Data/Hora (\' . $tzLabel . \')\', \'Status\', \'Latência (ms)\', \'Avaliação\'], \';\');

while ($row = $rows->fetch()) {
    $dt  = $row[\'checked_at\'] ? (new DateTimeImmutable($row[\'checked_at\']))->setTimezone($tz)->format(\'d/m/Y H:i:s\') : \'\';
    $lat = $row[\'latency_ms\'];
    $avaliacao = $row[\'status\'] === \'offline\' ? \'Queda\' : ($lat === null ? \'Timeout\' : ($lat > 200 ? \'Latência Alta\' : ($lat > 100 ? \'Latência Média\' : \'Ótimo\')));
    fputcsv($out, [
        $dt,
        strtoupper($row[\'status\']),
        $lat ?? \'\',
        $avaliacao,
    ], \';\');
}
fclose($out);
exit;';

if (strpos($c2, $old2) !== false) {
    file_put_contents($f2, str_replace($old2, $new2, $c2));
    echo "OK export_logs.php\n";
} else {
    echo "FAIL export_logs.php\n";
    // Tentar patch parcial: adiciona filtro de status
    $c2b = str_replace(
        '$rows->execute([$ipId, $days]);',
        '$statusSuffix2 = "";
if ($status !== \'all\') { $sql .= " AND status = ?"; $params[] = $status; $statusSuffix2 = "_".$status; }
$rows = $pdo->prepare($sql); $rows->execute($params);',
        $c2
    );
    file_put_contents($f2, $c2b);
    echo "FALLBACK export_logs.php\n";
}

echo "DONE\n";
