<?php
// Melhora export_logs.php: filtro de status + fuso do usuario + coluna avaliacao
$f = "/var/www/html/views/export_logs.php";
$c = file_get_contents($f);

// Adiciona parametro status e melhora query
$old1 = '$days  = max(1, min(90, (int)($_GET[\'days\'] ?? 7)));';
$new1 = '$days   = max(1, min(90, (int)($_GET[\'days\'] ?? 7)));
$status = in_array($_GET[\'status\'] ?? \'\', [\'online\', \'offline\']) ? $_GET[\'status\'] : \'all\';';
$c = str_replace($old1, $new1, $c);

// Adiciona fuso do usuario apos o fetch do IP
$old2 = '$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]);';
$new2 = '$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);';
$c = str_replace($old2, $new2, $c);

// Melhora nome do arquivo
$old3 = '$filename = \'monitorping_\' . preg_replace(\'/[^a-z0-9_-]/i\', \'_\', $ipRow[\'host\']) . \'_\' . date(\'Ymd\') . \'.csv\';';
$new3 = '$sfx = $status !== \'all\' ? \'_\'.$status : \'\';
$filename = \'monitorping_\' . preg_replace(\'/[^a-z0-9_-]/i\', \'_\', $ipRow[\'host\']) . \'_\' . $days . \'d\' . $sfx . \'_\' . date(\'Ymd\') . \'.csv\';';
$c = str_replace($old3, $new3, $c);

// Melhora cabecalho do CSV
$old4 = 'fputcsv($out, [\'Data/Hora (UTC)\', \'Status\', \'Latência (ms)\'], \';\');';
$new4 = 'fputcsv($out, [\'Data/Hora (\' . $tz->getName() . \')\', \'Status\', \'Latência (ms)\', \'Avaliação\'], \';\');';
$c = str_replace($old4, $new4, $c);

// Melhora loop de escrita
$old5 = 'while ($row = $rows->fetch()) {
    fputcsv($out, [
        $row[\'checked_at\'],
        $row[\'status\'],
        $row[\'latency_ms\'] ?? \'\'
    ], \';\');
}';
$new5 = '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\'];
    if ($row[\'status\'] === \'offline\')  $av = \'Queda\';
    elseif ($lat === null)              $av = \'Timeout\';
    elseif ($lat > 200)                 $av = \'Latência Alta\';
    elseif ($lat > 100)                 $av = \'Latência Média\';
    else                                $av = \'Ótimo\';
    fputcsv($out, [$dt, strtoupper($row[\'status\']), $lat ?? \'\', $av], \';\');
}';
$c = str_replace($old5, $new5, $c);

file_put_contents($f, $c);
echo "OK export_logs.php\n";
