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

/**
 * Add a file or multiple files to the whitelist
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_whitelist_file_endpoint($request) {
    // Debug logging
    wpsec_log('File whitelist endpoint called', 'info');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for file whitelist', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $file_paths = $request->get_param('file_path');
    $reason = $request->get_param('reason') ?: '';
    $added_by = $request->get_param('added_by') ?: 'user';
    
    if (empty($file_paths)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Convert to array if a single file path is provided
    if (!is_array($file_paths)) {
        $file_paths = array($file_paths);
    }
    
    // Process each file
    $results = array();
    $success_count = 0;
    $error_count = 0;
    
    foreach ($file_paths as $file_path) {
        // Normalize the file path
        $normalized_path = wpsec_normalize_scan_path($file_path);
        wpsec_log('Processing path: ' . $file_path, 'info');
        wpsec_log('Normalized path: ' . $normalized_path, 'info');

        // Add file to whitelist
        $result = wpsec_whitelist_file($normalized_path, $reason, $added_by);
        
        if (is_wp_error($result)) {
            wpsec_log('Failed to whitelist file: ' . $result->get_error_message(), 'error');
            $error_count++;
            $results[] = array(
                'file_path' => $file_path,
                'normalized_path' => $normalized_path,
                'status' => 'error',
                'message' => $result->get_error_message()
            );
        } else {
            wpsec_log('File successfully whitelisted: ' . $normalized_path, 'info');
            $success_count++;
            $results[] = array(
                'file_path' => $file_path,
                'normalized_path' => $normalized_path,
                'status' => 'success',
                'message' => 'File added to whitelist'
            );
        }
    }
    
    return rest_ensure_response([
        'status' => ($success_count > 0) ? 'success' : 'error',
        'message' => "$success_count file(s) added to whitelist, $error_count failure(s)",
        'total' => count($file_paths),
        'success_count' => $success_count,
        'error_count' => $error_count,
        'results' => $results
    ]);
}

/**
 * Remove a file or multiple files from the whitelist
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_remove_from_whitelist_endpoint($request) {
    // Debug logging
    wpsec_log('Remove from whitelist endpoint called', 'info');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for remove from whitelist', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $file_paths = $request->get_param('file_path');
    
    if (empty($file_paths)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Convert to array if a single file path is provided
    if (!is_array($file_paths)) {
        $file_paths = array($file_paths);
    }
    
    // Process each file
    $results = array();
    $success_count = 0;
    $error_count = 0;
    
    foreach ($file_paths as $file_path) {
        // Normalize the file path
        $normalized_path = wpsec_normalize_scan_path($file_path);
        
        // Remove file from whitelist
        $result = wpsec_remove_from_whitelist($normalized_path);
        
        if (!$result) {
            wpsec_log('File not found in whitelist: ' . $normalized_path, 'warning');
            $error_count++;
            $results[] = array(
                'file_path' => $file_path,
                'normalized_path' => $normalized_path,
                'status' => 'error',
                'message' => 'File not found in whitelist'
            );
        } else {
            wpsec_log('File successfully removed from whitelist: ' . $normalized_path, 'info');
            $success_count++;
            $results[] = array(
                'file_path' => $file_path,
                'normalized_path' => $normalized_path,
                'status' => 'success',
                'message' => 'File removed from whitelist'
            );
        }
    }
    
    return rest_ensure_response([
        'status' => ($success_count > 0) ? 'success' : 'error',
        'message' => "$success_count file(s) removed from whitelist, $error_count failure(s)",
        'total' => count($file_paths),
        'success_count' => $success_count,
        'error_count' => $error_count,
        'results' => $results
    ]);
}

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

    // Get parameters
    $include_details = $request->get_param('include_details') ? true : false;
    $verify_integrity = $request->get_param('verify_integrity') ? true : false;
    
    // Get whitelisted files
    $whitelisted_files = wpsec_get_whitelisted_files($include_details);
    
    // Verify integrity if requested
    $integrity_results = null;
    if ($verify_integrity) {
        $integrity_results = wpsec_verify_whitelist_integrity();
    }
    
    wpsec_log('Successfully retrieved whitelisted files list', 'info');
    
    $response = [
        'status' => 'success',
        'count' => count($whitelisted_files),
        'files' => $whitelisted_files
    ];
    
    if ($integrity_results) {
        $response['integrity'] = $integrity_results;
    }
    
    return rest_ensure_response($response);
}

/**
 * Verify the integrity of all whitelisted files
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_verify_whitelist_integrity_endpoint($request) {
    // Debug logging
    wpsec_log('Verify whitelist integrity endpoint called', 'info');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for verify whitelist integrity', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Verify integrity
    $integrity_results = wpsec_verify_whitelist_integrity();
    
    wpsec_log('Successfully verified whitelist integrity', 'info');
    
    return rest_ensure_response([
        'status' => 'success',
        'integrity' => $integrity_results
    ]);
}

/**
 * Clean up the whitelist
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_cleanup_whitelist_endpoint($request) {
    // Debug logging
    wpsec_log('Cleanup whitelist endpoint called', 'info');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for cleanup whitelist', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Clean up whitelist
    $removed = wpsec_cleanup_whitelist();
    
    wpsec_log('Successfully cleaned up whitelist, removed ' . $removed . ' entries', 'info');
    
    return rest_ensure_response([
        'status' => 'success',
        'removed' => $removed
    ]);
}
