<?php
/**
 * The admin-specific functionality of the plugin
 *
 * @package SPAI_Contact_Form
 */

class SPAI_Admin {
    
    /**
     * The ID of this plugin
     */
    private $plugin_name;
    
    /**
     * The version of this plugin
     */
    private $version;
    
    /**
     * Initialize the class
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }
    
    /**
     * Register the stylesheets for the admin area
     */
    public function enqueue_styles($hook) {
        // Only load on our plugin pages
        if (strpos($hook, 'spai-contact-form') === false) {
            return;
        }
        
        wp_enqueue_style($this->plugin_name, SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/css/admin.css', array(), $this->version, 'all');
    }
    
    /**
     * Register the JavaScript for the admin area
     */
    public function enqueue_scripts($hook) {
        // Only load on our plugin pages
        if (strpos($hook, 'spai-contact-form') === false) {
            return;
        }
        
        // jQuery UI dependencies
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-dialog');
        wp_enqueue_style('wp-jquery-ui-dialog');
        
        // Admin script
        wp_enqueue_script($this->plugin_name, SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/js/admin.js', array('jquery', 'jquery-ui-sortable'), $this->version, false);
        
        // Form builder script
        wp_enqueue_script($this->plugin_name . '-form-builder', SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/js/form-builder.js', array('jquery', 'jquery-ui-sortable'), $this->version, false);
        
        // Phone input dependencies
        wp_enqueue_style('intl-tel-input', SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/css/css/intlTelInput.min.css', array(), '17.0.0');
        wp_enqueue_script('intl-tel-input', SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/js/vendor/intl-tel-input/js/intlTelInput.min.js', array(), '17.0.0', false);
        wp_enqueue_script($this->plugin_name . '-phone-input', SPAI_CONTACT_FORM_PLUGIN_URL . 'assets/js/phone-input.js', array('intl-tel-input'), $this->version, false);
        
        // Localize script
        wp_localize_script($this->plugin_name, 'spai_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('spai_admin_nonce'),
            'plugin_url' => SPAI_CONTACT_FORM_PLUGIN_URL,
            'strings' => array(
                'confirm_delete' => __('Are you sure you want to delete this form?', 'spai-contact-form'),
                'saving' => __('Saving...', 'spai-contact-form'),
                'saved' => __('Saved', 'spai-contact-form'),
                'error' => __('An error occurred. Please try again.', 'spai-contact-form')
            )
        ));
    }
    
    /**
     * Add plugin admin menu
     */
    public function add_plugin_admin_menu() {
        add_menu_page(
            __('SPAI Forms', 'spai-contact-form'),
            __('SPAI Forms', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form',
            array($this, 'display_forms_page'),
            'dashicons-forms',
            30
        );
        
        add_submenu_page(
            'spai-contact-form',
            __('All Forms', 'spai-contact-form'),
            __('All Forms', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form',
            array($this, 'display_forms_page')
        );
        
        add_submenu_page(
            'spai-contact-form',
            __('Add New Form', 'spai-contact-form'),
            __('Add New', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form-new',
            array($this, 'display_form_editor')
        );
        
        add_submenu_page(
            'spai-contact-form',
            __('Submissions', 'spai-contact-form'),
            __('Submissions', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form-submissions',
            array($this, 'display_submissions_page')
        );
        
        add_submenu_page(
            'spai-contact-form',
            __('Integrations', 'spai-contact-form'),
            __('Integrations', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form-integrations',
            array($this, 'display_integrations_page')
        );
        
        add_submenu_page(
            'spai-contact-form',
            __('Settings', 'spai-contact-form'),
            __('Settings', 'spai-contact-form'),
            'manage_options',
            'spai-contact-form-settings',
            array($this, 'display_settings_page')
        );
    }
    
    /**
     * Add settings link on plugin page
     */
    public function add_action_links($links) {
        $settings_link = '<a href="' . admin_url('admin.php?page=spai-contact-form-settings') . '">' . __('Settings', 'spai-contact-form') . '</a>';
        array_unshift($links, $settings_link);
        
        return $links;
    }
    
    /**
     * Display forms list page
     */
    public function display_forms_page() {
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'templates/admin/forms-list.php';
    }
    
    /**
     * Display form editor page
     */
    public function display_form_editor() {
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'templates/admin/form-editor.php';
    }
    
    /**
     * Display submissions page
     */
    public function display_submissions_page() {
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'templates/admin/submissions.php';
    }
    
    /**
     * Display integrations page
     */
    public function display_integrations_page() {
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'templates/admin/integrations.php';
    }
    
    /**
     * Display settings page
     */
    public function display_settings_page() {
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'templates/admin/settings.php';
    }
    
    /**
     * Ajax handler to save form
     */
    public function ajax_save_form() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $form_id = isset($_POST['form_id']) && $_POST['form_id'] !== 'null' ? intval($_POST['form_id']) : null;
        $form_data = isset($_POST['form_data']) ? wp_unslash($_POST['form_data']) : array();
        
        // Log the received data for debugging
        
        // Validate form data
        if (empty($form_data['form_name'])) {
            wp_send_json_error(__('Form name is required.', 'spai-contact-form'));
        }
        
        // Ensure form_fields is set and is an array
        if (!isset($form_data['form_fields'])) {
            $form_data['form_fields'] = array();
        }
        
        // Ensure form_settings is set and is an array
        if (!isset($form_data['form_settings'])) {
            $form_data['form_settings'] = array();
        }
        
        $db_handler = new SPAI_DB_Handler();
        $result = $db_handler->save_form($form_data, $form_id);
        
        if ($result) {
            wp_send_json_success(array(
                'message' => __('Form saved successfully.', 'spai-contact-form'),
                'form_id' => $result
            ));
        } else {
            wp_send_json_error(__('Failed to save form.', 'spai-contact-form'));
        }
    }
    
    /**
     * Ajax handler to delete form
     */
    public function ajax_delete_form() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
        
        if (!$form_id) {
            wp_send_json_error(__('Invalid form ID.', 'spai-contact-form'));
        }
        
        $db_handler = new SPAI_DB_Handler();
        $result = $db_handler->delete_form($form_id);
        
        if ($result) {
            wp_send_json_success(__('Form deleted successfully.', 'spai-contact-form'));
        } else {
            wp_send_json_error(__('Failed to delete form.', 'spai-contact-form'));
        }
    }
    
    /**
     * Ajax handler to test integration
     */
    public function ajax_test_integration() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $integration = isset($_POST['integration']) ? sanitize_text_field($_POST['integration']) : '';
        $settings = isset($_POST['settings']) ? $_POST['settings'] : array();
        
        switch ($integration) {
            case 'monday':
                require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/monday/class-spai-monday-integration.php';
                $monday = new SPAI_Monday_Integration($settings['api_key']);
                $result = $monday->test_connection();
                break;
                
            case 'salespartner':
                require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/salespartner/class-spai-salespartner-integration.php';
                $salespartner = new SPAI_SalesPartner_Integration($settings['api_url']);
                $result = $salespartner->test_connection();
                break;
                
            case 'gchat':
                require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/notifications/class-spai-gchat-integration.php';
                $gchat = new SPAI_GChat_Integration($settings['webhook_url']);
                $result = $gchat->test_connection();
                break;

            case 'email':
                require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/notifications/class-spai-email-integration.php';
                $email = new SPAI_Email_Integration($settings);
                $result = $email->test_connection();
                break;

            default:
                $result = array('success' => false, 'message' => __('Invalid integration type.', 'spai-contact-form'));
        }
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * Ajax handler to get Monday.com boards
     */
    public function ajax_get_monday_boards() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
        
        if (empty($api_key)) {
            wp_send_json_error(__('API key is required.', 'spai-contact-form'));
        }
        
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/monday/class-spai-monday-integration.php';
        $monday = new SPAI_Monday_Integration($api_key);
        $boards = $monday->get_boards();
        
        if ($boards['success']) {
            wp_send_json_success($boards['boards']);
        } else {
            wp_send_json_error($boards['message']);
        }
    }
    
    /**
     * Ajax handler to get Monday.com columns
     */
    public function ajax_get_monday_columns() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
        $board_id = isset($_POST['board_id']) ? sanitize_text_field($_POST['board_id']) : '';
        
        if (empty($api_key) || empty($board_id)) {
            wp_send_json_error(__('API key and board ID are required.', 'spai-contact-form'));
        }
        
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/monday/class-spai-monday-integration.php';
        $monday = new SPAI_Monday_Integration($api_key);
        $columns = $monday->get_board_columns($board_id);
        
        if ($columns['success']) {
            wp_send_json_success($columns['columns']);
        } else {
            wp_send_json_error($columns['message']);
        }
    }
    
    /**
     * Ajax handler to import form fields from Monday.com board
     */
    public function ajax_import_monday_fields() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
        $board_id = isset($_POST['board_id']) ? sanitize_text_field($_POST['board_id']) : '';
        
        if (empty($api_key) || empty($board_id)) {
            wp_send_json_error(__('API key and board ID are required.', 'spai-contact-form'));
        }
        
        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/monday/class-spai-monday-integration.php';
        $monday = new SPAI_Monday_Integration($api_key);
        
        // Get board columns with details
        $response = $monday->get_board_columns_detailed($board_id);
        
        if (!$response['success']) {
            wp_send_json_error($response['message']);
        }
        
        // Reverse mapping - Monday column to form field
        $reverse_mapping = array(
            'text_mks23050' => array('name' => 'first_name', 'type' => 'text', 'label' => 'First Name'),
            'text_mks29gdm' => array('name' => 'last_name', 'type' => 'text', 'label' => 'Last Name'),
            'lead_email' => array('name' => 'email', 'type' => 'email', 'label' => 'Email'),
            'lead_phone' => array('name' => 'phone', 'type' => 'phone', 'label' => 'Phone'),
            'text_mks25te4' => array('name' => 'street', 'type' => 'text', 'label' => 'Street Address'),
            'text_mks2z52j' => array('name' => 'city', 'type' => 'text', 'label' => 'City'),
            'text_mks2jcz1' => array('name' => 'state', 'type' => 'select', 'label' => 'State'),
            'text_mks2vp2g' => array('name' => 'zip', 'type' => 'text', 'label' => 'Zip'),
            'type' => array('name' => 'project_type', 'type' => 'select', 'label' => 'Project Type'),
            'single_select' => array('name' => 'role', 'type' => 'select', 'label' => 'Your Role'),
            'dropdown' => array('name' => 'project_intestests', 'type' => 'multi_select', 'label' => 'What are you looking for?'),
            'multi_select' => array('name' => 'project_services', 'type' => 'multi_select', 'label' => 'What services are you interested in?'),
            'dropdown3' => array('name' => 'project_budget', 'type' => 'select', 'label' => 'Estimated Budget'),
            'date5' => array('name' => 'estimated_install_date', 'type' => 'date', 'label' => 'Estimated Install Date'),
            'long_text' => array('name' => 'message', 'type' => 'textarea', 'label' => 'Tell us more about your project'),
            'files' => array('name' => 'upload', 'type' => 'file', 'label' => 'Upload plans/photos'),
            'boolean_mks2k3gq' => array('name' => 'sms_consent', 'type' => 'consent_checkbox', 'label' => 'Consent Checkbox')
        );
        
        $form_fields = array();
        
        foreach ($response['columns'] as $column) {
            // Skip if not in our mapping
            if (!isset($reverse_mapping[$column['id']])) {
                continue;
            }
            
            $field_config = $reverse_mapping[$column['id']];
            
            // Create field array
            $field = array(
                'id' => 'field_' . time() . '_' . rand(1000, 9999),
                'type' => $field_config['type'],
                'name' => $field_config['name'],
                'label' => $field_config['label'],
                'required' => false
            );
            
            // Handle dropdown/select fields
            if (in_array($column['type'], ['dropdown', 'multiple-select']) && isset($column['settings'])) {
                $options = array();
                foreach ($column['settings']['labels'] as $label_data) {
                    if (is_array($label_data) && isset($label_data['name'])) {
                        $options[] = $label_data['name'];
                    } else if (is_string($label_data)) {
                        $options[] = $label_data;
                    }
                }
                $field['options'] = $options;
            }
            
            // Special handling for specific fields
            if ($field['name'] === 'state') {
                // Add US states
                $field['options'] = array(
                    'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 
                    'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 
                    'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 
                    'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 
                    'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 
                    'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 
                    'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'Washington DC', 'West Virginia', 
                    'Wisconsin', 'Wyoming'
                );
            }
            
            if ($field['type'] === 'consent_checkbox') {
                $field['label_text'] = 'By checking this box, you agree to receive text messages. Standard message and data rates may apply. Reply STOP to opt out at any time.';
                $field['default_checked'] = true;
                $field['hide_label'] = true;
            }
            
            $form_fields[] = $field;
        }
        
        // Add country field (not from Monday)
        $form_fields[] = array(
            'id' => 'field_' . time() . '_country',
            'type' => 'hidden',
            'name' => 'country',
            'label' => 'Country',
            'value' => 'USA'
        );
        
        wp_send_json_success($form_fields);
    }
    
    /**
     * Ajax handler to save integration settings
     */
    public function ajax_save_integrations() {
        check_ajax_referer('spai_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }

        $monday_settings = isset($_POST['monday_settings']) ? $_POST['monday_settings'] : array();
        $salespartner_settings = isset($_POST['salespartner_settings']) ? $_POST['salespartner_settings'] : array();
        $chat_widget_settings = isset($_POST['chat_widget_settings']) ? $_POST['chat_widget_settings'] : array();
        $gchat_settings = isset($_POST['gchat_settings']) ? $_POST['gchat_settings'] : array();

        // Convert string boolean values to actual booleans
        if (isset($monday_settings['enabled'])) {
            $monday_settings['enabled'] = ($monday_settings['enabled'] === 'true');
        }
        if (isset($salespartner_settings['enabled'])) {
            $salespartner_settings['enabled'] = ($salespartner_settings['enabled'] === 'true');
        }
        if (isset($chat_widget_settings['enabled'])) {
            $chat_widget_settings['enabled'] = ($chat_widget_settings['enabled'] === 'true');
        }
        if (isset($gchat_settings['enabled'])) {
            $gchat_settings['enabled'] = ($gchat_settings['enabled'] === 'true');
        }

        // Save settings
        update_option('spai_contact_form_monday_settings', $monday_settings);
        update_option('spai_contact_form_salespartner_settings', $salespartner_settings);
        update_option('spai_contact_form_chat_widget_settings', $chat_widget_settings);
        update_option('spai_contact_form_gchat_settings', $gchat_settings);

        // Clear chat widget status cache when SalesPartner settings change
        if (!empty($salespartner_settings['company_id'])) {
            delete_transient('spai_chat_widget_status_' . md5($salespartner_settings['company_id']));
        }

        wp_send_json_success(__('Settings saved successfully', 'spai-contact-form'));
    }
    
    /**
     * Ajax handler to save field mapping
     */
    public function ajax_save_field_mapping() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $monday_mapping = isset($_POST['monday_mapping']) ? $_POST['monday_mapping'] : array();
        
        // Save mapping
        update_option('spai_contact_form_monday_mapping', $monday_mapping);
        
        wp_send_json_success(__('Field mapping saved successfully', 'spai-contact-form'));
    }
    
    /**
     * Ajax handler to export form
     */
    public function ajax_export_form() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
        
        if (!$form_id) {
            wp_send_json_error(__('Invalid form ID.', 'spai-contact-form'));
        }
        
        $db_handler = new SPAI_DB_Handler();
        $form = $db_handler->get_form($form_id);
        
        if (!$form) {
            wp_send_json_error(__('Form not found.', 'spai-contact-form'));
        }
        
        // Prepare export data
        $export_data = array(
            'form_name' => $form->form_name,
            'form_fields' => json_decode($form->form_fields, true),
            'form_settings' => json_decode($form->form_settings, true),
            'exported_at' => current_time('mysql'),
            'version' => '1.0.0'
        );
        
        wp_send_json_success($export_data);
    }
    
    /**
     * Ajax handler to import form
     */
    public function ajax_import_form() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $form_data = isset($_POST['form_data']) ? $_POST['form_data'] : array();
        
        if (empty($form_data)) {
            wp_send_json_error(__('No form data provided.', 'spai-contact-form'));
        }
        
        // Basic structure check
        if (!isset($form_data['form_name']) || !isset($form_data['form_fields'])) {
            wp_send_json_error(__('Invalid form data structure.', 'spai-contact-form'));
        }
        
        // Validate field types compatibility
        $supported_field_types = array_keys(SPAI_Field_Manager::get_field_types());
        $unsupported_fields = array();
        
        foreach ($form_data['form_fields'] as $field) {
            if (!in_array($field['type'], $supported_field_types)) {
                $unsupported_fields[] = $field['type'];
            }
        }
        
        if (!empty($unsupported_fields)) {
            wp_send_json_error(
                sprintf(
                    __('Form contains unsupported field types: %s. Please update the plugin or remove these fields before importing.', 'spai-contact-form'),
                    implode(', ', array_unique($unsupported_fields))
                )
            );
        }
        
        // Add import suffix to form name to avoid conflicts
        $form_data['form_name'] = $form_data['form_name'] . ' (Imported ' . date('Y-m-d H:i') . ')';
        
        $db_handler = new SPAI_DB_Handler();
        $new_form_id = $db_handler->save_form($form_data);
        
        if ($new_form_id) {
            wp_send_json_success(array(
                'message' => __('Form imported successfully.', 'spai-contact-form'),
                'form_id' => $new_form_id,
                'edit_url' => admin_url('admin.php?page=spai-contact-form-new&form_id=' . $new_form_id)
            ));
        } else {
            wp_send_json_error(__('Failed to import form.', 'spai-contact-form'));
        }
    }
    
    /**
     * Ajax handler to test email (simple)
     */
    public function ajax_test_email() {
        check_ajax_referer('spai_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }

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

        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/notifications/class-spai-email-integration.php';
        $email = new SPAI_Email_Integration($settings);
        $result = $email->test_connection();

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['message']);
        }
    }

    /**
     * Ajax handler to send REAL test email with full template
     */
    public function ajax_send_real_test_email() {
        check_ajax_referer('spai_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }

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

        // Validate email
        $to_email = isset($test_data['to_email']) ? sanitize_email($test_data['to_email']) : '';
        if (empty($to_email) || !is_email($to_email)) {
            wp_send_json_error(__('Please enter a valid email address', 'spai-contact-form'));
        }

        // Build fake form data for the template
        $first_name = isset($test_data['first_name']) ? sanitize_text_field($test_data['first_name']) : 'Test';
        $test_attachment = isset($test_data['test_attachment_option']) ? sanitize_text_field($test_data['test_attachment_option']) : '';

        $form_data = array(
            'first_name' => $first_name,
            'last_name' => 'User',
            'email' => $to_email
        );

        // If testing with attachment, add the field value
        $has_attachment = false;
        if (!empty($test_attachment) && !empty($settings['attachment_field'])) {
            $form_data[$settings['attachment_field']] = $test_attachment;
            $has_attachment = true;
        }

        require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/notifications/class-spai-email-integration.php';
        $email = new SPAI_Email_Integration($settings);
        $result = $email->process_submission($form_data, array());

        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(__('Email sent to %s', 'spai-contact-form'), $to_email),
                'has_attachment' => $has_attachment
            ));
        } else {
            wp_send_json_error($result['error']);
        }
    }

    /**
     * Ajax handler to export all submissions
     */
    public function ajax_export_submissions() {
        check_ajax_referer('spai_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Unauthorized', 'spai-contact-form'));
        }
        
        $format = isset($_POST['format']) ? sanitize_text_field($_POST['format']) : 'json';
        
        $db_handler = new SPAI_DB_Handler();
        $submissions = $db_handler->get_all_submissions();
        
        if ($format === 'csv') {
            // Prepare CSV data
            $csv_data = array();
            
            // Build header row from all possible fields
            $all_fields = array('id', 'form_name', 'created_at');
            $submission_fields = array();
            
            // Collect all unique field names from submissions
            foreach ($submissions as $submission) {
                if (is_array($submission->submission_data)) {
                    foreach ($submission->submission_data as $key => $value) {
                        if (!in_array($key, $submission_fields)) {
                            $submission_fields[] = $key;
                        }
                    }
                }
            }
            
            $all_fields = array_merge($all_fields, $submission_fields, array('integration_status', 'ip_address', 'user_agent'));
            $csv_data[] = $all_fields;
            
            // Add data rows
            foreach ($submissions as $submission) {
                $row = array(
                    $submission->id,
                    $submission->form_name,
                    $submission->created_at
                );
                
                // Add submission data fields
                foreach ($submission_fields as $field) {
                    $value = isset($submission->submission_data[$field]) ? $submission->submission_data[$field] : '';
                    // Handle array values
                    if (is_array($value)) {
                        $value = implode(', ', $value);
                    }
                    $row[] = $value;
                }
                
                // Add integration status
                $status_text = '';
                if (is_array($submission->integration_status)) {
                    $statuses = array();
                    foreach ($submission->integration_status as $integration => $info) {
                        $statuses[] = $integration . ': ' . $info['status'];
                    }
                    $status_text = implode('; ', $statuses);
                }
                $row[] = $status_text;
                
                $row[] = $submission->ip_address;
                $row[] = $submission->user_agent;
                
                $csv_data[] = $row;
            }
            
            wp_send_json_success(array(
                'format' => 'csv',
                'data' => $csv_data,
                'filename' => 'spai-submissions-' . date('Y-m-d-His') . '.csv'
            ));
        } else {
            // JSON format
            $export_data = array(
                'plugin' => 'SPAI Contact Form',
                'version' => SPAI_CONTACT_FORM_VERSION,
                'exported_at' => current_time('mysql'),
                'total_submissions' => count($submissions),
                'submissions' => $submissions
            );
            
            wp_send_json_success(array(
                'format' => 'json',
                'data' => $export_data,
                'filename' => 'spai-submissions-' . date('Y-m-d-His') . '.json'
            ));
        }
    }
}
