<?php
if (! class_exists('AI_APP_ONSITE_Prompt_Editor_Handler')) {
    class AI_APP_ONSITE_Prompt_Editor_Handler
    {
        public function __construct()
        {
            // Read callback
            add_action('wp_ajax_ai_app_onsite_get_field_tags', array($this, 'ai_app_onsite_get_field_tags'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_field_tags', array($this, 'ai_app_onsite_get_field_tags'));

            add_action('wp_ajax_ai_app_onsite_get_Model_Token_field', array($this, 'ai_app_onsite_get_Model_Token_field'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_Model_Token_field', array($this, 'ai_app_onsite_get_Model_Token_field'));

            add_action('wp_ajax_ai_app_onsite_save_prompt_editor', array($this, 'ai_app_onstie_save_prompt_editor_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_save_prompt_editor', array($this, 'ai_app_onstie_save_prompt_editor_callback'));

            add_action('wp_ajax_ai_app_onsite_get_prompt_editor', array($this, 'ai_app_onsite_get_prompt_editor'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_prompt_editor', array($this, 'ai_app_onsite_get_prompt_editor'));
        }

        public function get_quill_allowed_html() {
            return [
                'h1' => ['class' => true, 'style' => true],
                'h2' => ['class' => true, 'style' => true],
                'p' => ['class' => true, 'style' => true],
                'span' => ['class' => true, 'style' => true],
                'strong' => ['class' => true, 'style' => true],
                'em' => ['class' => true, 'style' => true],
                'u' => ['class' => true, 'style' => true],
                's' => ['class' => true, 'style' => true],
                'a' => ['href' => true, 'target' => true, 'rel' => true, 'style' => true, 'class' => true],
                'ul' => ['class' => true, 'style' => true],
                'ol' => ['class' => true, 'style' => true],
                'li' => ['class' => true, 'style' => true],
                'blockquote' => ['class' => true, 'style' => true],
                'div' => ['class' => true, 'style' => true],
                'br' => [],
            ];
        }

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

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

            // Extract individual settings values
            $prompt            = isset($_POST['prompt']) ? wp_unslash($_POST['prompt']) : '';
            $ai_response_style = isset($_POST['ai_response_style']) ? sanitize_text_field(wp_unslash($_POST['ai_response_style'])) : '';
            $ai_response_tone = isset($_POST['ai_response_tone']) ? sanitize_text_field(wp_unslash($_POST['ai_response_tone'])) : '';
            $eg_ai_output = isset($_POST['eg_ai_output']) ? sanitize_text_field(wp_unslash($_POST['eg_ai_output'])) : '';


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

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

            // If settings already exist, update the row; otherwise, insert a new row
            if ($existing_settings) {
                // Update existing row
                $wpdb->update(
                    $table_name_settings,
                    array(
                        'prompt'            => wp_strip_all_tags($prompt),
                        'prompt_html'       => $prompt,
                        'ai_response_style' => $ai_response_style,
                        'ai_response_tone'  => $ai_response_tone,
                        'eg_ai_output'      => $eg_ai_output,
                    ),
                    array('id' => $existing_settings->id), // where clause: update based on the existing row's ID
                    array('%s', '%s', '%s', '%s', '%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,
                        'prompt'            => wp_strip_all_tags($prompt),
                        'prompt_html'       => $prompt,
                        'ai_response_style' => $ai_response_style,
                        'ai_response_tone'  => $ai_response_tone,
                        'eg_ai_output'      => $eg_ai_output,
                    ),
                    array('%d', '%s', '%s', '%s', '%s', '%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 static function ai_app_onsite_get_field_tags()
        {

            global $wpdb;
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';

            // Check if the table exists
            if ($wpdb->get_var("SHOW TABLES LIKE '$table_name_settings'") != $table_name_settings) {
                die('Table does not exist.');
            }

            // Check if the table has rows
            $rows_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name_settings WHERE app_id = 1");
            if ($rows_count == 0) {
                $results = array('status' => '404',  'message' => 'No rows found in the table.');

                // Return the data
                wp_send_json($results);

                die();
            }

            // Fetch the data
            $results = $wpdb->get_results("SELECT field_tag FROM $table_name_settings WHERE app_id = 1", ARRAY_A);

            // Return the data
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }

        public static function ai_app_onsite_get_Model_Token_field()
        {

            global $wpdb;
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_model_settings';

            // Check if the table exists
            if ($wpdb->get_var("SHOW TABLES LIKE '$table_name_settings'") != $table_name_settings) {
                die('Table does not exist.');
            }

            // Check if the table has rows
            $rows_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name_settings WHERE app_id = 1");
            if ($rows_count == 0) {
                $results = array('status' => '404',  'message' => 'No rows found in the table.');

                // Return the data
                wp_send_json($results);

                die();
            }

            // Fetch the data
            $results = $wpdb->get_results("SELECT * FROM $table_name_settings WHERE app_id = 1", ARRAY_A);

            // Return the data
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }

        public static function ai_app_onsite_get_prompt_editor()
        {
            global $wpdb;
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_prompt_editor';

            // Check if the table exists
            if ($wpdb->get_var("SHOW TABLES LIKE '$table_name_settings'") != $table_name_settings) {
                die('Table does not exist.');
            }

            // Check if the table has rows
            $rows_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name_settings WHERE app_id = 1");
            if ($rows_count == 0) {

                $results = array('status' => '404',  'message' => 'No rows found in the table.');

                // Return the data
                wp_send_json($results);

                die();
            }

            // Fetch the data
            $results = $wpdb->get_results("SELECT * FROM $table_name_settings WHERE app_id = 1", ARRAY_A);

            // Return the data
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }
    }

    new AI_APP_ONSITE_Prompt_Editor_Handler(); // Instantiate the class
}
