<?php
// Developer eonbry

// Impede que erros apareçam na tela e quebrem o JSON, mas você pode ver no error_log se precisar
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(E_ALL);

$ipl = real_ip();

// Adicionado @ para evitar erro fatal se o ipinfo.io bloquear a requisição por limite de acessos
$ip_data = @file_get_contents("https://ipinfo.io/" . $ipl . "/json");
$details = $ip_data ? json_decode($ip_data) : null;

// Proteção com fallback (?? 'Unknown') caso a API não retorne os dados
$country = $details->country ?? 'Unknown';
$state   = $details->region ?? 'Unknown';
$city    = $details->city ?? 'Unknown';
$isp_raw = $details->org ?? 'Unknown';
$isp     = $isp_raw !== 'Unknown' ? preg_replace("/AS\\d{1,}\\s/", "", $isp_raw) : 'Unknown';
$loc     = $details->loc ?? 'Unknown';

// Correção: Verificar se "m" existe antes de chamar
if (isset($_REQUEST["m"]) && $_REQUEST["m"]) {
    $started = microtime(true);
    
    // Tratamento de erro na conexão com banco
    try {
        $db = new SQLite3("./.ansdb.db");
    } catch (Exception $e) {
        die(json_encode(["error" => "Database connection failed"]));
    }

    $api = [];
    $res = $db->query("SELECT * FROM theme");
    if ($res) {
        while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
            $api[] = ["name" => $row["name"], "url" => $row["url"]];
        }
    }
    $new = json_encode($api);
    $new = str_replace("\\/", "/", $new);
    
    $api2 = [];
    $res2 = $db->query("SELECT * FROM advert");
    if ($res2) {
        while ($row2 = $res2->fetchArray(SQLITE3_ASSOC)) {
            $api2[] = ["title" => $row2["title"], "description" => $row2["description"], "url" => $row2["url"]];
        }
    }
    
    // Correção na verificação de vazio
    if (empty($api2)) {
        $new2 = "[{\"title\":\"MUG IBO IPTV\",\"description\":\"Best Media Player in the world.\",\"url\":\"https://flixapp.org/public/upload/1604854505.png\"}]";
    } else {
        $new2 = json_encode($api2);
        $new2 = str_replace("\\/", "/", $new2);
    }
    
    $end = microtime(true);
    $difference = $end - $started;
    $queryTime = number_format($difference, 16);
    
    echo "{\"themes\":" . $new . ",\r\n\"adverts\":" . $new2 . ",\"app_type\":\"android\",\"use_agent\":\"mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/88.0.4324.104 safari/537.36\",\"total_execution_time\":" . $queryTime . "}";
} else {
    // HTML de Acesso Negado
    ?>
    <style>
    @import "https://fonts.googleapis.com/css?family=Share+Tech+Mono|Montserrat:700";*{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;box-sizing:border-box;color:inherit}body{background-image:radial-gradient(black 40%,#000954 99%);height:100vh}div{background:rgba(0,0,0,0);width:70vw;position:relative;top:50%;transform:translateY(-50%);margin:0 auto;padding:30px 30px 10px;box-shadow:0 0 150px -20px rgba(0,0,0,0.5);z-index:3}P{font-family:"Share Tech Mono",monospace;color:#f5f5f5;margin:0 0 20px;font-size:17px;line-height:1.2}span{color:#F0DA00}i{color:#36FE00}div a{text-decoration:none}b{color:#81a2be}a{color:#FF2D00}@keyframes slide{from{right:-100px;transform:rotate(360deg);opacity:0}to{right:15px;transform:rotate(0deg);opacity:1}}
    </style>

    <div>
    <p><span></span><a>Access Denied. You Do Not Have The Permission To Access This Page On This Server</a></p>
    <p>$ <span>Time Of Arrival</span>: "<i><?php echo date("d-m-Y H:i:s"); ?></i>"</p>
    <p>>>>> <span>IP Address</span>: <i><?php echo real_ip(); ?></i></p>
    <p>>>>> <span>Country</span>: <i><?php echo htmlspecialchars($country); ?></i></p>
    <p>>>>> <span>State</span>: <i><?php echo htmlspecialchars($state); ?></i></p>
    <p>>>>> <span>City</span>: <i><?php echo htmlspecialchars($city); ?></i></p>
    <p>>>>> <span>Location</span>: <i><?php echo htmlspecialchars($loc); ?></i></p>
    <p>>>>> <span>ISP</span>: <i><?php echo htmlspecialchars($isp); ?></i></p>
    <p>>>>> <span>Operating System</span>: <i><?php echo htmlspecialchars(get_os()); ?></i></p>
    <p>>>>> <span>Browser</span>: <i><?php echo htmlspecialchars(Browser_type()); ?></i></p>
    <p>>>>> <span>Device</span>: <i><?php echo htmlspecialchars(get_device()); ?></i></p>
    <p>>>>> <span>Tor Browser</span>: <i><?php echo htmlspecialchars(IsTorExitPoint()); ?></i></p>
    <p>>>>> <span>@admin</span>:  <i>Logging Session And Recording Ip:</i> <j> " Completed . . . "</j></p>
    <p>>>>> <span>@admin</span>:  <i>Preparing to DDos Recorded Ip:</i> <j>" Successful . . . "</j></p>
    <p>>>>> <span>@admin</span>:  <j>" </j><a>!!! You Will Be Blacklisted Shortly.... !!!</a><j> "</j></p>
    </div>
            
    <script>
    var str = document.getElementsByTagName('div')[0].innerHTML.toString();
    var i = 0;
    document.getElementsByTagName('div')[0].innerHTML = "";

    setTimeout(function() {
        var se = setInterval(function() {
            i++;
            document.getElementsByTagName('div')[0].innerHTML = str.slice(0, i) + "|";
            if (i == str.length) {
                clearInterval(se);
                document.getElementsByTagName('div')[0].innerHTML = str;
            }
        }, 10);
    },0);
    </script>
    <?php
}

function real_ip() {
    $ip = "undefined";
    if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (isset($_SERVER["REMOTE_ADDR"])) {
        $ip = $_SERVER["REMOTE_ADDR"];
    }
    return htmlspecialchars($ip, ENT_QUOTES, "UTF-8");
}

function get_os() {
    $user_agent = $_SERVER["HTTP_USER_AGENT"] ?? '';
    $os_platform = "Unknown OS Platform";
    $os_array = ["/windows nt 10/i" => "Windows 10", "/windows nt 6.3/i" => "Windows 8.1", "/windows nt 6.2/i" => "Windows 8", "/windows nt 6.1/i" => "Windows 7", "/windows nt 6.0/i" => "Windows Vista", "/windows nt 5.2/i" => "Windows Server 2003/XP x64", "/windows nt 5.1/i" => "Windows XP", "/windows xp/i" => "Windows XP", "/windows nt 5.0/i" => "Windows 2000", "/windows me/i" => "Windows ME", "/win98/i" => "Windows 98", "/win95/i" => "Windows 95", "/win16/i" => "Windows 3.11", "/macintosh|mac os x/i" => "Mac OS X", "/mac_powerpc/i" => "Mac OS 9", "/linux/i" => "Linux", "/ubuntu/i" => "Ubuntu", "/iphone/i" => "iPhone", "/ipod/i" => "iPod", "/ipad/i" => "iPad", "/android/i" => "Android", "/blackberry/i" => "BlackBerry", "/webos/i" => "Mobile"];
    
    foreach ($os_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $os_platform = $value;
        }
    }
    return $os_platform;
}

function Browser_type() {
    $user_agent = $_SERVER["HTTP_USER_AGENT"] ?? '';
    $browser = "Unknown Browser";
    $browser_array = ["/msie/i" => "Internet Explorer", "/Trident/i" => "Internet Explorer", "/firefox/i" => "Firefox", "/safari/i" => "Safari", "/chrome/i" => "Chrome", "/edge/i" => "Edge", "/opera/i" => "Opera", "/netscape/i" => "Netscape", "/maxthon/i" => "Maxthon", "/konqueror/i" => "Konqueror", "/ubrowser/i" => "UC Browser", "/mobile/i" => "Handheld Browser"];
    
    foreach ($browser_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $browser = $value;
        }
    }
    return $browser;
}

function get_device() {
    $user_agent = strtolower($_SERVER["HTTP_USER_AGENT"] ?? '');
    $http_accept = strtolower($_SERVER["HTTP_ACCEPT"] ?? '');
    $tablet_browser = 0;
    $mobile_browser = 0;
    
    if (preg_match("/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i", $user_agent)) {
        $tablet_browser++;
    }
    if (preg_match("/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i", $user_agent)) {
        $mobile_browser++;
    }
    if (strpos($http_accept, "application/vnd.wap.xhtml+xml") > 0 || isset($_SERVER["HTTP_X_WAP_PROFILE"]) || isset($_SERVER["HTTP_PROFILE"])) {
        $mobile_browser++;
    }
    
    $mobile_ua = substr($user_agent, 0, 4);
    $mobile_agents = ["w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-", "newt", "noki", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda ", "xda-"];
    
    if (in_array($mobile_ua, $mobile_agents)) {
        $mobile_browser++;
    }
    
    if (strpos($user_agent, "opera mini") > 0) {
        $mobile_browser++;
        $stock_ua = strtolower($_SERVER["HTTP_X_OPERAMINI_PHONE_UA"] ?? ($_SERVER["HTTP_DEVICE_STOCK_UA"] ?? ""));
        if (preg_match("/(tablet|ipad|playbook)|(android(?!.*mobile))/i", $stock_ua)) {
            $tablet_browser++;
        }
    }
    
    if ($tablet_browser > 0) {
        return "Tablet";
    }
    if ($mobile_browser > 0) {
        return "Mobile";
    }
    return "Computer";
}

function IsTorExitPoint() {
    if (!isset($_SERVER["REMOTE_ADDR"]) || !isset($_SERVER["SERVER_PORT"]) || !isset($_SERVER["SERVER_ADDR"])) {
        return "False";
    }
    $reverse_ip = ReverseIPOctets($_SERVER["REMOTE_ADDR"]);
    $reverse_server_ip = ReverseIPOctets($_SERVER["SERVER_ADDR"]);
    
    if (gethostbyname($reverse_ip . "." . $_SERVER["SERVER_PORT"] . "." . $reverse_server_ip . ".ip-port.exitlist.torproject.org") == "127.0.0.2") {
        return "True";
    }
    return "False";
}

function ReverseIPOctets($inputip) {
    $ipoc = explode(".", $inputip);
    if (count($ipoc) === 4) {
        return $ipoc[3] . "." . $ipoc[2] . "." . $ipoc[1] . "." . $ipoc[0];
    }
    return $inputip;
}
?>