<?php
// ── 1. Cria views/export_incidents_pdf.php ──────────────────────────────────
$pdfFile = '/var/www/html/views/export_incidents_pdf.php';

if (file_exists($pdfFile)) {
    echo "SKIP: export_incidents_pdf.php ja existe\n";
} else {
    $content = <<<'PHPEOF'
<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../config.php';

require_login();
$user = current_user();
$pdo  = db();

$ipId = (int)($_GET['ip_id'] ?? 0);
$days = max(1, min(365, (int)($_GET['days'] ?? 30)));

if (!$ipId) { http_response_code(400); echo 'IP nao informado.'; exit; }

$ipStmt = $pdo->prepare("SELECT * 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; }

$tz = new DateTimeZone(in_array($user['timezone'] ?? '', timezone_identifiers_list(), true) ? $user['timezone'] : 'America/Sao_Paulo');

$statsStmt = $pdo->prepare("
    SELECT COUNT(*) AS total,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL '1 day'
");
$statsStmt->execute([$ipId, $days]);
$stats = $statsStmt->fetch();
$totalChecks = (int)($stats['total'] ?? 0);
$onCount     = (int)($stats['on_count'] ?? 0);
$uptimePct   = $totalChecks > 0 ? round($onCount / $totalChecks * 100, 3) : null;

$transStmt = $pdo->prepare("
    WITH logs AS (
        SELECT checked_at, status,
               LAG(status) OVER (ORDER BY checked_at) AS prev_status
        FROM ping_logs
        WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL '1 day'
    )
    SELECT checked_at::TEXT, status FROM logs
    WHERE status IS DISTINCT FROM prev_status
    ORDER BY checked_at LIMIT 2000
");
$transStmt->execute([$ipId, $days]);
$transitions = $transStmt->fetchAll();

$incidents    = [];
$totalDownSec = 0;
$pendingStart = null;

foreach ($transitions as $t) {
    if ($t['status'] === 'offline') {
        $pendingStart = $t['checked_at'];
    } elseif ($t['status'] === 'online' && $pendingStart !== null) {
        try {
            $startDt = new DateTimeImmutable($pendingStart);
            $endDt   = new DateTimeImmutable($t['checked_at']);
            $dur = max(0, $endDt->getTimestamp() - $startDt->getTimestamp());
            $totalDownSec += $dur;
            $incidents[] = ['start' => $startDt->setTimezone($tz)->format('d/m/Y H:i:s'), 'end' => $endDt->setTimezone($tz)->format('d/m/Y H:i:s'), 'duration' => $dur, 'open' => false];
        } catch (Throwable) {}
        $pendingStart = null;
    }
}
if ($pendingStart !== null) {
    try {
        $startDt = new DateTimeImmutable($pendingStart);
        $dur = max(0, time() - $startDt->getTimestamp());
        $totalDownSec += $dur;
        $incidents[] = ['start' => $startDt->setTimezone($tz)->format('d/m/Y H:i:s'), 'end' => null, 'duration' => $dur, 'open' => true];
    } catch (Throwable) {}
}
$incidents = array_reverse($incidents);

function fmtDur(int $sec): string {
    if ($sec < 60)   return $sec . 's';
    if ($sec < 3600) return round($sec / 60) . ' min';
    $h = intdiv($sec, 3600); $m = intdiv($sec % 3600, 60);
    return $m > 0 ? "{$h}h {$m}min" : "{$h}h";
}

$geradoEm    = (new DateTimeImmutable('now', $tz))->format('d/m/Y H:i:s');
$totalInc    = count($incidents);
$totalDownFmt = $totalDownSec > 0 ? fmtDur($totalDownSec) : '0';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Relatorio de Falhas - <?= htmlspecialchars($ipRow['label']) ?> - <?= $days ?>d</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Arial, sans-serif; font-size: 11px; color: #1e293b; background: #fff; }
.print-bar { position: fixed; top: 0; left: 0; right: 0; background: #1e293b; color: #fff; display: flex; align-items: center; justify-content: space-between; padding: 10px 24px; gap: 12px; z-index: 999; }
.print-bar button { padding: 8px 20px; border-radius: 8px; border: none; cursor: pointer; font-weight: 700; font-size: 13px; }
.btn-pdf { background: #dc2626; color: #fff; }
.btn-close { background: rgba(255,255,255,.12); color: #fff; }
.content { margin-top: 52px; padding: 24px 28px; max-width: 900px; margin-left: auto; margin-right: auto; }
.report-header { border-bottom: 3px solid #dc2626; padding-bottom: 16px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: flex-end; flex-wrap: wrap; gap: 10px; }
.report-title { font-size: 20px; font-weight: 800; color: #0f172a; }
.report-sub { font-size: 12px; color: #64748b; margin-top: 4px; }
.report-meta { text-align: right; font-size: 10px; color: #94a3b8; line-height: 1.6; }
.stats { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
.stat-card { flex: 1; min-width: 130px; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 16px; text-align: center; }
.stat-value { font-size: 22px; font-weight: 900; }
.stat-label { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: #64748b; margin-top: 3px; }
.stat-green { color: #16a34a; border-color: #86efac; background: #f0fdf4; }
.stat-red { color: #dc2626; border-color: #fca5a5; background: #fef2f2; }
.stat-blue { color: #2563eb; border-color: #93c5fd; background: #eff6ff; }
.stat-gray { color: #475569; border-color: #e2e8f0; background: #f8fafc; }
.stat-amber { color: #92400e; border-color: #fde68a; background: #fffbeb; }
.section-title { font-size: 13px; font-weight: 800; color: #0f172a; margin-bottom: 10px; padding-bottom: 6px; border-bottom: 2px solid #f1f5f9; }
table { width: 100%; border-collapse: collapse; font-size: 10.5px; }
thead tr { background: #7f1d1d; color: #fff; }
thead th { padding: 9px 12px; text-align: left; font-weight: 700; font-size: 9px; text-transform: uppercase; letter-spacing: .06em; }
tbody tr:nth-child(even) { background: #fef9f9; }
tbody tr.open-row { background: #fff1f2; }
tbody td { padding: 7px 12px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
.badge { display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: 9px; font-weight: 700; text-transform: uppercase; }
.badge-closed { background: #dcfce7; color: #16a34a; }
.badge-open { background: #fee2e2; color: #dc2626; }
.badge-long { background: #fef3c7; color: #92400e; }
.no-incidents { text-align: center; padding: 40px 20px; color: #16a34a; font-size: 14px; font-weight: 700; background: #f0fdf4; border-radius: 10px; border: 1px solid #86efac; }
.report-footer { margin-top: 20px; padding-top: 12px; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; font-size: 9px; color: #94a3b8; }
@media print {
    .print-bar { display: none !important; }
    .content { margin-top: 0 !important; padding: 16px !important; }
    body { font-size: 10px; }
    table { page-break-inside: auto; }
    tr { page-break-inside: avoid; page-break-after: auto; }
    thead { display: table-header-group; }
    @page { margin: 15mm; size: A4; }
}
</style>
</head>
<body>
<div class="print-bar">
    <div style="font-size:13px;font-weight:700;">Relatorio de Falhas: <?= htmlspecialchars($ipRow['label']) ?> &middot; <?= $days ?> dias</div>
    <div style="display:flex;gap:8px;">
        <button class="btn-pdf" onclick="window.print()">Salvar como PDF / Imprimir</button>
        <button class="btn-close" onclick="window.close()">Fechar</button>
    </div>
</div>
<div class="content">
    <div class="report-header">
        <div>
            <div class="report-title">Relatorio de Falhas</div>
            <div class="report-sub">
                <strong><?= htmlspecialchars($ipRow['label']) ?></strong> &middot;
                <code style="background:#fff1f2;color:#dc2626;padding:2px 6px;border-radius:4px;font-size:11px;"><?= htmlspecialchars($ipRow['host']) ?></code>
                &middot; Periodo: ultimos <?= $days ?> dias
            </div>
        </div>
        <div class="report-meta">Gerado em: <?= $geradoEm ?><br>Fuso: <?= $tz->getName() ?><br>MonitorPing</div>
    </div>
    <div class="stats">
        <div class="stat-card <?= $uptimePct !== null && $uptimePct >= 99 ? 'stat-green' : 'stat-red' ?>">
            <div class="stat-value"><?= $uptimePct !== null ? $uptimePct . '%' : '&mdash;' ?></div>
            <div class="stat-label">Disponibilidade</div>
        </div>
        <div class="stat-card <?= $totalInc === 0 ? 'stat-green' : 'stat-red' ?>">
            <div class="stat-value"><?= $totalInc ?></div>
            <div class="stat-label">Incidentes</div>
        </div>
        <div class="stat-card <?= $totalDownSec === 0 ? 'stat-green' : 'stat-amber' ?>">
            <div class="stat-value" style="font-size:<?= strlen($totalDownFmt) > 5 ? '16px' : '22px' ?>;"><?= htmlspecialchars($totalDownFmt) ?></div>
            <div class="stat-label">Tempo Offline</div>
        </div>
        <div class="stat-card stat-gray">
            <div class="stat-value"><?= $totalChecks ?></div>
            <div class="stat-label">Checks no periodo</div>
        </div>
        <div class="stat-card stat-blue">
            <div class="stat-value"><?= $days ?>d</div>
            <div class="stat-label">Periodo analisado</div>
        </div>
    </div>
    <div class="section-title">Historico de Incidentes</div>
    <?php if (empty($incidents)): ?>
    <div class="no-incidents">Nenhum incidente registrado nos ultimos <?= $days ?> dias!</div>
    <?php else: ?>
    <table>
        <thead><tr><th>#</th><th>Inicio da Queda</th><th>Recuperacao</th><th>Duracao</th><th>Status</th></tr></thead>
        <tbody>
        <?php foreach ($incidents as $idx => $inc):
            $isOpen = $inc['open'];
            $isLong = !$isOpen && $inc['duration'] > 3600;
        ?>
        <tr class="<?= $isOpen ? 'open-row' : '' ?>">
            <td style="color:#94a3b8;font-size:9px;"><?= $totalInc - $idx ?></td>
            <td style="font-family:monospace;color:#dc2626;font-weight:700;"><?= htmlspecialchars($inc['start']) ?></td>
            <td style="font-family:monospace;color:<?= $isOpen ? '#dc2626' : '#16a34a' ?>;">
                <?= $isOpen ? '<em>Em andamento</em>' : htmlspecialchars($inc['end']) ?>
            </td>
            <td style="font-weight:700;color:<?= $isLong ? '#92400e' : ($isOpen ? '#dc2626' : '#475569') ?>;">
                <?= htmlspecialchars(fmtDur($inc['duration'])) ?><?= $isOpen ? ' (estimado)' : '' ?>
            </td>
            <td>
                <?php if ($isOpen): ?>
                    <span class="badge badge-open">Em andamento</span>
                <?php elseif ($isLong): ?>
                    <span class="badge badge-long">Queda longa</span>
                <?php else: ?>
                    <span class="badge badge-closed">Recuperado</span>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
    <div class="report-footer">
        <span>MonitorPing &middot; Relatorio de Falhas gerado em <?= $geradoEm ?></span>
        <span><?= $totalInc ?> incidente(s) &middot; <?= $days ?> dias &middot; <?= htmlspecialchars($ipRow['host']) ?></span>
    </div>
</div>
<script>window.addEventListener('load',function(){setTimeout(function(){window.print();},400);});</script>
</body>
</html>
PHPEOF;
    file_put_contents($pdfFile, $content);
    echo "OK: export_incidents_pdf.php criado\n";
}

// ── 2. Adiciona rota no index.php ────────────────────────────────────────────
$idx = '/var/www/html/index.php';
$ci  = file_get_contents($idx);

if (strpos($ci, 'export_incidents_pdf') !== false) {
    echo "SKIP: rota ja existe no index.php\n";
} else {
    $old = "    case 'export_logs':
        require __DIR__ . '/views/export_logs.php';
        break;";
    $new = "    case 'export_logs':
        require __DIR__ . '/views/export_logs.php';
        break;

    case 'export_incidents_pdf':
        require __DIR__ . '/views/export_incidents_pdf.php';
        break;";
    if (strpos($ci, $old) !== false) {
        file_put_contents($idx, str_replace($old, $new, $ci));
        echo "OK: rota adicionada no index.php\n";
    } else {
        echo "FAIL: ancora nao encontrada no index.php\n";
    }
}

// ── 3. Adiciona botao em user_ip_detail.php ──────────────────────────────────
$detail = '/var/www/html/views/user_ip_detail.php';
$cd     = file_get_contents($detail);

if (strpos($cd, 'export_incidents_pdf') !== false) {
    echo "SKIP: botao ja existe em user_ip_detail.php\n";
} else {
    $old2 = "        <a class=\"primary-button\" href=\"<?= BASE_URL ?>index.php?page=user_ip_form&id=<?= (int)\$ip['id'] ?>\">Gerenciar IP</a>
    </div>
</div>

<script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script>";

    $new2 = "        <!-- Exportar relatorio de falhas em PDF -->
        <form method=\"get\" action=\"<?= BASE_URL ?>index.php\" target=\"_blank\" style=\"display:flex; gap:6px; align-items:center;\">
            <input type=\"hidden\" name=\"page\" value=\"export_incidents_pdf\">
            <input type=\"hidden\" name=\"ip_id\" value=\"<?= (int)\$ip['id'] ?>\">
            <select name=\"days\" style=\"padding:7px 10px; border:1px solid #fca5a5; border-radius:8px; font-size:0.88rem; background:#fff1f2; cursor:pointer; color:#dc2626;\">
                <option value=\"7\">7 dias</option>
                <option value=\"30\" selected>30 dias</option>
                <option value=\"90\">90 dias</option>
            </select>
            <button type=\"submit\" style=\"background:#dc2626; color:#fff; border:none; padding:8px 16px; border-radius:8px; font-size:0.88rem; font-weight:700; cursor:pointer;\">
                Relatorio de Falhas (PDF)
            </button>
        </form>
        <a class=\"primary-button\" href=\"<?= BASE_URL ?>index.php?page=user_ip_form&id=<?= (int)\$ip['id'] ?>\">Gerenciar IP</a>
    </div>
</div>

<script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script>";

    if (strpos($cd, $old2) !== false) {
        file_put_contents($detail, str_replace($old2, $new2, $cd));
        echo "OK: botao adicionado em user_ip_detail.php\n";
    } else {
        // tentativa alternativa sem a linha do chart.js
        $old3 = "        <a class=\"primary-button\" href=\"<?= BASE_URL ?>index.php?page=user_ip_form&id=<?= (int)\$ip['id'] ?>\">Gerenciar IP</a>
    </div>
</div>";
        if (strpos($cd, $old3) !== false) {
            // conta ocorrencias
            $count = substr_count($cd, $old3);
            echo "WARN: ancora basica encontrada $count vez(es) - pode haver ambiguidade\n";
        } else {
            echo "FAIL: ancora nao encontrada em user_ip_detail.php\n";
            // debug: mostra trecho de Acoes
            $lines = explode("\n", $cd);
            foreach ($lines as $i => $line) {
                if (strpos($line, 'Gerenciar IP') !== false) {
                    echo "Linha " . ($i+1) . ": " . trim($line) . "\n";
                }
            }
        }
    }
}

echo "DONE\n";
