<?php
if ( ! class_exists( 'AI_APP_ONSITE_Plugin_Settings_Handler' ) ) {
    class AI_APP_ONSITE_Plugin_Settings_Handler {
        public function __construct() {
            // Hook the AJAX action to the appropriate method in this class
            add_action( 'wp_ajax_ai_app_onsite_save_plugin_settings', array( $this, 'ai_app_onsite_save_plugin_settings_callback' ) );
            add_action( 'wp_ajax_nopriv_ai_app_onsite_save_plugin_settings', array( $this, 'ai_app_onsite_save_plugin_settings_callback' ) );

            add_action( 'wp_ajax_ai_app_onsite_get_plugin_settings', array( $this, 'ai_app_onsite_get_plugin_settings' ) );
            add_action( 'wp_ajax_nopriv_ai_app_onsite_get_plugin_settings', array( $this, 'ai_app_onsite_get_plugin_settings' ) );

            add_action( 'wp_ajax_ai_app_onsite_handle_csv_upload', array( $this, 'ai_app_onsite_handle_csv_upload_callback' ) );
            add_action( 'wp_ajax_nopriv_ai_app_onsite_handle_csv_upload', array( $this, 'ai_app_onsite_handle_csv_upload_callback' ) );

            add_action( 'wp_ajax_ai_app_onsite_get_accept_terms_of_service', array( $this, 'ai_app_onsite_get_accept_terms_of_service_callback' ) );
            add_action( 'wp_ajax_nopriv_ai_app_onsite_get_accept_terms_of_service', array( $this, 'ai_app_onsite_get_accept_terms_of_service_callback' ) );


        }

        public function ai_app_onsite_save_plugin_settings_callback() {
            global $wpdb; // Access the WordPress database object
            if ( 
                ! isset( $_POST['ai_app_onsite_plugin_settings_nonce_field'] ) || 
                ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ai_app_onsite_plugin_settings_nonce_field'] ) ), 'ai_app_onsite_plugin_settings_nonce' ) 
            ) {
                wp_send_json_error( 'Nonce verification failed.' );
            }

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

            // Extract individual settings values
            $agree_terms = isset($_POST['terms_of_service'] ) && $_POST['terms_of_service']  == true ? 1 : 0;
            $app_selector = isset( $_POST['app_selector'] ) ? sanitize_text_field( wp_unslash( $_POST['app_selector'] ) ) : '';
            $app_email = isset($_POST['app_email'] ) ? sanitize_text_field(wp_unslash($_POST['app_email']) ) : '';
            $banned_words = isset( $_POST['banned_words'] ) ? serialize( array_map( 'sanitize_text_field', wp_unslash( $_POST['banned_words'] ) ) ) : '';
            
            if ($app_selector == '') {
                $results = array('status' => '404', 'error' => 'App Name is required.');
                wp_send_json($results);
                exit;
            }else {
                $suffix = '_aiao';
                $max_length = 300;

                // Normalize spaces and trim
                $trimmed_value = trim(preg_replace('/\s+/', ' ', $app_selector));

                // Generate shortcode as PHP does
                $shortcode_preview = strtolower(str_replace(' ', '_', $trimmed_value)) . $suffix;

                // If shortcode exceeds limit, trim until valid
                if (strlen($shortcode_preview) > $max_length) {
                   $results = array('status' => '404', 'error' => 'The generated shortcode exceeds '.$max_length.' characters (' .
                    strlen($shortcode_preview) . ' chars generated). Please shorten the app name.');
                    wp_send_json($results);
                    exit;
                }
            }

            $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_data = array(
                    'agree_terms' => $agree_terms,
                    'app_selector' => $app_selector,
                    'app_email' => $app_email,
                    'banned_words' => $banned_words
                );

                // Conditionally include 'banned_words_csv' in the update data array
                // Include 'banned_words_csv' in the update data array if $serializedData is not empty
                if (!empty($serializedData)) {
                    $update_data['banned_words_csv'] = serialize($serializedData);
                } else {
                    
                    // If $serializedData is empty, reset 'banned_words_csv' to empty string
                    $update_data['banned_words_csv'] = $existing_settings->banned_words_csv;
                }
                // Update existing row
                $wpdb->update(
                    $table_name_settings,
                    $update_data,
                    array('id' => $existing_settings->id), // where clause: update based on the existing row's ID
                    array('%d', '%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 {
                    $table_app_properties = $wpdb->prefix . 'ai_app_onsite_app_properties';

                    $existing_app = $wpdb->get_row("SELECT * FROM $table_app_properties WHERE app_id = 1");
        
                    if ($existing_app) {
                        // Update the app name if it already exists
                        $wpdb->update(
                            $table_app_properties,
                            array(
                                'app_name' => $app_selector,
                            ),
                            array('app_id' => $existing_app->app_id),
                            array('%s'),
                            array('%d')
                        );
        
                        if ($wpdb->last_error) {
                            wp_send_json_error('Error updating app name: ' . $wpdb->last_error);
                        }
                    } else {
                        // Insert new app name if it doesn't exist
                        $wpdb->insert(
                            $table_app_properties,
                            array(
                                'app_id' => 1,
                                'app_name' => $app_selector,
                                'submit_button_txt' => 'Submit',
                            ),
                            array('%d', '%s', '%s')
                        );
        
                        if ($wpdb->last_error) {
                            wp_send_json_error('Error saving app name: ' . $wpdb->last_error);
                        }
                    }
                    // 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, 
                        'agree_terms' => $agree_terms,
                        'app_selector' => $app_selector,
                        'app_email' => $app_email,
                        'banned_words' => ' ',
                        'banned_words_csv' => ' '
                    ),
                    array('%d', '%d', '%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
                    $table_app_properties = $wpdb->prefix . 'ai_app_onsite_app_properties';

                    // Insert new app name into the app properties table
                    $wpdb->insert(
                        $table_app_properties,
                        array(
                            'app_id' => 1,
                            'app_name' => $app_selector,
                            'submit_button_txt' => 'Submit',
                        ),
                        array('%d', '%s', '%s')
                    );

                    if ($wpdb->last_error) {
                        wp_send_json_error('Error saving app name: ' . $wpdb->last_error);
                    }
                    wp_send_json_success('Settings saved successfully.');
                }
            }
            
        }

        function ai_app_onsite_get_plugin_settings() {
            
            global $wpdb;
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_plugin_settings';
            $table_app_name = $wpdb->prefix . 'ai_app_onsite_app_properties';

            // 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();
            }

            $getAppName = $wpdb->get_results("SELECT * FROM $table_app_name WHERE app_id = 1", ARRAY_A);

            $appName = isset($getAppName[0]['app_name_show']) && !empty($getAppName[0]['app_name_show']) 
                ? $getAppName[0]['app_name_show'] 
                : (isset($getAppName[0]['app_name']) ? $getAppName[0]['app_name'] : '');
            
            // Fetch the data
            $results = $wpdb->get_results("SELECT * FROM $table_name_settings WHERE app_id = 1", ARRAY_A);

            //  Create a mapping of app IDs to app names
            $appNameMapping = [];
            // Unserialize 'banned_words_csv' before sending response
                foreach ($results as &$row) {
                    if (!empty($appName)) {
                        $row['appName'] = $appName;
                    }
                    $banned_words_raw = $row['banned_words_csv'] ?? '';

                    if (is_string($banned_words_raw) && $banned_words_raw !== '' && is_serialized($banned_words_raw)) {
                        $unserializedDataCsv = unserialize($banned_words_raw);
                    } else {
                        $unserializedDataCsv = [];
                    }
                    $unserializedData = unserialize($row['banned_words']);
                        if ($unserializedDataCsv !== false) {
                            foreach ($unserializedDataCsv as &$value) {
                                $value = unserialize($value);
                            }
                            $row['banned_words_csv'] = $unserializedDataCsv;
                        } else {
                            $row['banned_words_csv'] = array(); // Set it to an empty array if unserialization failed
                        }
                        if ($unserializedData !== false) {
                            $row['banned_words'] = $unserializedData;
                        } else {
                            $row['banned_words'] = array(); // Set it to an empty array if unserialization failed
                        }
                }
                $results_with_keys = array(
                    'result' => $results,
                    'tos_current_version' => AI_APP_ONSITE_TOS_VERSION,
                    'tos_accepted_version' => get_option('ai_app_onsite_accepted_tos_version')
                );

                wp_send_json($results_with_keys);
                exit;
        }

        public function ai_app_onsite_handle_csv_upload_callback() {
            global $wpdb;
            if ( 
                ! isset( $_POST['ai_app_onsite_plugin_settings_nonce_csv_upload_field'] ) || 
                ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ai_app_onsite_plugin_settings_nonce_csv_upload_field'] ) ), 'ai_app_onsite_plugin_settings_nonce' ) 
            ) {
                wp_send_json_error( 'Nonce verification failed.' );
            }
           $table_name_settings = $wpdb->prefix . 'ai_app_onsite_plugin_settings';
           if ( isset( $_FILES['csv-file'] ) && ! empty( $_FILES['csv-file']['name'] ) ) {
               global $wp_filesystem;

               // Ensure WP_Filesystem is initialized
               if ( empty( $wp_filesystem ) ) {
                   require_once( ABSPATH . 'wp-admin/includes/file.php' );
                   WP_Filesystem();
               }

               $serializedData = array();
               $upload_overrides = array( 'test_form' => false );
               $movefile = wp_handle_upload( $_FILES['csv-file'], $upload_overrides );
               
               if ( $movefile && ! isset( $movefile['error'] ) ) {
                   // Get the file path on the server
                   $file_path = $movefile['file']; // This is the local file path after upload

                   // Check if the file exists
                   if ( file_exists( $file_path ) ) {
                       // Read the file content using WP_Filesystem
                       $file_contents = $wp_filesystem->get_contents( $file_path );

                       // Ensure the file contents were fetched successfully
                       if ( $file_contents !== false ) {
                           // Split the contents into lines (assuming it's a CSV)
                           $lines = explode("\n", $file_contents);

                           // Loop through each line and process the CSV data
                           foreach ( $lines as $line ) {
                               $data = str_getcsv($line); // Parse each line as CSV
                               if (!empty($data)) {
                                   $serializedData[] = serialize($data); // Serialize and store the data
                               }
                           }
                       } else {
                           wp_send_json_error( 'Error reading the uploaded file' );
                       }
                   } else {
                       wp_send_json_error( 'File does not exist' );
                   }
               } else {
                   wp_send_json_error( 'Error uploading file: ' . $movefile['error'] );
               }

                   $existing_settings = $wpdb->get_row("SELECT * FROM $table_name_settings WHERE app_id = 1");
                   if ($existing_settings) {
                       if (!empty($serializedData)) {
                           $update_data['banned_words_csv'] = serialize($serializedData);
                       } else {
                           $update_data['banned_words_csv'] = $existing_settings->banned_words_csv;
                       }
                       $wpdb->update(
                           $table_name_settings,
                           $update_data,
                           array('id' => $existing_settings->id), // where clause: update based on the existing row's ID
                           array('%s'),
                           array('%d') // where format
                       );
                           if ($wpdb->last_error) {
                               wp_send_json_error('Error updating data: ' . $wpdb->last_error);
                           } else {
                               // Return success message for update
                               wp_send_json_success('CSV upload successfully.');
                           }
                   } else {
                          $wpdb->insert(
                               $table_name_settings,
                               array(
                                   'app_id'   => 1, 
                                   'agree_terms' => '',
                                   'app_selector' => '',
                                   'banned_words' => '',
                                   'banned_words_csv' => serialize($serializedData)
                               ),
                               array('%d', '%d', '%s', '%s' , '%s')
                           );
                           if ($wpdb->last_error) {
                               wp_send_json_error('Error saving data: ' . $wpdb->last_error);
                           } else {
                               wp_send_json_success('CSV upload successfully.');
                           }
                   }
           }

        }       

        public function ai_app_onsite_get_accept_terms_of_service_callback() {
            global $wpdb;
            if ( 
                ! isset( $_POST['ai_app_onsite_plugin_settings_terms_of_service_nonce'] ) || 
                ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ai_app_onsite_plugin_settings_terms_of_service_nonce'] ) ), 'ai_app_onsite_plugin_settings_nonce' ) 
            ) {
                wp_send_json_error( 'Nonce verification failed.' );
            }
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_plugin_settings';   

            $checked = ($_POST['terms_of_service'] == "true") ? 1 : 0;

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

            if ($existing_settings) {
                $update_data = array(
                    'agree_terms' => $checked
                );
                $where = array('id' => $existing_settings->id);

                $wpdb->update(
                    $table_name_settings,
                    $update_data,
                    $where,
                    array('%d'), // data format
                    array('%d') // where format
                );

                if ($wpdb->last_error) {
                    wp_send_json_error('Error updating data: ' . $wpdb->last_error);
                } else {
                    if ($checked) {
                        // Update the version of the Terms of Service
                        aiapp_set_option('ai_app_onsite_accepted_tos_version', AI_APP_ONSITE_TOS_VERSION);
                    }
                    wp_send_json_success('Terms of Service updated successfully.');
                }
            } else {
                $insert_data = array(
                    'app_id' => 1,
                    'agree_terms' => $checked,
                    'app_selector' => '',
                    'banned_words' => '',
                    'banned_words_csv' => ''
                );

                $wpdb->insert(
                    $table_name_settings,
                    $insert_data,
                    array('%d', '%d', '%s', '%s', '%s') // data format
                );

                if ($wpdb->last_error) {
                    wp_send_json_error('Error saving data: ' . $wpdb->last_error);
                } else {
                    if ($checked) {
                        // Update the version of the Terms of Service
                        aiapp_set_option('ai_app_onsite_accepted_tos_version', AI_APP_ONSITE_TOS_VERSION);
                    }
                    wp_send_json_success('Terms of Service saved successfully.');
                }
            }
        }
    }

    new AI_APP_ONSITE_Plugin_Settings_Handler(); // Instantiate the class
}

