<?php
// Patch mikrotik_poller.php — adiciona id ao SELECT e registra eventos de queda
$f = "/var/www/html/mikrotik/mikrotik_poller.php";
$c = file_get_contents($f);

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

// Passo 1: adiciona id ao SELECT
$old1 = 'SELECT if_index, last_status, alert_on_down, alert_email, last_alert_sent_at, last_alert_status FROM nms_interfaces WHERE device_id = ?';
$new1 = 'SELECT id, if_index, last_status, alert_on_down, alert_email, last_alert_sent_at, last_alert_status FROM nms_interfaces WHERE device_id = ?';

if (strpos($c, $old1) !== false) {
    $c = str_replace($old1, $new1, $c);
    echo "SELECT OK\n";
} else {
    echo "FAIL SELECT\n"; exit;
}

// Passo 2: adiciona registro de eventos apos o UPDATE de alerta
$old2 = '                    $pdo->prepare("UPDATE nms_interfaces SET last_alert_sent_at=?, last_alert_status=? WHERE device_id=? AND if_index=?")
                        ->execute([$now, $newStatus, $deviceId, $ifIndex]);
                }
            }
        }
    }';

$new2 = '                    $pdo->prepare("UPDATE nms_interfaces SET last_alert_sent_at=?, last_alert_status=? WHERE device_id=? AND if_index=?")
                        ->execute([$now, $newStatus, $deviceId, $ifIndex]);
                    // Registra evento de queda/recuperacao
                    $ifId = isset($prev[\'id\']) ? (int)$prev[\'id\'] : null;
                    if ($ifId) {
                        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, $old2) !== false) {
    $c = str_replace($old2, $new2, $c);
    file_put_contents($f, $c);
    echo "EVENTS OK\n";
} else {
    echo "FAIL EVENTS — anchor not found\n";
}
