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

/**
 * Batch process multiple files (quarantine or delete)
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_batch_file_actions_endpoint($request) {
    // Debug logging
    wpsec_log('Batch file actions endpoint called', 'action');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for batch file actions', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $files = $request->get_param('files');
    $operation = $request->get_param('operation');
    
    if (empty($files) || !is_array($files)) {
        wpsec_log('Missing or invalid required parameter: files', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing or invalid required parameter: files (must be an array)',
            array('status' => 400)
        );
    }
    
    if (empty($operation) || !in_array($operation, ['quarantine', 'delete'])) {
        wpsec_log('Missing or invalid required parameter: operation', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing or invalid required parameter: operation (must be "quarantine" or "delete")',
            array('status' => 400)
        );
    }
    
    // Process the batch
    $results = wpsec_batch_process_files($files, $operation);
    
    wpsec_log('Batch file actions completed: ' . $results['success_count'] . '/' . $results['total'] . ' successful', 'action');
    
    return rest_ensure_response([
        'status' => 'success',
        'message' => 'Batch ' . $operation . ' operation completed',
        'results' => $results
    ]);
}

/**
 * Quarantine a file identified as malicious
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_quarantine_file_endpoint($request) {
    // Debug logging
    wpsec_log('File quarantine endpoint called', 'action');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for quarantine action', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $file_path = $request->get_param('file_path');
    $scan_finding_id = $request->get_param('scan_finding_id');
    $permanent_deletion = $request->get_param('permanent_deletion');
    
    if (empty($file_path)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Normalize the file path to handle different server configurations
    $normalized_path = wpsec_normalize_scan_path($file_path);
    wpsec_log('Original path: ' . $file_path, 'info');
    wpsec_log('Normalized path: ' . $normalized_path, 'info');

    // Security checks
    if (!wpsec_validate_file_path($normalized_path)) {
        wpsec_log('Invalid or unsafe file path: ' . $normalized_path, 'error');
        return new WP_Error(
            'invalid_file_path',
            'Invalid or unsafe file path',
            array('status' => 400)
        );
    }
    
    // Update file_path to use the normalized version
    $file_path = $normalized_path;

    // Ensure file exists
    if (!file_exists($file_path)) {
        wpsec_log('File not found: ' . $file_path, 'error');
        return new WP_Error(
            'file_not_found',
            'File not found',
            array('status' => 404)
        );
    }

    // Perform quarantine operation
    $result = wpsec_quarantine_file($file_path, $scan_finding_id);
    
    if (is_wp_error($result)) {
        wpsec_log('Quarantine failed: ' . $result->get_error_message(), 'error');
        return $result;
    }

    wpsec_log('File quarantined successfully: ' . $file_path, 'action');
    
    return rest_ensure_response([
        'status' => 'success',
        'message' => 'File quarantined successfully',
        'file_path' => $file_path,
        'quarantine_id' => $result['quarantine_id'],
        'original_path' => $result['original_path'],
        'quarantine_path' => $result['quarantine_path'],
        'timestamp' => $result['timestamp']
    ]);
}

/**
 * Delete a file identified as malicious
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_delete_file_endpoint($request) {
    // Debug logging
    wpsec_log('File deletion endpoint called', 'action');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for delete action', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $file_path = $request->get_param('file_path');
    $scan_finding_id = $request->get_param('scan_finding_id');
    $permanent_deletion = $request->get_param('permanent_deletion');
    
    if (empty($file_path)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Normalize the file path to handle different server configurations
    $normalized_path = wpsec_normalize_scan_path($file_path);
    wpsec_log('Original path: ' . $file_path, 'info');
    wpsec_log('Normalized path: ' . $normalized_path, 'info');

    // Security checks
    if (!wpsec_validate_file_path($normalized_path)) {
        wpsec_log('Invalid or unsafe file path: ' . $normalized_path, 'error');
        return new WP_Error(
            'invalid_file_path',
            'Invalid or unsafe file path',
            array('status' => 400)
        );
    }
    
    // Update file_path to use the normalized version
    $file_path = $normalized_path;

    // Ensure file exists
    if (!file_exists($file_path)) {
        wpsec_log('File not found: ' . $file_path, 'error');
        return new WP_Error(
            'file_not_found',
            'File not found',
            array('status' => 404)
        );
    }

    // Check if permanent deletion was requested (value must be 'yes')
    $permanent = ($permanent_deletion === 'yes');
    if ($permanent) {
        wpsec_log('Permanent deletion flag set to "yes"', 'info');
    }

    // Perform delete operation
    $result = wpsec_delete_file($file_path, $scan_finding_id, $permanent);
    
    if (is_wp_error($result)) {
        wpsec_log('Deletion failed: ' . $result->get_error_message(), 'error');
        return $result;
    }

    wpsec_log('File deleted successfully: ' . $file_path, 'action');
    
    // For non-permanent deletion, return quarantine information similar to quarantine endpoint
    if (!$permanent && is_array($result)) {
        return rest_ensure_response([
            'status' => 'success',
            'message' => 'File deleted successfully',
            'file_path' => $file_path,
            'quarantine_id' => $result['quarantine_id'],
            'original_path' => $result['original_path'],
            'quarantine_path' => $result['quarantine_path'],
            'timestamp' => $result['timestamp']
        ]);
    }
    
    // For permanent deletion, use the original format
    return rest_ensure_response([
        'status' => 'success',
        'message' => 'File deleted successfully',
        'file_path' => $file_path,
        'timestamp' => current_time('mysql')
    ]);
}

/**
 * Restore file(s) from quarantine
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_restore_file_endpoint($request) {
    // Debug logging
    wpsec_log('File restore endpoint called', 'action');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for restore action', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters - support both single and bulk restore
    $quarantine_ids = $request->get_param('quarantine_ids'); // For bulk restore
    $quarantine_id = $request->get_param('quarantine_id');   // For single restore
    
    // Handle bulk restore if quarantine_ids array is provided
    if (!empty($quarantine_ids) && is_array($quarantine_ids)) {
        wpsec_log('Bulk restore operation requested for ' . count($quarantine_ids) . ' files', 'action');
        
        // Perform bulk restore operation
        $result = wpsec_batch_restore_files($quarantine_ids);
        
        return rest_ensure_response([
            'status' => 'success',
            'message' => sprintf('Bulk restore completed: %d/%d successful, %d failed', 
                        $result['success_count'], $result['total'], $result['failed_count']),
            'total' => $result['total'],
            'success_count' => $result['success_count'],
            'failed_count' => $result['failed_count'],
            'success' => $result['success'],
            'failed' => $result['failed'],
            'timestamp' => current_time('mysql')
        ]);
    } 
    // Handle single restore for backward compatibility
    elseif (!empty($quarantine_id)) {
        wpsec_log('Single restore operation requested for ID: ' . $quarantine_id, 'action');
        
        // Perform restore operation
        $result = wpsec_restore_quarantined_file($quarantine_id);
        
        if (is_wp_error($result)) {
            wpsec_log('Restore failed: ' . $result->get_error_message(), 'error');
            return $result;
        }

        wpsec_log('File restored successfully: ' . $result['original_path'], 'action');
        
        return rest_ensure_response([
            'status' => 'success',
            'message' => 'File restored successfully',
            'quarantine_id' => $quarantine_id,
            'original_path' => $result['original_path'],
            'timestamp' => current_time('mysql')
        ]);
    }
    // No valid parameters provided
    else {
        wpsec_log('Missing required parameters: either quarantine_id or quarantine_ids must be provided', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameters: either quarantine_id or quarantine_ids must be provided',
            array('status' => 400)
        );
    }
}

/**
 * List all quarantined files
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_list_quarantine_endpoint($request) {
    // Debug logging
    wpsec_log('List quarantine endpoint called', 'info');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for list quarantine', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get quarantined files
    $quarantined_files = wpsec_get_quarantined_files();
    
    return rest_ensure_response([
        'status' => 'success',
        'count' => count($quarantined_files),
        'files' => $quarantined_files
    ]);
}
