<?php

if (! class_exists('AI_App_Onsite_Email_Settings_Handler')) {
    class AI_App_Onsite_Email_Settings_Handler
    {

        public function __construct()
        {
            // Hook the AJAX action to the appropriate method in this class
            add_action('wp_ajax_ai_app_onsite_save_email_setting', array($this, 'ai_app_onsite_save_email_setting_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_save_email_setting', array($this, 'ai_app_onsite_save_email_setting_callback'));


            add_action('wp_ajax_ai_app_onsite_get_email_settings', array($this, 'ai_app_onsite_get_email_settings'));
            // add_action( 'wp_ajax_nopriv_ai_app_onsite_email_webhook_settings', array( $this, 'ai_app_onsite_email_email_settings' ) );
        }

        // Public method to handle AJAX callback
        public function ai_app_onsite_save_email_setting_callback()
        {
            global $wpdb; // Access the WordPress database object


            // Verify nonce
            if (! isset($_POST['ai_app_onsite_email_settings_nonce_field']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_email_settings_nonce_field'])), 'ai_app_onsite_email_settings_nonce')) {
                wp_send_json_error('Nonce verification failed.');
            }


            // Extract individual settings values
            $email_enabled = isset($_POST['email_enabled']) && $_POST['email_enabled'] == 'true' ? 1 : 0;
            $email_address = isset($_POST['email_address']) ? sanitize_email(wp_unslash($_POST['email_address'])) : '';

            // Check if settings already exist in the database
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_email_setting';

            $existing_settings = $wpdb->get_row("SELECT * FROM $table_name_settings WHERE app_id = 1");

            // If settings already exist, update the row; otherwise, insert a new row
            if ($existing_settings) {
                // Update existing row
                $wpdb->update(
                    $table_name_settings,
                    array(
                        'email_enable' => $email_enabled,
                        'email_address' => $email_address
                    ),
                    array('app_id' => 1), // where clause: update based on the app_id
                    array('%d', '%s'),
                    array('%d') // where format
                );

                // Check if the database operation was successful
                if ($wpdb->last_error) {
                    wp_send_json_error('Error updating data: ' . $wpdb->last_error);
                } else {
                    // Return success message for update
                    wp_send_json_success('Settings updated successfully.');
                }
            } else {
                // Insert new row
                $wpdb->insert(
                    $table_name_settings,
                    array(
                        'app_id'   => 1,
                        'email_enable' => $email_enabled,
                        'email_address' => $email_address
                    ),
                    array('%d', '%d', '%s')
                );

                // Check if the database operation was successful
                if ($wpdb->last_error) {
                    wp_send_json_error('Error saving data: ' . $wpdb->last_error);
                } else {
                    // Return success message for insert
                    wp_send_json_success('Settings saved successfully.');
                }
            }
        }

        // Public method to handle AJAX callback for fetching settings
        public function ai_app_onsite_get_email_setting()
        {
            echo "email_setting";
            die();
        }
    }

    new AI_App_Onsite_Email_Settings_Handler(); // Instantiate the class
}
