<?php
/**
 * Extra Config AJAX Handler
 * Handles all AJAX requests with proper security
 *
 * @package AIAutoTool
 * @subpackage ExtraConfig
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

/**
 * AJAX Handler class
 */
class Aiautotool_Extra_Config_AJAX_Handler {
    
    /**
     * Security instance
     *
     * @var Aiautotool_Extra_Config_Security
     */
    private $security;
    
    /**
     * Settings registry instance
     *
     * @var Aiautotool_Extra_Config_Settings_Registry
     */
    private $settings;
    
    /**
     * Constructor
     *
     * @param Aiautotool_Extra_Config_Security          $security Security instance
     * @param Aiautotool_Extra_Config_Settings_Registry $settings Settings instance
     */
    public function __construct($security, $settings) {
        $this->security = $security;
        $this->settings = $settings;
    }
    
    /**
     * Register AJAX handlers
     *
     * @return void
     */
    public function register_handlers() {
        // Database cleanup actions
        add_action('wp_ajax_aiautotool_extra_config_delete_revisions', array($this, 'delete_revisions'));
        add_action('wp_ajax_aiautotool_extra_config_delete_drafts', array($this, 'delete_drafts'));
        add_action('wp_ajax_aiautotool_extra_config_delete_trash', array($this, 'delete_trash'));
        
        // Settings actions
        add_action('wp_ajax_aiautotool_extra_config_reset_settings', array($this, 'reset_settings'));
        add_action('wp_ajax_aiautotool_extra_config_export_settings', array($this, 'export_settings'));
        add_action('wp_ajax_aiautotool_extra_config_import_settings', array($this, 'import_settings'));
    }
    
    /**
     * Verify AJAX request security
     *
     * @return bool|void Returns false or dies if verification fails
     */
    private function verify_request() {
        // Verify nonce
        if (!$this->security->verify_ajax_nonce('nonce')) {
            wp_send_json_error(
                array('message' => __('Security verification failed', 'ai-auto-tool')),
                403
            );
        }
        
        // Verify permissions
        if (!$this->security->can_manage_settings()) {
            wp_send_json_error(
                array('message' => __('You do not have permission to perform this action', 'ai-auto-tool')),
                403
            );
        }
        
        return true;
    }
    
    /**
     * Delete post revisions
     *
     * @return void
     */
    public function delete_revisions() {
        $this->verify_request();
        
        global $wpdb;
        
        // Use prepared statement
        $deleted = $wpdb->delete(
            $wpdb->posts,
            array('post_type' => 'revision'),
            array('%s')
        );
        
        if (false === $deleted) {
            wp_send_json_error(array(
                'message' => __('Database error occurred while deleting revisions', 'ai-auto-tool'),
                'error'   => $wpdb->last_error
            ));
        }
        
        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: %d: number of deleted revisions */
                _n(
                    'Successfully deleted %d revision',
                    'Successfully deleted %d revisions',
                    $deleted,
                    'ai-auto-tool'
                ),
                $deleted
            ),
            'deleted' => $deleted
        ));
    }
    
    /**
     * Delete auto-draft posts
     *
     * @return void
     */
    public function delete_drafts() {
        $this->verify_request();
        
        global $wpdb;
        
        // Use prepared statement
        $deleted = $wpdb->delete(
            $wpdb->posts,
            array('post_status' => 'auto-draft'),
            array('%s')
        );
        
        if (false === $deleted) {
            wp_send_json_error(array(
                'message' => __('Database error occurred while deleting drafts', 'ai-auto-tool'),
                'error'   => $wpdb->last_error
            ));
        }
        
        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: %d: number of deleted drafts */
                _n(
                    'Successfully deleted %d draft',
                    'Successfully deleted %d drafts',
                    $deleted,
                    'ai-auto-tool'
                ),
                $deleted
            ),
            'deleted' => $deleted
        ));
    }
    
    /**
     * Delete trashed posts
     *
     * @return void
     */
    public function delete_trash() {
        $this->verify_request();
        
        global $wpdb;
        
        // Use prepared statement
        $deleted = $wpdb->delete(
            $wpdb->posts,
            array('post_status' => 'trash'),
            array('%s')
        );
        
        if (false === $deleted) {
            wp_send_json_error(array(
                'message' => __('Database error occurred while emptying trash', 'ai-auto-tool'),
                'error'   => $wpdb->last_error
            ));
        }
        
        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: %d: number of deleted posts */
                _n(
                    'Successfully deleted %d post from trash',
                    'Successfully deleted %d posts from trash',
                    $deleted,
                    'ai-auto-tool'
                ),
                $deleted
            ),
            'deleted' => $deleted
        ));
    }
    
    /**
     * Reset settings to defaults
     *
     * @return void
     */
    public function reset_settings() {
        $this->verify_request();
        
        $reset = $this->settings->reset();
        
        if (!$reset) {
            wp_send_json_error(array(
                'message' => __('Failed to reset settings', 'ai-auto-tool')
            ));
        }
        
        wp_send_json_success(array(
            'message'  => __('Settings reset to defaults successfully', 'ai-auto-tool'),
            'settings' => $this->settings->get_all()
        ));
    }
    
    /**
     * Export settings
     *
     * @return void
     */
    public function export_settings() {
        $this->verify_request();
        
        $export = $this->settings->export();
        
        if (empty($export)) {
            wp_send_json_error(array(
                'message' => __('Failed to export settings', 'ai-auto-tool')
            ));
        }
        
        wp_send_json_success(array(
            'message' => __('Settings exported successfully', 'ai-auto-tool'),
            'data'    => $export,
            'filename' => 'aiautotool-extra-config-' . date('Y-m-d') . '.json'
        ));
    }
    
    /**
     * Import settings
     *
     * @return void
     */
    public function import_settings() {
        $this->verify_request();
        
        // Get JSON data from POST
        $json = isset($_POST['settings_data']) ? wp_unslash($_POST['settings_data']) : '';
        
        if (empty($json)) {
            wp_send_json_error(array(
                'message' => __('No settings data provided', 'ai-auto-tool')
            ));
        }
        
        $imported = $this->settings->import($json);
        
        if (is_wp_error($imported)) {
            wp_send_json_error(array(
                'message' => $imported->get_error_message()
            ));
        }
        
        wp_send_json_success(array(
            'message'  => __('Settings imported successfully', 'ai-auto-tool'),
            'settings' => $this->settings->get_all()
        ));
    }
    
    /**
     * Get database cleanup statistics
     *
     * @return void
     */
    public function get_cleanup_stats() {
        $this->verify_request();
        
        global $wpdb;
        
        // Count revisions
        $revisions_count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s",
                'revision'
            )
        );
        
        // Count auto-drafts
        $drafts_count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = %s",
                'auto-draft'
            )
        );
        
        // Count trashed posts
        $trash_count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = %s",
                'trash'
            )
        );
        
        wp_send_json_success(array(
            'revisions' => (int) $revisions_count,
            'drafts'    => (int) $drafts_count,
            'trash'     => (int) $trash_count,
            'total'     => (int) $revisions_count + (int) $drafts_count + (int) $trash_count
        ));
    }
    
    /**
     * Test a specific feature
     *
     * @return void
     */
    public function test_feature() {
        $this->verify_request();
        
        $feature = isset($_POST['feature']) ? sanitize_key($_POST['feature']) : '';
        
        if (empty($feature)) {
            wp_send_json_error(array(
                'message' => __('No feature specified', 'ai-auto-tool')
            ));
        }
        
        // Test the feature
        $result = $this->perform_feature_test($feature);
        
        if (is_wp_error($result)) {
            wp_send_json_error(array(
                'message' => $result->get_error_message()
            ));
        }
        
        wp_send_json_success(array(
            'message' => __('Feature test completed', 'ai-auto-tool'),
            'result'  => $result
        ));
    }
    
    /**
     * Perform feature test
     *
     * @param string $feature Feature key to test
     * @return array|WP_Error Test results
     */
    private function perform_feature_test($feature) {
        switch ($feature) {
            case 'speed-off1': // jQuery Migrate
                $scripts = wp_scripts();
                $has_jquery_migrate = isset($scripts->registered['jquery-migrate']);
                return array(
                    'status' => !$has_jquery_migrate ? 'success' : 'warning',
                    'message' => !$has_jquery_migrate ? 
                        __('jQuery Migrate is disabled', 'ai-auto-tool') : 
                        __('jQuery Migrate is still loaded', 'ai-auto-tool')
                );
                
            default:
                return new WP_Error(
                    'unknown_feature',
                    __('Unknown feature test', 'ai-auto-tool')
                );
        }
    }
    
    /**
     * Batch delete operation
     *
     * @return void
     */
    public function batch_cleanup() {
        $this->verify_request();
        
        $operations = isset($_POST['operations']) ? (array) $_POST['operations'] : array();
        
        if (empty($operations)) {
            wp_send_json_error(array(
                'message' => __('No operations specified', 'ai-auto-tool')
            ));
        }
        
        $results = array();
        global $wpdb;
        
        foreach ($operations as $operation) {
            $operation = sanitize_key($operation);
            
            switch ($operation) {
                case 'revisions':
                    $deleted = $wpdb->delete($wpdb->posts, array('post_type' => 'revision'), array('%s'));
                    $results['revisions'] = (int) $deleted;
                    break;
                    
                case 'drafts':
                    $deleted = $wpdb->delete($wpdb->posts, array('post_status' => 'auto-draft'), array('%s'));
                    $results['drafts'] = (int) $deleted;
                    break;
                    
                case 'trash':
                    $deleted = $wpdb->delete($wpdb->posts, array('post_status' => 'trash'), array('%s'));
                    $results['trash'] = (int) $deleted;
                    break;
            }
        }
        
        $total_deleted = array_sum($results);
        
        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: %d: total number of deleted items */
                _n(
                    'Successfully deleted %d item',
                    'Successfully deleted %d items',
                    $total_deleted,
                    'ai-auto-tool'
                ),
                $total_deleted
            ),
            'results' => $results
        ));
    }
}


