<?php
class SeekMake_Event_Handler {

    public function handle_event() {
        if (!SeekMake_Security::verify_nonce('seekmake_nonce', 'seekmake_event')) {
            wp_send_json_error(array('message' => 'Invalid security token.'), 403);
        }

        if (!SeekMake_Security::check_capability('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'), 403);
        }

        $event_type = isset($_POST['event_type']) ? sanitize_text_field($_POST['event_type']) : '';
        $event_data = isset($_POST['event_data']) ? $_POST['event_data'] : array();
        
        $event_data = SeekMake_Security::sanitize_event_data($event_data);

        switch ($event_type) {
            case 'config_updated':
                $this->handle_config_update($event_data);
                break;

            case 'widget_settings_changed':
                $this->handle_widget_settings_change($event_data);
                break;

            case 'manufacturer_id_changed':
                $this->handle_manufacturer_id_change($event_data);
                break;

            case 'plugin_activated':
                $this->handle_plugin_activation($event_data);
                break;

            case 'auto_update':
                $this->handle_auto_update($event_data);
                break;

            default:
                do_action('seekmake_handle_custom_event', $event_type, $event_data);
                wp_send_json_success(array('message' => 'Event processed.'));
                break;
        }
    }

    public function handle_auth() {
        if (!SeekMake_Security::verify_nonce('seekmake_nonce', 'seekmake_event')) {
            wp_send_json_error(array('message' => 'Invalid security token.'), 403);
        }

        if (!SeekMake_Security::check_capability('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'), 403);
        }

        $event_data = isset($_POST['event_data']) ? $_POST['event_data'] : array();
        
        if (is_string($event_data)) {
            $event_data = wp_unslash($event_data);
            $decoded_data = json_decode($event_data, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                wp_send_json_error(array('message' => 'Invalid event data format.'));
            }
            $event_data = $decoded_data;
        }
        
        $event_data = SeekMake_Security::sanitize_event_data($event_data);

        if (empty($event_data['manufacturer_id'])) {
            wp_send_json_error(array('message' => 'Manufacturer ID is required.'));
        }

        $manufacturer_id = SeekMake_Security::sanitize_manufacturer_id($event_data['manufacturer_id']);
        
        if (!SeekMake_Security::validate_manufacturer_id($manufacturer_id, true)) {
            wp_send_json_error(array(
                'message' => 'Invalid manufacturer ID format. Authentication blocked.',
                'code' => 'INVALID_MANUFACTURER_ID'
            ));
        }

        $user_email = isset($event_data['user_email']) ? sanitize_email($event_data['user_email']) : '';
        $user_name = isset($event_data['user_name']) ? sanitize_text_field($event_data['user_name']) : '';

        update_option('seekmake_manufacturer_id', $manufacturer_id);
        update_option('seekmake_authenticated', true);
        update_option('seekmake_user_email', $user_email);
        update_option('seekmake_user_name', $user_name);
        update_option('seekmake_auth_timestamp', current_time('mysql'));

        if (!empty($event_data['token'])) {
            update_option('seekmake_auth_token', sanitize_text_field($event_data['token']));
        }

        $default_widgets = array(
            'Instant Quote',
            'Client Dashboard',
            'Astra AI'
        );
        update_option('seekmake_active_plugins', $default_widgets);
        update_option('seekmake_widgets_activated', true);

        do_action('seekmake_authenticated', array(
            'manufacturer_id' => $manufacturer_id,
            'user_email' => $user_email,
            'user_name' => $user_name
        ));

        do_action('seekmake_widgets_activated', $default_widgets);

        wp_send_json_success(array(
            'message' => 'Authentication successful.',
            'manufacturer_id' => $manufacturer_id,
            'user_email' => $user_email,
            'widgets_activated' => $default_widgets
        ));
    }

    public function disconnect_account() {
        if (!SeekMake_Security::verify_nonce('seekmake_nonce', 'seekmake_event')) {
            wp_send_json_error(array('message' => 'Invalid security token.'), 403);
        }

        if (!SeekMake_Security::check_capability('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'), 403);
        }

        delete_option('seekmake_authenticated');
        delete_option('seekmake_user_email');
        delete_option('seekmake_user_name');
        delete_option('seekmake_auth_token');
        delete_option('seekmake_auth_timestamp');
        delete_option('seekmake_manufacturer_id');
        
        delete_option('seekmake_active_plugins');
        delete_option('seekmake_woocommerce_enabled');
        
        delete_option('seekmake_last_update');

        do_action('seekmake_disconnected');

        wp_send_json_success(array(
            'message' => 'Account disconnected successfully. All features have been deactivated.'
        ));
    }

    private function handle_config_update($data) {
        $settings = get_option('seekmake_settings', array());
        
        if (isset($data['config'])) {
            $settings = array_merge($settings, $data['config']);
            update_option('seekmake_settings', $settings);
            
            do_action('seekmake_config_updated', $settings);
            
            wp_send_json_success(array(
                'message' => 'Configuration updated successfully.',
                'settings' => $settings
            ));
        }

        wp_send_json_error(array('message' => 'Invalid configuration data.'));
    }

    private function handle_widget_settings_change($data) {
        if (isset($data['widget_type']) && isset($data['settings'])) {
            $widget_type = sanitize_text_field($data['widget_type']);
            $widget_settings = get_option('seekmake_widget_settings', array());
            
            $widget_settings[$widget_type] = $data['settings'];
            update_option('seekmake_widget_settings', $widget_settings);
            
            do_action('seekmake_widget_settings_updated_' . $widget_type, $data['settings']);
            
            wp_send_json_success(array(
                'message' => 'Widget settings updated successfully.',
                'widget_type' => $widget_type
            ));
        }

        wp_send_json_error(array('message' => 'Invalid widget settings data.'));
    }

    private function handle_manufacturer_id_change($data) {
        if (isset($data['manufacturer_id'])) {
            $manufacturer_id = SeekMake_Security::sanitize_manufacturer_id($data['manufacturer_id']);
            
            update_option('seekmake_manufacturer_id', $manufacturer_id);
            
            do_action('seekmake_manufacturer_id_changed', $manufacturer_id);
            
            wp_send_json_success(array(
                'message' => 'Manufacturer ID updated successfully.',
                'manufacturer_id' => $manufacturer_id
            ));
        }

        wp_send_json_error(array('message' => 'Invalid manufacturer ID.'));
    }

    private function handle_plugin_activation($data) {
        if (isset($data['plugin_name'])) {
            $plugin_name = sanitize_text_field($data['plugin_name']);
            
            $active_plugins = get_option('seekmake_active_plugins', array());
            
            if (!in_array($plugin_name, $active_plugins)) {
                $active_plugins[] = $plugin_name;
                update_option('seekmake_active_plugins', $active_plugins);
            }
            
            do_action('seekmake_plugin_activated', $plugin_name);
            
            wp_send_json_success(array(
                'message' => 'Plugin activated successfully.',
                'plugin_name' => $plugin_name
            ));
        }

        wp_send_json_error(array('message' => 'Invalid plugin name.'));
    }

    private function handle_auto_update($data) {
        update_option('seekmake_last_update', current_time('mysql'));
        
        if (isset($data['settings'])) {
            $current_settings = get_option('seekmake_settings', array());
            $updated_settings = array_merge($current_settings, $data['settings']);
            update_option('seekmake_settings', $updated_settings);
        }
        
        do_action('seekmake_auto_update_triggered', $data);
        
        wp_send_json_success(array(
            'message' => 'Auto-update completed successfully.',
            'timestamp' => current_time('mysql')
        ));
    }

    public function save_settings() {
        if (!SeekMake_Security::verify_nonce('seekmake_nonce', 'seekmake_settings')) {
            wp_send_json_error(array('message' => 'Invalid security token.'), 403);
        }

        if (!SeekMake_Security::check_capability('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'), 403);
        }

        $settings = isset($_POST['settings']) ? $_POST['settings'] : array();
        $settings = SeekMake_Security::sanitize_event_data($settings);

        update_option('seekmake_settings', $settings);

        do_action('seekmake_settings_saved', $settings);

        wp_send_json_success(array(
            'message' => 'Settings saved successfully.',
            'settings' => $settings
        ));
    }

    public function get_settings() {
        if (!SeekMake_Security::verify_nonce('seekmake_nonce', 'seekmake_settings')) {
            wp_send_json_error(array('message' => 'Invalid security token.'), 403);
        }

        if (!SeekMake_Security::check_capability('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'), 403);
        }

        $settings = get_option('seekmake_settings', array());
        $manufacturer_id = get_option('seekmake_manufacturer_id', '');

        wp_send_json_success(array(
            'settings' => $settings,
            'manufacturer_id' => $manufacturer_id
        ));
    }
}
