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

/**
 * Endpoint to get detailed scan error information
 * This provides a comprehensive view of any errors that occurred during scans
 */
function wpsec_scan_errors_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 scan ID from request or use latest scan
    $scan_id = isset($request['scan_id']) ? $request['scan_id'] : get_option('wpsec_current_scan_id');
    
    if (!$scan_id) {
        return rest_ensure_response([
            'status' => 'error',
            'message' => 'No scan ID provided and no recent scan found'
        ]);
    }
    
    // Get scan status and basic info
    $status = get_option('wpsec_scan_' . $scan_id . '_status', 'unknown');
    $error_message = get_option('wpsec_scan_' . $scan_id . '_error', '');
    $progress = get_option('wpsec_scan_' . $scan_id . '_progress', 0);
    $start_time = get_option('wpsec_scan_' . $scan_id . '_start', 0);
    $end_time = get_option('wpsec_scan_' . $scan_id . '_end', 0);
    
    // Get detailed error information
    $critical_error_json = get_option('wpsec_scan_' . $scan_id . '_critical_error', '{}');
    $file_errors_json = get_option('wpsec_scan_' . $scan_id . '_file_errors', '[]');
    
    // Parse JSON data
    $critical_error = json_decode($critical_error_json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $critical_error = [];
    }
    
    $file_errors = json_decode($file_errors_json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $file_errors = [];
    }
    
    // Get the last scanned file
    $last_scanned_file = get_option('wpsec_scan_' . $scan_id . '_last_scanned_file', '');
    
    // Build response with all error information
    $response = [
        'scan_id' => $scan_id,
        'status' => $status,
        'error_message' => $error_message,
        'progress' => $progress,
        'started_at' => $start_time ? gmdate('Y-m-d H:i:s', $start_time) : null,
        'ended_at' => $end_time ? gmdate('Y-m-d H:i:s', $end_time) : null,
        'last_scanned_file' => $last_scanned_file,
        'has_critical_error' => !empty($critical_error),
        'critical_error' => $critical_error,
        'file_errors' => $file_errors,
        'file_error_count' => count($file_errors)
    ];
    
    return rest_ensure_response($response);
}

// Register the endpoint
add_action('rest_api_init', function () {
    register_rest_route('wpsec/v1', '/scan-errors(?:/(?P<scan_id>[^/]+))?', [
        'methods' => 'GET',
        'callback' => 'wpsec_scan_errors_endpoint',
        'permission_callback' => '__return_true',
        'args' => [
            'scan_id' => [
                'required' => false,
                'validate_callback' => function($param) {
                    return is_string($param);
                }
            ]
        ]
    ]);
});
