<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';

// CLI cron
if (php_sapi_name() === 'cli' && isset($argv[1]) && $argv[1] === 'cron') {
    require __DIR__ . '/ping_cron.php';
    exit;
}

// HTTP cron
if (isset($_GET['cron']) && $_GET['cron'] == '1') {
    $pdo = db();
    // Limite de bruteforce cron token: max 10 erros em 5 minutos (300s)
    if (!empty(CRON_HTTP_TOKEN) && ($_GET['cron_token'] ?? '') !== CRON_HTTP_TOKEN) {
        if (!check_rate_limit_ip($pdo, 'cron_token', 10, 300)) {
            http_response_code(429);
            echo "Accesso bloqueado temporariamente pelo Anti-Brute-Force.";
            exit;
        }
        http_response_code(403);
        echo "Token invalido.";
        exit;
    }
    // Sucesso, libera IP se estivesse bloqueado
    clear_rate_limit_ip($pdo, 'cron_token');
    
    require __DIR__ . '/ping_cron.php';
    exit;
}

$page = $_GET['page'] ?? 'home';

if ($page === 'login') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        
        $pdo = db();
        // Limite de login: max 5 tentativas erradas em 10 minutos (600s)
        if (!check_rate_limit_ip($pdo, 'login_attempt', 5, 600)) {
            $error = "Muitas tentativas falhas. Bloqueado por medida de segurança. Tente novamente em alguns minutos.";
        } else {
            if (login($email, $password)) {
                clear_rate_limit_ip($pdo, 'login_attempt');
                redirect('index.php?page=dashboard');
            } else {
                $error = "Login invalido.";
            }
        }
    }
    require __DIR__ . '/views/login.php';
    exit;
}

if ($page === 'register') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!$name || !$email || !$password) {
            $error = "Preencha todos os campos.";
        } else {
            $pdo = db();
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetchColumn() > 0) {
                $error = "E-mail ja cadastrado.";
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, role) VALUES (?, ?, ?, 'user')");
                $stmt->execute([$name, $email, $hash]);
                $user_id = (int)$pdo->lastInsertId();

                $stmt = $pdo->prepare("SELECT id FROM plans WHERE name = 'Free' LIMIT 1");
                $stmt->execute();
                $plan = $stmt->fetch();
                if ($plan) {
                    $stmt2 = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id) VALUES (?, ?)");
                    $stmt2->execute([$user_id, $plan['id']]);
                }

                login($email, $password);
                redirect('index.php?page=dashboard');
            }
        }
    }
    require __DIR__ . '/views/register.php';
    exit;
}

if ($page === 'logout') {
    logout();
    redirect('index.php?page=login');
}

require_login();
$user = current_user();

switch ($page) {
    case 'home':
    case 'dashboard':
        require __DIR__ . '/views/user_dashboard.php';
        break;

    case 'user_ips':
        $pdo = db();
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_ip') {
            if (!csrf_check($_POST['csrf_token'] ?? null)) {
                http_response_code(403);
                exit('CSRF invalido.');
            }
            $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM monitored_ips WHERE id = ? AND user_id = ?");
                $stmt->execute([$id, $user['id']]);
            }
            redirect('index.php?page=user_ips');
        }
        require __DIR__ . '/views/user_ips.php';
        break;

    case 'api_dashboard':
        require __DIR__ . '/views/api_dashboard.php';
        break;

    case 'api_toggle_ip':
        require __DIR__ . '/views/api_toggle_ip.php';
        break;

    case 'user_ip_form':
        $pdo = db();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $label = trim($_POST['label'] ?? '');
            $hostInput = trim($_POST['host'] ?? '');
            $interval_seconds = (int)($_POST['interval_seconds'] ?? 60);
            $timeout_ms = (int)($_POST['timeout_ms'] ?? 1000);
            $alert_email = trim($_POST['alert_email'] ?? '');
            $channelsInput = $_POST['channels'] ?? [];
            $check_method = strtolower(trim($_POST['check_method'] ?? 'auto'));
            $check_port_raw = trim($_POST['check_port'] ?? '');

            if (!csrf_check($_POST['csrf_token'] ?? null)) {
                $error = "CSRF invalido.";
            }

            if (!in_array($check_method, ['auto', 'icmp', 'tcp'], true)) {
                $check_method = 'auto';
            }

            $hostParts = split_host_and_port($hostInput);
            $host = $hostParts['host'];
            $hostPort = $hostParts['port'];

            $check_port = null;
            if ($check_port_raw !== '') {
                if (!ctype_digit($check_port_raw)) {
                    if (empty($error)) {
                        $error = "Porta invalida.";
                    }
                } else {
                    $check_port = (int)$check_port_raw;
                }
            }
            if (empty($error) && $check_port !== null && ($check_port < 1 || $check_port > 65535)) {
                $error = "Porta invalida.";
            }
            if (empty($error) && $check_port !== null && $hostPort !== null && $check_port !== $hostPort) {
                $error = "Porta em conflito com host:porta.";
            }
            if ($check_port === null && $hostPort !== null) {
                $check_port = $hostPort;
            }
            if (empty($error) && $check_method === 'tcp' && $check_port === null) {
                $error = "Informe a porta TCP.";
            }
            if ($check_method === 'icmp') {
                $check_port = null;
            }

            $hostToSave = $host;
            if ($check_port !== null && $check_method !== 'icmp') {
                $hostToSave = $host . ':' . $check_port;
            }

            $hasCheckMethod = ensure_monitored_ips_check_method($pdo);

            $plan = get_user_plan($user['id']);
            $min_interval = (int)$plan['min_interval_seconds'];
            $max_ips = (int)$plan['max_ips'];

            if (empty($error)) {
                if ($interval_seconds < $min_interval) {
                    $error = "Intervalo minimo de {$min_interval} segundos.";
                } elseif (!validate_monitor_host($host, $hostError)) {
                    $error = $hostError;
                } else {
                    $current = count_user_ips($user['id']);
                    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

                    if (!$id && $current >= $max_ips) {
                        $error = "Voce atingiu o limite de IPs do seu plano ({$max_ips}).";
                    } elseif (!$label || !$host) {
                        $error = "Preencha todos os campos obrigatorios.";
                    } else {
                    if ($id) {
                        if ($hasCheckMethod) {
                            $stmt = $pdo->prepare("UPDATE monitored_ips SET label=?, host=?, interval_seconds=?, timeout_ms=?, alert_email=?, check_method=? WHERE id=? AND user_id=?");
                            $stmt->execute([$label, $hostToSave, $interval_seconds, $timeout_ms, $alert_email ?: null, $check_method, $id, $user['id']]);
                        } else {
                            $stmt = $pdo->prepare("UPDATE monitored_ips SET label=?, host=?, interval_seconds=?, timeout_ms=?, alert_email=? WHERE id=? AND user_id=?");
                            $stmt->execute([$label, $hostToSave, $interval_seconds, $timeout_ms, $alert_email ?: null, $id, $user['id']]);
                        }
                        $ipId = $id;
                    } else {
                        if ($hasCheckMethod) {
                            $stmt = $pdo->prepare("INSERT INTO monitored_ips (user_id, label, host, interval_seconds, timeout_ms, alert_email, check_method) VALUES (?, ?, ?, ?, ?, ?, ?)");
                            $stmt->execute([$user['id'], $label, $hostToSave, $interval_seconds, $timeout_ms, $alert_email ?: null, $check_method]);
                        } else {
                            $stmt = $pdo->prepare("INSERT INTO monitored_ips (user_id, label, host, interval_seconds, timeout_ms, alert_email) VALUES (?, ?, ?, ?, ?, ?)");
                            $stmt->execute([$user['id'], $label, $hostToSave, $interval_seconds, $timeout_ms, $alert_email ?: null]);
                        }
                        $ipId = (int)$pdo->lastInsertId();
                    }
                        sync_alert_channels($ipId, is_array($channelsInput) ? $channelsInput : [], $alert_email ?: null);

                        // Realiza um ping imediato ao salvar para ja popular status/latencia
                        $ping = ping_host($hostToSave, $timeout_ms, $check_method);
                        $status = $ping['status'];
                        $latency = $ping['latency_ms'];
                        $pdo->prepare("
                            UPDATE monitored_ips
                            SET last_status = ?, last_latency_ms = ?, last_check_at = NOW()
                            WHERE id = ? AND user_id = ?
                        ")->execute([$status, $latency, $ipId, $user['id']]);
                        $pdo->prepare("
                            INSERT INTO ping_logs (monitored_ip_id, status, latency_ms, checked_at)
                            VALUES (?, ?, ?, NOW())
                        ")->execute([$ipId, $status, $latency]);

                        redirect('index.php?page=user_ips');
                    }
                }
            }
        }
        require __DIR__ . '/views/user_ip_form.php';
        break;

    case 'user_logs':
        require __DIR__ . '/views/user_logs.php';
        break;

    case 'user_ip_detail':
        require __DIR__ . '/views/user_ip_detail.php';
        break;

    case 'admin_dashboard':
        require_admin();
        require __DIR__ . '/views/admin_dashboard.php';
        break;

    case 'admin_users':
        require_admin();
        require __DIR__ . '/views/admin_users.php';
        break;

    case 'admin_plans':
        require_admin();
        require __DIR__ . '/views/admin_plans.php';
        break;

    case 'admin_ips':
        require_admin();
        require __DIR__ . '/views/admin_ips.php';
        break;

    case 'admin_logs':
        require_admin();
        require __DIR__ . '/views/admin_logs.php';
        break;

    case 'admin_settings':
        require_admin();
        require __DIR__ . '/views/admin_settings.php';
        break;

    case 'status_page':
        require __DIR__ . '/views/status_page.php';
        break;

    default:
        http_response_code(404);
        require __DIR__ . '/includes/header.php';
        echo "<div class='card'><h2>Pagina nao encontrada</h2></div>";
        require __DIR__ . '/includes/footer.php';
        break;
}
