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

function wpsec_results_endpoint($request) {
    // Validate API key
    if (!wpsec_validate_api_key()) {
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get the latest scan ID
    $scan_id = get_option('wpsec_current_scan_id');
    if (!$scan_id) {
        return rest_ensure_response([
            'status' => 'error',
            'message' => 'No scan has been performed yet'
        ]);
    }

    // Get scan results
    $status = get_option('wpsec_scan_' . $scan_id . '_status', 'unknown');
    $start_time = get_option('wpsec_scan_' . $scan_id . '_start', 0);
    $end_time = get_option('wpsec_scan_' . $scan_id . '_end', 0);
    $duration = get_option('wpsec_scan_' . $scan_id . '_duration', 0);
    $files_scanned = get_option('wpsec_scan_' . $scan_id . '_files_scanned', 0);
    $infected_files_json = get_option('wpsec_scan_' . $scan_id . '_infected_files', '[]');
    $infected_count = get_option('wpsec_scan_' . $scan_id . '_infected_count', 0);

    // Decode infected files from JSON
    $infected_files = json_decode($infected_files_json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wpsec_debug_log(' Error decoding infected files JSON: ' . json_last_error_msg(), 'error');
        $infected_files = [];
    }

    // Add file info for each infected file
    foreach ($infected_files as &$file) {
        if (isset($file['file']) && file_exists($file['file'])) {
            $file['size'] = filesize($file['file']);
            $file['modified'] = gmdate('Y-m-d H:i:s', filemtime($file['file']));
            $file['relative_path'] = str_replace(ABSPATH, '', $file['file']);
        }
    }

    $response = [
        'status' => $status,
        'scan_id' => $scan_id,
        'started_at' => gmdate('Y-m-d H:i:s', $start_time),
        'infected_files' => $infected_files,
        'total_files_scanned' => $files_scanned,
        'infected_count' => $infected_count,
        'completed_at' => $end_time ? gmdate('Y-m-d H:i:s', $end_time) : null,
        'duration' => $duration
    ];

    return rest_ensure_response($response);
}
