<?php
/**
 * MikroTik NMS — Entry Point
 * Acesse via: index.php?page=nms ou /mikrotik/index.php?page=...
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

// URL base absoluta do módulo NMS — garante links corretos independente de onde a view é chamada
define('NMS_URL', BASE_URL . 'mikrotik/index.php');

require_login();
$user = current_user();
$page = $_GET['page'] ?? 'nms_dashboard';

switch ($page) {

    case 'nms_dashboard':
        require __DIR__ . '/views/dashboard.php';
        break;

    case 'nms_devices':
        $pdo = db();
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_device') {
            if (!csrf_check($_POST['csrf_token'] ?? null)) { http_response_code(403); exit('CSRF inválido.'); }
            $id = (int)($_POST['id'] ?? 0);
            if ($id) {
                $pdo->prepare("DELETE FROM nms_devices WHERE id = ? AND user_id = ?")->execute([$id, $user['id']]);
            }
            header('Location: index.php?page=nms_devices'); exit;
        }
        require __DIR__ . '/views/devices.php';
        break;

    case 'nms_device_form':
        $pdo = db();
        require __DIR__ . '/views/device_form.php';
        break;

    case 'nms_device_detail':
        $pdo = db();
        require __DIR__ . '/views/device_detail.php';
        break;

    case 'nms_interface_dashboard':
        $pdo = db();
        require __DIR__ . '/views/interface_dashboard.php';
        break;

    case 'nms_pppoe':
        $pdo = db();
        require __DIR__ . '/views/pppoe_clients.php';
        break;

    case 'nms_alerts':
        $pdo = db();
        require __DIR__ . '/views/alerts.php';
        break;

    case 'nms_map':
        $pdo = db();
        require __DIR__ . '/views/map.php';
        break;

    case 'nms_api_realtime':
        require __DIR__ . '/views/api/realtime.php';
        break;

    case 'nms_api_history':
        require __DIR__ . '/views/api/history.php';
        break;

    case 'nms_api_map':
        require __DIR__ . '/views/api/map_devices.php';
        break;

    default:
        http_response_code(404);
        require __DIR__ . '/../includes/header.php';
        echo "<div class='card'><h2>Página NMS não encontrada</h2></div>";
        require __DIR__ . '/../includes/footer.php';
        break;
}
