<?php
/**
 * Ubiquiti NMS — Entry Point
 * Acesse via: ubiquiti/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';

define('UBNT_URL', BASE_URL . 'ubiquiti/index.php');

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

switch ($page) {

    case 'ubnt_panels':
        $pdo = db();
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_panel') {
            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 ubiquiti_panels WHERE id = ? AND user_id = ?")->execute([$id, $user['id']]);
            }
            header('Location: ' . UBNT_URL . '?page=ubnt_panels'); exit;
        }
        require __DIR__ . '/views/panels.php';
        break;

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

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

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

    case 'ubnt_api_panels':
        require __DIR__ . '/views/api/panels_json.php';
        break;

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