<?php
defined('ABSPATH') || exit;

// Include our new logger class
require_once dirname(__FILE__) . '/class-wpsec-logger.php';

function wpsec_log_results($infected_files, $scanned_count, $scan_duration) {
    $upload_dir = wp_upload_dir();
    $log_dir = $upload_dir['basedir'] . '/wpsec-scan-results/';
    
    // Create directory with proper permissions if it doesn't exist
    if (!file_exists($log_dir)) {
        wp_mkdir_p($log_dir);
        // Add an empty index.php file for security
        file_put_contents($log_dir . 'index.php', '<?php // Silence is golden');
    }
    
    $log_path = $log_dir . 'scan_results_' . gmdate('Y-m-d_H-i-s') . '.json';
    $latest_log_path = $log_dir . 'latest_scan_results.json';
    
    $log_data = [
        'timestamp' => gmdate('Y-m-d H:i:s'),
        'scan_duration' => $scan_duration,
        'total_files_scanned' => $scanned_count,
        'infected_count' => count($infected_files),
        'infected_files' => $infected_files
    ];
    
    // Save detailed log
    if (file_put_contents($log_path, json_encode($log_data, JSON_PRETTY_PRINT)) === false) {
        wpsec_debug_log('❌ ERROR: Failed to write detailed scan results to ' . $log_path, 'error');
    } else {
        wpsec_debug_log('✅ Detailed scan results saved to: ' . $log_path, 'info');
        
        // Also save as latest results
        if (file_put_contents($latest_log_path, json_encode($log_data, JSON_PRETTY_PRINT)) === false) {
            wpsec_debug_log('❌ ERROR: Failed to write latest scan results', 'error');
        }
        
        // Keep only the latest 10 scan results
        wpsec_cleanup_old_logs($log_dir);
    }
}

function wpsec_cleanup_old_logs($log_dir) {
    $files = glob($log_dir . 'scan_results_*.json');
    
    if (count($files) <= 10) {
        return;
    }
    
    // Sort by filename (which includes the date/time)
    usort($files, function($a, $b) {
        return strcmp($b, $a); // Descending order
    });
    
    // Delete all but the 10 newest files
    $files_to_delete = array_slice($files, 10);
    foreach ($files_to_delete as $file) {
        @wp_delete_file($file);
    }
}

function wpsec_get_log_results() {
    $upload_dir = wp_upload_dir();
    $latest_log_path = $upload_dir['basedir'] . '/wpsec-scan-results/latest_scan_results.json';
    
    if (file_exists($latest_log_path)) {
        $content = file_get_contents($latest_log_path);
        $data = json_decode($content, true);
        
        if ($data) {
            return $data;
        }
    }
    
    return [
        'timestamp' => 'Never',
        'total_files_scanned' => 0,
        'infected_count' => 0,
        'infected_files' => [],
        'error' => 'No scan results found'
    ];
}