<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.

if (!defined('WPINC')) {
    die;
}

class Aysa_Optimization_Ajax_Handler {
    
    public function __construct() {
        add_action('wp_ajax_aysa_refresh_metrics', array($this, 'handle_refresh_metrics'));
        add_action('wp_ajax_aysa_get_optimization_dashboard', array($this, 'handle_get_dashboard'));
        add_action('wp_ajax_aysa_trigger_metrics_calculation', array($this, 'handle_trigger_calculation'));
    }
    
    /**
     * Handle manual metrics refresh request
     */
    public function handle_refresh_metrics() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_POST['nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_refresh_metrics')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        try {
            // Load optimization metrics calculator
            require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-optimization-metrics.php';
            $metrics_calculator = new Aysa_Optimization_Metrics();
            
            // Calculate and store new metrics
            $result = $metrics_calculator->calculate_and_store_metrics();
            
            if ($result) {
                wp_send_json_success(array(
                    'message' => 'Metrics refreshed successfully',
                    'timestamp' => current_time('c')
                ));
            } else {
                wp_send_json_error('Failed to refresh metrics');
            }
            
        } catch (Exception $e) {
            aysa_debug_log('Aysa Optimization Metrics: Exception in refresh - ' . $e->getMessage());
            wp_send_json_error('An error occurred while refreshing metrics');
        }
    }
    
    /**
     * Handle dashboard data request
     */
    public function handle_get_dashboard() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_POST['nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_optimization_dashboard')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        try {
            // Load optimization metrics calculator
            require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-optimization-metrics.php';
            $metrics_calculator = new Aysa_Optimization_Metrics();
            
            // Get dashboard data
            $dashboard_data = $metrics_calculator->get_dashboard_data();
            
            wp_send_json_success($dashboard_data);
            
        } catch (Exception $e) {
            aysa_debug_log('Aysa Optimization Metrics: Exception in dashboard - ' . $e->getMessage());
            wp_send_json_error('An error occurred while fetching dashboard data');
        }
    }
    
    /**
     * Handle metrics calculation trigger
     */
    public function handle_trigger_calculation() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_POST['nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_trigger_calculation')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        try {
            // Schedule immediate calculation
            wp_schedule_single_event(time() + 60, 'aysa_daily_metrics_calculation');
            
            wp_send_json_success(array(
                'message' => 'Metrics calculation scheduled',
                'scheduled_time' => date('Y-m-d H:i:s', time() + 60)
            ));
            
        } catch (Exception $e) {
            aysa_debug_log('Aysa Optimization Metrics: Exception in trigger calculation - ' . $e->getMessage());
            wp_send_json_error('An error occurred while scheduling metrics calculation');
        }
    }
}
