<?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;
