<?php
if (! class_exists('AI_APP_ONSITE_Model_Settings_Handler')) {
    class AI_APP_ONSITE_Model_Settings_Handler
    {
        public function __construct()
        {
            // Hook the AJAX action to the appropriate method in this class

            // // Ajax handler
            add_action('wp_ajax_ai_app_onsite_save_model_settings', array($this, 'ai_app_onsite_save_model_settings_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_save_model_settings', array($this, 'ai_app_onsite_save_model_settings_callback'));

            add_action('wp_ajax_ai_app_onsite_get_model_settings', array($this, 'ai_app_onsite_get_model_settings'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_model_settings', array($this, 'ai_app_onsite_get_model_settings'));

            add_action('wp_ajax_ai_app_onsite_get_model_list', array($this, 'ai_app_onsite_get_model_list'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_model_list', array($this, 'ai_app_onsite_get_model_list'));

            add_action('wp_ajax_ai_app_onsite_save_openai_key', array($this, 'ai_app_onsite_save_openai_key_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_save_openai_key', array($this, 'ai_app_onsite_save_openai_key_callback'));

            add_action('wp_ajax_ai_app_onsite_get_openapi_data', array($this, 'ai_app_onsite_get_openapi_data'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_openapi_data', array($this, 'ai_app_onsite_get_openapi_data'));
        }

        function ai_app_onsite_save_model_settings_callback()
        {
            global $wpdb;

            //Verify if the request came via AJAX
            if (
                ! isset($_POST['action']) ||
                sanitize_text_field(wp_unslash($_POST['action'])) !== 'ai_app_onsite_save_model_settings' ||
                ! isset($_POST['ai_app_onsite_model_settings_nonce_field']) || // Check if the nonce field is set
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_model_settings_nonce_field'])), 'ai_app_onsite_model_settings_nonce')
            ) {
                wp_send_json_error('Unauthorized request');
            }


            // Extract individual settings values  openai-iv
            $model       = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
            $max_tokens  = isset($_POST['max-tokens']) ? sanitize_text_field(wp_unslash($_POST['max-tokens'])) : '';
            $temperature = isset($_POST['temperature']) ? sanitize_text_field(wp_unslash($_POST['temperature'])) : '';
            $top_p       = isset($_POST['top-p']) ? floatval(sanitize_text_field(wp_unslash($_POST['top-p']))) : 0;
            $f_penalty   = isset($_POST['f-penalty']) ? sanitize_text_field(wp_unslash($_POST['f-penalty'])) : '';
            $p_penalty   = isset($_POST['p-penalty']) ? sanitize_text_field(wp_unslash($_POST['p-penalty'])) : '';


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

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

            if ($existing_settings) {

                $wpdb->update(
                    $table_name_settings,
                    array(
                        'model'       => $model,
                        'temperature' => $temperature,
                        'f_penalty'   => $f_penalty,
                        'p_penalty'   => $p_penalty,
                        'max_tokens'  => $max_tokens,
                        'top_p'       => $top_p

                    ),
                    array('id' => $existing_settings->id),
                    array('%s', '%f', '%f', '%f', '%d', '%f'),
                );
                $existing_settings = $wpdb->get_row("SELECT * FROM $table_name_settings WHERE app_id = 1");

                // Check if the database operation was successful
                if ($wpdb->last_error) {
                    wp_send_json_error('Error updating data: ' . $wpdb->last_error);
                } else {
                    $results = array('status' => '200',  'message' => 'Settings saved successfully', 'data' => $existing_settings);
                    // Return success message for insert
                    wp_send_json_success($results);
                }
            } else {
                // Insert new row
                $wpdb->insert(
                    $table_name_settings,
                    array(
                        'app_id'      => 1,
                        'model'       => $model,
                        'temperature' => $temperature,
                        'f_penalty'   => $f_penalty,
                        'p_penalty'   => $p_penalty,
                        'max_tokens'  => $max_tokens,
                        'top_p'       => $top_p
                    ),
                    array('%d', '%s', '%d', '%d', '%d', '%d', '%d')
                );
            }
            $existing_settings = $wpdb->get_row("SELECT * FROM $table_name_settings WHERE app_id = 1");

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

        function ai_app_onsite_get_model_list() 
        {
            global $wpdb;
            $table_name_models = $wpdb->prefix . 'ai_app_onsite_models';

            $models_data = $wpdb->get_results(
            "SELECT category, model, supported_parameters, endpoint, description 
             FROM $table_name_models 
             ORDER BY category, model ASC",
            ARRAY_A
            );

            if (empty($models_data)) {
            return [];
            }

            $grouped_models = [];
            foreach ($models_data as $model) {
            $cat = $model['category'];
            if (!isset($grouped_models[$cat])) {
                $grouped_models[$cat] = [];
            }
            $grouped_models[$cat][] = [
                'model' => $model['model'],
                'supported_parameters' => json_decode($model['supported_parameters'], true),
                'endpoint' => $model['endpoint'],
                'description' => $model['description']
            ];
            }

            return $grouped_models;
        }

        function ai_app_onsite_get_model_settings()
        {
            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.');
            }

            // Get the models list
            $models_list = $this->ai_app_onsite_get_model_list();

            // 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.', 'models_list' => $models_list);
                // 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);

            // add models list to results
            $results[0]['models_list'] = $models_list; 
                
            // Return the data
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }


        function ai_app_onsite_get_openapi_data()
        {

            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");
            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 openai_key, key_status FROM $table_name_settings WHERE app_id = 1", ARRAY_A);

            // Return the data
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }


        function ai_app_onsite_save_openai_key_callback()
        {
            global $wpdb;

            if (
                ! isset($_POST['action']) ||
                ! isset($_POST['api_Key_nonce']) || // Check if the nonce field is set
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['api_Key_nonce'])), 'ai_app_onsite_model_settings_nonce')
            ) {
                wp_send_json_error('Invalid nonce. Please refresh the page and try again.');
                return;
            }
            // Extract individual settings values  openai-iv
            $openai_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';
            $api_status = isset($_POST['api_status']) ? sanitize_text_field(wp_unslash($_POST['api_status'])) : '';
    
            $engine_model      = isset($_POST['engine_model']) ? sanitize_text_field(wp_unslash($_POST['engine_model'])) : '';




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

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

            if ($existing_settings) {
                $wpdb->update(
                    $table_name_settings,
                    array(
                        'openai_key' => $openai_key,
                        'key_status' => $api_status,


                    ),
                    array('id' => $existing_settings->id),
                    array('%s', '%s'),
                );
                // 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,
                        'openai_key'  => $openai_key,
                        'key_status'  => $api_status,
                        'model'       => $engine_model,
                        'temperature' => '0.7',
                        'f_penalty'   => '0',
                        'p_penalty'   => '0',
                        'max_tokens'  => '3000',
                        'top_p'       => '1',
                    ),
                    array('%d', '%s', '%s', '%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.');
                }
            }
        }
    }

    new AI_APP_ONSITE_Model_Settings_Handler(); // Instantiate the class
}
