<?php
    function isRunningOnDomain(string $targetDomain): bool {
        // 1. Get the raw host from headers (e.g., "script.example.com:8080")
        $rawHost = $_SERVER['HTTP_HOST'] ?? '';

        // 2. Extract the hostname to strip ports.
        //    We prepend 'http://' to make sure parse_url works correctly on the string.
        $currentHost = parse_url('http://' . $rawHost, PHP_URL_HOST);

        // Safety check: if parse_url fails, fallback to raw string
        if ($currentHost === false || $currentHost === null) {
            $currentHost = $rawHost;
        }

        // 3. Normalize both to lowercase (domains are case-insensitive)
        $currentHost = strtolower($currentHost);
        $targetDomain = strtolower($targetDomain);

        // 4. Check for Exact Match (e.g., "example.com")
        if ($currentHost === $targetDomain) {
            return true;
        }

        // 5. Check for Subdomain Match (e.g., "script.example.com")
        //    We prepend a dot '.' to strictly enforce the subdomain boundary.
        //    This prevents "anotherexample.com" from matching "example.com".
        if (str_ends_with($currentHost, '.' . $targetDomain)) {
            return true;
        }

        return false;
    }

	$time_start = microtime(true);
	require('include/init.php');

	/*if (empty($_SESSION["first_visit"])) {
		$_SESSION["first_visit"] = time();
	}
	$_SESSION["fresh"] = false;*/

	$u = Login::getUser();

    # Cookie that randomly puts users to captcha
	if ($u && (in_array($u->id, ANNOYING_RETARDS))) {
        $randstring = hash("sha256", mt_rand(1,100000));
        setcookie("request_type", "ad5c0b2ddea5f7ff" . $randstring);
    }

	if ($_SESSION['session']->isNonLoggedinSodi()) {
	    $_SESSION['session']->unBan();
	   /* if ($_SESSION['user']->isBanned()) {
	        $_SESSION['user'] == Null;
	    }*/
	    if (!$u) {
	        Login::tryLogin(16, "recskaboy");
	    }
	}

	if (isset($_SESSION['user']) && $_SESSION['user']->id == 1371 && !isset($_SESSION['lastlogin'])) {
		unset($_SESSION['user']);
		unset($_SESSION['userId']);

	}
	$_SESSION['session']->setBans();
    if ($_SESSION['session']->isNonLoggedinSodi()) {
      //header("Location: https://szextarskereso.info/tmp/amator141067334.jpg");
      //die("<img src='https://szextarskereso.info/tmp/amator141067334.jpg'>");
    }

    if (isset($_SESSION['user']) && $_SESSION['user']->id == 16 && !isset($_SESSION['dkredirect'])) {
        #header("Location: https://forum.sodika.dk/include/sredirect.php?id=k16xrvzuilpxo7qba12el1iq", true, 302);
    } else if (isset($_SESSION['user']) && $_SESSION['user']->id == 7 && !isset($_SESSION['dkredirect'])) {
        #header("Location: https://forum.sodika.dk/include/sredirect.php?id=o7oxi23dn1ltige267720rdh", true, 302);
    }

    if (!isset($_SESSION['user']) && isRunningOnDomain('sodika.org')) {
        // 301 non-logged all in users, hopefully google too.
        $redirect_url = "https://forum.sodika.dk" . $_SERVER['REQUEST_URI'];

        while (ob_get_level()) {
            ob_end_clean();
        }

        header('Location: ' . $redirect_url, true, 301);

        // [CRITICAL for NGINX] Disable FastCGI Buffering
        // This forces Nginx to flush the response immediately even if PHP is still running.
        header('X-Accel-Buffering: no');

        // [CRITICAL for Cloudflare] Send Content-Length and Plain Text
        // Prevents Cloudflare from waiting for HTML body to inject scripts (Rocket Loader, etc.)
        header('Content-Type: text/plain');

        header('Content-Length: 0'); // Tell client the body is empty
        header('Connection: close'); // Tell client not to wait for more

        Application::logRetard();
        SESSION::SaveSession();

        die;
    }


	$template = new Template('index');
	echo $template->getContents();
	if (isset($_GET['debug']) && isset($_SESSION['user']) && $_SESSION['user']->isAdmin()) {
		//echo '<p>Total execution time in seconds: ' . round((microtime(true) - $time_start), 4) . '</p>';
		//echo Db::getInstance()->getConnection()->printLog();
	}
    //Application::logVisitor();
    Application::logRetard();
    SESSION::SaveSession();

