<?php
// Patch snmp_poller.php — adiciona registro de eventos de queda
$f = "/var/www/html/mikrotik/snmp_poller.php";
$c = file_get_contents($f);

if (strpos($c, 'nms_interface_events') !== false) { echo "SKIP\n"; exit; }

$old = '                $pdo->prepare("UPDATE nms_interfaces SET last_alert_sent_at=?, last_alert_status=? WHERE id=?")
                    ->execute([$now, $newStatus, $ifId]);
            }
        }
    }
}';

$new = '                $pdo->prepare("UPDATE nms_interfaces SET last_alert_sent_at=?, last_alert_status=? WHERE id=?")
                    ->execute([$now, $newStatus, $ifId]);
                // Registra evento de queda/recuperacao
                if ($newStatus === \'down\') {
                    $pdo->prepare("INSERT INTO nms_interface_events (interface_id, started_at, alert_sent) VALUES (?, ?, TRUE)")
                        ->execute([$ifId, $now]);
                } elseif ($newStatus === \'up\') {
                    $pdo->prepare("
                        UPDATE nms_interface_events
                        SET recovered_at = ?, duration_seconds = EXTRACT(EPOCH FROM (?::timestamptz - started_at))::INT
                        WHERE id = (
                            SELECT id FROM nms_interface_events
                            WHERE interface_id = ? AND recovered_at IS NULL
                            ORDER BY started_at DESC LIMIT 1
                        )
                    ")->execute([$now, $now, $ifId]);
                }
            }
        }
    }
}';

if (strpos($c, $old) !== false) {
    file_put_contents($f, str_replace($old, $new, $c));
    echo "OK\n";
} else {
    echo "FAIL — anchor not found\n";
}
