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

/**
 * Reset a scan and its associated data
 *
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response|WP_Error The response
 */
function wpsec_reset_scan_endpoint($request) {
    // Debug logging
    wpsec_debug_log('WPFort Debug - Scan reset endpoint called', 'debug');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_debug_log('WPFort Debug - API key validation failed', 'debug');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Check if we should clear all non-completed scans
    if (isset($request['clear_all']) && $request['clear_all']) {
        wpsec_debug_log('WPFort Debug - Clear all non-completed scans requested', 'debug');
        $reset_results = wpsec_reset_all_non_completed_scans();
        return rest_ensure_response($reset_results);
    }

    $scan_id = $request['scan_id'];
    
    // Validate scan ID format
    if (!preg_match('/^wpsec_[a-f0-9]+\.[0-9]+$/', $scan_id)) {
        wpsec_debug_log('WPFort Debug - Invalid scan ID format: ' . $scan_id, 'debug');
        return new WP_Error(
            'rest_invalid_param',
            'Invalid scan ID format',
            array('status' => 400)
        );
    }
    
    // Reset the scan
    $reset_result = wpsec_reset_scan($scan_id);
    
    if ($reset_result) {
        return rest_ensure_response([
            'success' => true,
            'message' => 'Scan reset successfully',
            'scan_id' => $scan_id
        ]);
    } else {
        return rest_ensure_response([
            'success' => false,
            'message' => 'Failed to reset scan',
            'scan_id' => $scan_id
        ]);
    }
}

/**
 * Reset all non-completed scans
 * 
 * This resets all scans that are in a non-completed state like 'scanning', 'running', 
 * 'paused', 'resuming', etc.
 * 
 * @return array Results with count of scans reset
 */
function wpsec_reset_all_non_completed_scans() {
    global $wpdb;

    $reset_count = 0;
    $failed_count = 0;
    $non_completed_statuses = ['scanning', 'running', 'paused', 'resuming'];
    
    // Find all non-completed scans
    $option_pattern = $wpdb->esc_like('wpsec_scan_') . '%' . $wpdb->esc_like('_status');
    
    $options = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
            $option_pattern
        )
    );
    $reset_scans = array();
    
    if (!empty($options)) {
        foreach ($options as $option) {
            // Extract scan ID from option name
            $scan_id = str_replace(['wpsec_scan_', '_status'], '', $option->option_name);
            $status = $option->option_value;
            
            // Only reset non-completed scans
            if (in_array($status, $non_completed_statuses)) {
                wpsec_debug_log('WPFort Debug - Resetting non-completed scan: ' . $scan_id . ' with status: ' . $status, 'debug');
                
                $reset_result = wpsec_reset_scan($scan_id);
                if ($reset_result) {
                    $reset_count++;
                    $reset_scans[] = [
                        'scan_id' => $scan_id,
                        'status' => $status,
                        'reset' => true
                    ];
                } else {
                    $failed_count++;
                    $reset_scans[] = [
                        'scan_id' => $scan_id,
                        'status' => $status,
                        'reset' => false
                    ];
                }
            }
        }
    }
    
    return [
        'success' => true,
        'message' => 'Reset operation completed',
        'reset_count' => $reset_count,
        'failed_count' => $failed_count,
        'scans' => $reset_scans
    ];
}

/**
 * Register the scan reset endpoint
 */
function wpsec_register_scan_reset_endpoint() {
    // Endpoint for resetting a specific scan
    register_rest_route('wpsec/v1', '/reset/(?P<scan_id>[a-zA-Z0-9_\.]+)', array(
        'methods' => 'POST',
        'callback' => 'wpsec_reset_scan_endpoint',
        'permission_callback' => '__return_true'
    ));
    
    // Endpoint for resetting all non-completed scans (with clear_all parameter)
    register_rest_route('wpsec/v1', '/reset', array(
        'methods' => 'POST',
        'callback' => 'wpsec_reset_scan_endpoint',
        'permission_callback' => '__return_true',
        'args' => array(
            'clear_all' => array(
                'required' => false,
                'default' => false,
                'validate_callback' => function($param) {
                    return is_bool($param) || $param === '1' || $param === 1 || $param === true || 
                           strtolower($param) === 'true' || strtolower($param) === 'yes';
                }
            )
        )
    ));
}
add_action('rest_api_init', 'wpsec_register_scan_reset_endpoint');
