<?php
if (! class_exists('AI_APP_ONSITE_Field_Selector_Handler')) {

    class AI_APP_ONSITE_Field_Selector_Handler
    {

        public function __construct()
        {

            // Save callback
            add_action('wp_ajax_ai_app_onsite_save_field_selector', array($this, 'ai_app_onsite_save_field_selector_callback'));

            add_action('wp_ajax_nopriv_ai_app_onsite_save_field_selector', array($this, 'ai_app_onsite_save_field_selector_callback'));

            // Read callback
            add_action('wp_ajax_ai_app_onsite_read_field_selector', array($this, 'ai_app_onsite_read_field_selector_callback'));

            add_action('wp_ajax_nopriv_ai_app_onsite_read_field_selector', array($this, 'ai_app_onsite_read_field_selector_callback'));

            // Delete callback
            add_action('wp_ajax_ai_app_onsite_delete_field_selector', array($this, 'ai_app_onsite_delete_field_selector_callback'));

            add_action('wp_ajax_nopriv_ai_app_onsite_delete_field_selector', array($this, 'ai_app_onsite_delete_field_selector_callback'));

            add_action('wp_ajax_ai_app_onsite_drag_data_save_database', array($this, 'ai_app_onsite_drag_data_save_database_callback'));

            add_action('wp_ajax_nopriv_ai_app_onsite_drag_data_save_database', array($this, 'ai_app_onsite_drag_data_save_database_callback'));
        }

        // Public method to handle AJAX callback
        public function ai_app_onsite_save_field_selector_callback()
        {

            global $wpdb; // Access the WordPress database object

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


            // Extract form data
            $form_data_array = isset($_POST['form_data_array']) ? sanitize_text_field(wp_unslash($_POST['form_data_array'])) : '';
            $form_data_array = json_decode($form_data_array, true);

            // Table name for field selector settings
            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';

            $max_field_option = $wpdb->get_var("SELECT MAX(field_position) FROM $table_name_settings WHERE app_id = 1");

            // Iterate through form data and insert/update settings
            foreach ($form_data_array as $index => $formData) {

                // Check if settings already exist for this field
                $existing_settings = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name_settings WHERE field_uniqueid = %s", $formData['field_uniqueid']));

                // echo 'existing_settings = {{'.$formData['field_label'].'}}';

                $field_label = $formData['field_label'];


                // Replace underscores with spaces
                $field_label = str_replace(' ', '_', $field_label);
                // Convert the first letter to lowercase
                $field_label = strtolower($field_label);
                // Enclose the key in curly braces
               
                $field_id = $formData['field_id'];

                $replaceField_id = str_replace(' ', '-', $field_id);
                // Convert the first letter to lowercase
                $formField_id = strtolower($replaceField_id);
                $field_tag = '{{' . $formField_id . '}}';

                if (isset($formData['field_dropdown_options'])) {
                    // Split the string into an array using '|' as a delimiter
                    $field_dropdown_options = explode('|', $formData['field_dropdown_options']);
                } else {
                    $field_dropdown_options = [];
                }

                // Serialize the array to store in the database
                $field_dropdown_options = serialize($field_dropdown_options);


                $field_position = isset($formData['field_order']) ? (int) $formData['field_order'] : (int) $index;

                // If settings already exist, update the row; otherwise, insert a new row
                if ($existing_settings) {
                    // Prepare data for update 
                    $update_data = array(
                        'app_id' => 1, // Adjust as necessary
                        'field_uniqueid' => $formData['field_uniqueid'],
                        'field_id' => $formField_id,
                        'app_width' => $formData['app_width_figure'],
                        'field_type' => $formData['field_creator'],
                        'field_label' => $formData['field_label'],
                        'field_maxchar' => $formData['field_maxchar'],
                        'field_dropdown_options' => $field_dropdown_options,
                        'field_sample_text' => $formData['field_creator'] == 'dropdown' ? '' : $formData['field_sample_text'],
                        'field_require_field_status' => $formData['section_required'] ? 1 : 0,
                        'field_include_in_export_email' => $formData['include_in_email'] ? 1 : 0,
                        'field_position' => $field_position,
                        'field_tag' => $field_tag,
                        // 'created_at' => current_time('mysql'),
                        'updated_at' => gmdate("Y-m-d H:i:s")
                    );

                    if ($existing_settings->field_tag !== $field_tag) {
                        // Update references in prompt editor table (only prompt and prompt_html columns)
                        $this->update_prompt_references('prompt', $existing_settings->field_tag, $field_tag, 1);
                        $this->update_prompt_references('prompt_html', $existing_settings->field_tag, $field_tag, 1);
                    }


                    // Update existing row
                    $wpdb->update(
                        $table_name_settings,
                        $update_data,
                        array('id' => $existing_settings->id),
                        array('%d', '%s', '%s',  '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s'),
                        array('%d') // where format
                    );
                } else {

                    $field_position = isset($formData['field_order']) ? (int) $formData['field_order'] : ((int) $max_field_option + 1);


                    // Prepare data for insertion
                    $create_data = array(
                        'app_id' => 1, // Adjust as necessary
                        'field_uniqueid' => $formData['field_uniqueid'],
                        'field_id' => $formData['field_id'],
                        'app_width' => $formData['app_width_figure'],
                        'field_type' => $formData['field_creator'],
                        'field_label' => $formData['field_label'],
                        'field_maxchar' => $formData['field_maxchar'],
                        'field_dropdown_options' => $field_dropdown_options,
                        'field_sample_text' => $formData['field_creator'] == 'dropdown' ? '' : $formData['field_sample_text'],
                        'field_require_field_status' => $formData['section_required'] ? 1 : 0,
                        'field_include_in_export_email' => $formData['include_in_email'] ? 1 : 0,
                        'field_position' => $field_position,
                        'field_tag' => $field_tag,
                        'created_at' => gmdate("Y-m-d H:i:s"),
                        'updated_at' => gmdate("Y-m-d H:i:s")
                    );

                    // Insert new row
                    $wpdb->insert(
                        $table_name_settings,
                        $create_data,
                        array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s')
                    );
                }

                // Check if the database operation was successful
                if ($wpdb->last_error) {
                    wp_send_json_error('Error savingdf data: ' . $wpdb->last_error);
                }
            }

            // If reached here, data saved successfully
            wp_send_json_success('Settings saved successfully.');
        }

        /**
         * Update references of an old field tag to a new one inside the prompt editor table.
         *
         * @param string $column       The column name to update ('prompt' or 'prompt_html').
         * @param string $current      The current field tag value (e.g., '{{old-tag}}').
         * @param string $expected     The new field tag value (e.g., '{{new-tag}}').
         * @param int    $app_id       The app ID for scoping the update.
         * @return int|false           Number of rows affected, or false on error.
         */
        public function update_prompt_references($column, $current, $expected, $app_id = 1) {
            global $wpdb;

            // Ensure the table name is accessible from the class
            $table_name_prompt_editor = $this->table_name_prompt_editor ?? $wpdb->prefix . 'ai_app_onsite_prompt_editor';

            // Validate column name to prevent SQL injection
            $allowed_columns = ['prompt', 'prompt_html'];
            if (!in_array($column, $allowed_columns, true)) {
                return false; // invalid column
            }

            // Prepare safe LIKE pattern
            $like = '%' . $wpdb->esc_like($current) . '%';

            // Build and execute the query
            $sql = $wpdb->prepare(
                "UPDATE {$table_name_prompt_editor}
                SET {$column} = REPLACE(COALESCE({$column}, ''), %s, %s)
                WHERE {$column} LIKE %s AND app_id = %d",
                $current,
                $expected,
                $like,
                (int) $app_id
            );

            return $wpdb->query($sql);
        }


        public function ai_app_onsite_read_field_selector_callback()
        {
            global $wpdb;

            $table_name = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';
            $table_name_prompt_editor   = $wpdb->prefix . 'ai_app_onsite_prompt_editor';

            // Fetch data from the database
            $results = $wpdb->get_results("SELECT * FROM $table_name WHERE app_id = 1 ORDER BY field_position ASC", ARRAY_A);


            // HTML content string to store the generated HTML
            $html_content = '';

            // Loop through each record and generate HTML content
            $ctr = 0;

            $app_width = $results[0]['app_width'] ?? '70';


            foreach ($results as $record) {
                // Sync the field tag value in the database
                $field_id  = strtolower(str_replace(' ', '-', trim($record['field_id'])));
                $expected  = '{{' . $field_id . '}}';
                $current   = trim($record['field_tag']);

                if ($current !== $expected) {
                    $wpdb->update(
                        $table_name,
                        ['field_tag' => $expected],
                        ['id' => (int) $record['id']]
                    );

                    // 2) Update references in prompt editor table (only prompt and prompt_html columns)
                    $this->update_prompt_references('prompt', $current, $expected, 1);
                    $this->update_prompt_references('prompt_html', $current, $expected, 1);
                }

                $html_content .= '
                    <div class="form-group ui-state-default" field_order="' . $ctr . '">
                        <div class="field-row top">
                            <div class="col-ai-3">
                                <label class="d-block fs-medium-14 mb-only-4 form-label">Type <span class="mk-red">*</span></label>';
                $html_content .= '
                                <select class="border" id="filed_creator_' . $ctr . '" onchange="createDropdown(' . $ctr . ')">
                                    <option value="textbox"' . ($record['field_type'] == 'textbox' ? 'selected' : '') . '>Textbox</option>
                                    <option value="textarea" ' . ($record['field_type'] == 'textarea' ? 'selected' : '') . '>Textarea</option>
                                    <option value="number" ' . ($record['field_type'] == 'number' ? 'selected' : '') . '>Number</option>
                                    <option value="email" ' . ($record['field_type'] == 'email' ? 'selected' : '') . '>Email</option>
                                    <option value="dropdown" ' . ($record['field_type'] == 'dropdown' ? 'selected' : '') . '>Drop-down</option>
                                </select>';

                $html_content .= '<p id="filed_creator_' . $ctr . '_error" class="fields-error"></p>';

                $html_content .= '<input type="hidden" id="field_unique_id_' . $ctr . '" value="' . $record['field_uniqueid'] . '">
                            </div>
                            <div class="col-ai-4">
                                <label for="text-area" class="d-block fs-medium-14 mb-only-4  form-label ">Label <span class="mk-red">*</span></label>
                                <input type="text" name="field-label-' . $ctr . '" id="field_label_' . $ctr . '" class="border field-label-gt" value="' . $record['field_label'] . '">
                                <p id="field_label_' . $ctr . '_error" class="fields-error"></p>
                            </div>
                            <div class="col-ai-4">
                                <label for="text-area" class="d-block fs-medium-14 mb-only-4  form-label">ID <span class="mk-red">*</span></label>
                                <input type="text" name="field-id-' . $ctr . '" id="field_id_' . $ctr . '" class="border  field-id-gt" value="' . $record['field_id'] . '">
                                <p id="field_id_' . $ctr . '_error" class="fields-error"></p>
                            </div>
                            <div class="col-ai-2" id="maxium-char_' . $ctr . '" class="maxium-char_' . $ctr . '" >
                                <label for="text-area" class="d-block fs-medium-14 mb-only-4  form-label">Max Char <span class="mk-red">*</span></label>
                                <input type="text" name="field-maxchar-' . $ctr . '" id="field_maxchar_' . $ctr . '" class="border  field-maxchar-gt field_maxchar-gt_' . $ctr . '" value="' . $record['field_maxchar'] . '">
                                <p id="field_maxchar_' . $ctr . '_error" class="fields-error"></p>
                            </div>
                            <div class="col-ai-1">
                               <label class="assets-icon-center-label"> <span class="grab-icon">
                                    <div class="assets-grab-icon"></div>
                               </span></label>
                                <p class="ai-remove-sec assets-icon-center">
                                    <button type="button" data-uid="' . $record['field_uniqueid'] . '" onclick="deleteFieldSection(this)">
                                    <div class="assets-delete-icon"></div>
                                    </button>
                                </p>
                            </div>';
                if (isset($record['field_type']) && $record['field_type'] == 'dropdown') {
                    $field_dropdown_options = unserialize($record['field_dropdown_options']);
                    $dropdown_options = implode('|', $field_dropdown_options);

                    $html_content .= '<div class="full-width dropdown-options-col_' . $ctr . '"><label for="dropdown-options-' . $ctr . '" class="d-block fs-medium-14 mb-only-4 form-label">Drop-down options <span class="mk-red">*</span></label><input type="text" name="dropdown-options-' . $ctr . '" id="dropdown_options_' . $ctr . '" class="border border-1 dropdown-options" value="' . $dropdown_options . '"><p>Separate values with "|"</p>
                                    <p id="dropdown_options_' . $ctr . '_error" class="fields-error"></p>
                                </div>';
                };

                $html_content .= '</div>
                        <div class="field-row bottm" id="field_sampl_text_' . $ctr . '">
                            <div class="col-ai-12">
                                <label for="text-area" class="d-block fs-medium-14 mb-only-4 form-label">Field Sample Text</label>
                                <input type="text" name="field-sample-text-' . $ctr . '" id="field_sample_text_' . $ctr . '" class="full-width border field-sample-text-' . $ctr . '" value="' . $record['field_sample_text'] . '">
                            </div>
                        </div>
                        <div class="field-row input-check-row mt-3">';

                $html_content .= '<div class="form-group"><input type="checkbox" id="section_required_' . $ctr . '" name="section-required-' . $ctr . '" value="" ' . ($record['field_require_field_status'] == 1 ? 'checked' : '') . '><label class="fs-medium-14" for="section_required_' . $ctr . '"> Required Field</label></div>';

                $html_content .= '<div class="form-group include-in-email-checkbox"><input type="checkbox" id="include_in_email_' . $ctr . '" name="include-in-email-' . $ctr . '" value="" ' . ($record['field_include_in_export_email'] == 1 ? 'checked' : '') . '><label class="fs-medium-14" for="include_in_email_' . $ctr . '"> Include in export/email</label></div>
                                </div>
                            </div>';
                $ctr++;
            }

            // Return the HTML content
            $arrayName = array('app_width' => $app_width, 'html_content' => $html_content, 'count' => $ctr);

            wp_send_json($arrayName);
            exit;
        }

        public function ai_app_onsite_delete_field_selector_callback()
        {

            global $wpdb;
            if (
                ! isset($_POST['ai_app_onsite_field_selector_nonce_field_delete']) ||
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_field_selector_nonce_field_delete'])), 'ai_app_onsite_delete_field_nonce')
            ) {
                wp_send_json_error('Nonce verification failed.for this');
                return false;
            }

            // Check if the field_uniqueid parameter is set
            if (isset($_POST['field_uniqueid'])) {

                // Sanitize the input to prevent SQL injection
                $field_uniqueid = isset($_POST['field_uniqueid']) ? sanitize_text_field(wp_unslash($_POST['field_uniqueid'])) : '';

                // Table name
                $table_name = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';

                // Delete the record from the database
                $wpdb->delete($table_name, array('field_uniqueid' => $field_uniqueid), array('%s'));

                // check error first
                if ($wpdb->last_error) {
                    wp_send_json_error('Error saving data: ' . $wpdb->last_error);
                } else {
                    // Return a success message
                    wp_send_json_success('Record deleted successfully');
                }
            } else {
                // Return an error message if field_uniqueid parameter is not set
                wp_send_json_error('Missing field_uniqueid parameter');
            }

            // Make sure no extra content is echoed
            exit;
        }


        public function ai_app_onsite_drag_data_save_database_callback()
        {
            if (
                ! isset($_POST['ai_app_onsite_fields_selector_order_nonce']) ||
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_fields_selector_order_nonce'])), 'ai_app_onsite_fields_selector_order_nonce')
            ) {
                wp_send_json_error('Nonce verification failed.');
            }

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

            // Decode the JSON data
            $form_data_array = isset($_POST['form_data_array']) ? sanitize_text_field(wp_unslash($_POST['form_data_array'])) : '';
            $form_data_array = json_decode($form_data_array, true);


            // Iterate through the form data array
            foreach ($form_data_array as $key => $value) {
          
                $field_position =  $value['fieldOrder'];
                // Uncomment the update query to actually update the data
                $wpdb->update(
                    $table_name, // Table name
                    array('field_position' => $field_position), // Data to update
                    array('field_uniqueid' => $value['fieldUniqueId']), // Where clause
                    array('%d'), // Data format (update_data format)
                    array('%s') // Where format
                );
            }

            // Send a success response
            wp_send_json_success('Data updated successfully.');
        }
    }

    new AI_APP_ONSITE_Field_Selector_Handler(); // Instantiate the class



}
