<?php

if( ! class_exists( 'ChatGPT_Assistant_Embedding_DB_Actions' ) ){
	ob_start();

	/**
	 * Class ChatGPT_Assistant_Settings_DB_Actions
	 * Class contains functions to interact with settings database
	 *
	 * Main functionality belong to inserting, updating and deleting
	 *
	 * Hooks used in the class
	 * @hooks           @filters        ays_chatgpt_assistant_item_save_settings
	 *
	 * Database tables without prefixes
	 * @tables          settings
	 *
	 * @param           $plugin_name
	 *
	 * @since           1.0.0
	 * @package         Ays_Chatgpt_Assistant
 	 * @subpackage      Ays_Chatgpt_Assistant/includes
 	 * @author          Ays_ChatGPT Assistant Team <info@ays-pro.com>
	 */
    class ChatGPT_Assistant_Embedding_DB_Actions extends ChatGPT_Assistant_Main_DB_Actions {
		public function store_data(){
            if( isset( $_REQUEST["embedding_action"] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST["embedding_action"] ) ), 'embedding_action' ) && current_user_can( 'manage_options' ) ){
                // $success = 0;
                // $name_prefix = 'ays_';
				
				$settings = array();

				// == Sanitize in the loop all values except checkboxes, radios (only for settings array). The latter sanitize separately (out of loop) ==				
                if( isset( $_REQUEST[ CHATGPT_ASSISTANT_NAME_PREFIX . '_settings' ] ) && !empty( $_REQUEST[ CHATGPT_ASSISTANT_NAME_PREFIX . '_settings' ] )) {
					foreach($_REQUEST[ CHATGPT_ASSISTANT_NAME_PREFIX . '_settings' ] as $each_setting_key => $each_setting_value){
						if(is_array($each_setting_value)){
							$settings[$each_setting_key] = json_encode($each_setting_value);
						}
						else{
							$each_setting_value = isset($each_setting_value) && $each_setting_value != '' ? sanitize_text_field($each_setting_value) : '';
							$each_setting_key   = isset($each_setting_key) && $each_setting_key != '' ? sanitize_text_field($each_setting_key) : '';
							$settings[$each_setting_key] = $each_setting_value;
						}
                    }
                }
				
				// == Sanitize checkboxes, radios, selects here ==
				$settings['enable_embedding'] = ( isset( $settings['enable_embedding'] ) && $settings['enable_embedding'] != '' ) ? sanitize_text_field($settings['enable_embedding']) : 'off';

				if( is_array( $settings ) && ! empty( $settings ) ){
					foreach ( $settings as $meta_key => $meta_value ){
						if( $this->get_setting( $meta_key , 'id' ) ) {
							$this->update_setting($meta_key, $meta_value );
						}else{
							$this->add_setting( $meta_key, $meta_value );
						}
					}
				}

                $message = "saved";
                // if($success > 0){
                    $url = admin_url('admin.php') . '?page=' . $this->plugin_name .'-embedding' . '&status=' . $message;
                    wp_redirect( $url );
                    exit();
                // }
            }

        }
    }
}
