<?php
if (! class_exists('AI_APP_ONSITE_App_Properties_Handler')) {
    class AI_APP_ONSITE_App_Properties_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_app_properties', array($this, 'ai_app_onsite_save_app_properties_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_save_app_properties', array($this, 'ai_app_onsite_save_app_properties_callback'));
            
            add_action('wp_ajax_ai_app_onsite_get_app_properties', array($this, 'ai_app_onsite_get_app_properties'));
            add_action('wp_ajax_nopriv_ai_app_onsite_get_app_properties', array($this, 'ai_app_onsite_get_app_properties'));

            add_action('wp_ajax_ai_app_onsite_handle_sitelogo_upload', array($this, 'ai_app_onsite_handle_sitelogo_upload_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_handle_sitelogo_upload', array($this, 'ai_app_onsite_handle_sitelogo_upload_callback'));

            add_action('wp_ajax_ai_app_onsite_remove_app_logo', array($this, 'ai_app_onsite_remove_app_logo_callback'));
            add_action('wp_ajax_nopriv_ai_app_onsite_remove_app_logo', array($this, 'ai_app_onsite_remove_app_logo_callback'));
        }

        function ai_app_onsite_save_app_properties_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_app_properties' ||
                ! isset($_POST['ai_app_onsite_app_properties_nonce_field']) ||
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_app_properties_nonce_field'])), 'ai_app_onsite_app_properties_nonce')
            ) {
                wp_send_json_error('Unauthorized request');
            }

            // Extract individual settings values
            $app_name = isset($_POST['app-name']) ? sanitize_text_field(wp_unslash($_POST['app-name'])) : '';
            $app_name_show = isset($_POST['app-name-show']) ? sanitize_text_field(wp_unslash($_POST['app-name-show'])) : '';
            $app_description = isset($_POST['app-description']) ? sanitize_text_field(wp_unslash($_POST['app-description'])) : '';
            $app_response_header = isset($_POST['response-header']) ? sanitize_text_field(wp_unslash($_POST['response-header'])) : '';
            $response_message = isset($_POST['response-message']) ? sanitize_text_field(wp_unslash($_POST['response-message'])) : '';
            $app_disclaimer = isset($_POST['app-disclaimer']) ? sanitize_text_field(wp_unslash($_POST['app-disclaimer'])) : '';
            $submit_btn_txt = isset($_POST['submit-btn-txt']) ? sanitize_text_field(wp_unslash($_POST['submit-btn-txt'])) : '';

            // Get the JSON string from $_POST
            
            $titleColorsJson = isset($_POST['titleColors']) ? 
                sanitize_text_field(wp_unslash($_POST['titleColors'])) : 
                wp_json_encode([
                    ["title_color_selected" => "#5c5c5c"],
                    ["title_color" => "#8d949a"],
                    ["title_color" => "#3b7dbb"]
                ]);
            $titleColorsJson = stripslashes($titleColorsJson);

            $fontColorsJson = isset($_POST['fontColor']) ? 
            sanitize_text_field(wp_unslash($_POST['fontColor'])) : 
            wp_json_encode([
                ["font_color_selected" => "#8d949a"],
                ["font_color" => "#000000"],
                ["font_color" => "#053f3e"]
            ]);
            $fontColorsJson = stripslashes($fontColorsJson);

            $bgColorsJson = isset($_POST['bgColor']) ? 
            sanitize_text_field(wp_unslash($_POST['bgColor'])) : 
            wp_json_encode([
                ["bg_color_selected" => "#f4f4f4"],
                ["bg_color" => "#e4fcff"],
                ["bg_color" => "#effdf9"]
            ]);
            $bgColorsJson = stripslashes($bgColorsJson);


            $btnColorsJson = isset($_POST['btnColors']) ? 
                sanitize_text_field(wp_unslash($_POST['btnColors'])) : 
                wp_json_encode([
                    ["btn_color_selected" => "#3b7dbb"],
                    ["btn_color" => "#8d949a"],
                    ["btn_color" => "#5c5c5c"]
                ]);
            $btnColorsJson = stripslashes($btnColorsJson);

            $btnFontColorsJson = isset($_POST['btnFontColors']) ? 
                sanitize_text_field(wp_unslash($_POST['btnFontColors'])) : 
                wp_json_encode([
                    ["btn_font_color_selected" => "#ffffff"],
                    ["btn_font_color" => "#000000"],
                    ["btn_font_color" => "#053f3e"]
                ]);
            $btnFontColorsJson = stripslashes($btnFontColorsJson);  

            $responseBgColorsJson = isset($_POST['responseBgColors']) ? 
                sanitize_text_field(wp_unslash($_POST['responseBgColors'])) : 
                wp_json_encode([
                    ["response_bg_color_selected" => "#f4f4f4"],
                    ["response_bg_color" => "#e4fcff"],
                    ["response_bg_color" => "#effdf9"]
                ]);
            $responseBgColorsJson = stripslashes($responseBgColorsJson);


            $app_corner = isset($_POST['app-corner']) ? sanitize_text_field(wp_unslash($_POST['app-corner'])) : 'soft-corner';
            $app_height = isset($_POST['app-height']) ? sanitize_text_field(wp_unslash($_POST['app-height'])) : 'slight-lift';

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

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

            // Check if a file was uploaded
            if (isset($_FILES['app-file']) && ! empty($_FILES['app-file']['name'])) {
                // Handle file upload
                $upload_overrides = array('test_form' => false);
                $movefile = wp_handle_upload($_FILES['app-file'], $upload_overrides);

                if ($movefile && ! isset($movefile['error'])) {
                    $file_url = $movefile['url']; // Get the file URL

                } else {
                    wp_send_json_error('Error uploading file: ' . $movefile['error']);
                }
            } else {
                $file_url = $existing_settings->app_logo;
            }

            if ($app_name_show == "true") {
                $app_name_temp = $app_name;
                $app_name = "";
            } else {
                $app_name_temp = "";
            }

            if ($existing_settings) {
                $wpdb->update(
                    $table_name_settings,
                    array(
                        'app_name'          => $app_name,
                        'app_name_show'     => $app_name_temp,
                        'app_logo'          => $file_url,
                        'app_description'   => $app_description,
                        'response_header'   => $app_response_header,
                        'response_message'  => $response_message,
                        'app_disclaimer'    => $app_disclaimer,
                        'submit_button_txt' => $submit_btn_txt,
                        'title_color'       => $titleColorsJson,
                        'font_color'        => $fontColorsJson,
                        'bg_color'          => $bgColorsJson,
                        'btn_color'         => $btnColorsJson,
                        'btn_font_color'    => $btnFontColorsJson,
                        'response_bg_color' => $responseBgColorsJson,
                        'app_corner'        => $app_corner,
                        'app_height'        => $app_height
                    ),
                    array('id' => $existing_settings->id),
                    array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'),
                    array('%d')
                );

                // 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,
                        'app_name'          => $app_name,
                        'app_name_show'     => $app_name_temp,
                        'app_logo'          => $file_url,
                        'app_description'   => $app_description,
                        'response_header'   => $app_response_header,
                        'response_message'  => $response_message,
                        'app_disclaimer'    => $app_disclaimer,
                        'submit_button_txt' => $submit_btn_txt,
                        'title_color'       => $titleColorsJson,
                        'font_color'        => $fontColorsJson,
                        'bg_color'          => $bgColorsJson,
                        'btn_color'         => $btnColorsJson,
                        'btn_font_color'    => $btnFontColorsJson,
                        'response_bg_color' => $responseBgColorsJson,
                        'app_corner'        => $app_corner,
                        'app_height'        => $app_height
                    ),
                    array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%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.');
                }
            }
        }

        public static function ai_app_onsite_get_app_properties()
        {
            global $wpdb;
            $table_name_settings = $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.');

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

                wp_send_json($results);
            }

            // 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) {
                //die('No rows found in the table.');
                $results = array('status' => '404', 'message' => 'App not found. Please create an app first.');

                wp_send_json($results);
            }

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

            $generateURLForID  = $results[0]['app_logo'];
            $appLogoImagePreview = wp_get_attachment_url($generateURLForID);

            if ($appLogoImagePreview) {
                // Add the image preview URL to the $results array
                $results[0]['appLogoImagePreview'] = $appLogoImagePreview;
            } else {
                $results[0]['appLogoImagePreview'] = 'No preview available'; // Handle cases where no URL is found
            }
            wp_send_json($results);

            // Don't forget to exit
            exit;
        }

        function ai_app_onsite_handle_sitelogo_upload_callback()
        {
            global $wpdb;


            // Verify nonce to ensure the request is valid
            if (
                !isset($_POST['ai_app_onsite_app_properties_logo_field_nonce_field']) ||
                !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ai_app_onsite_app_properties_logo_field_nonce_field'])), 'ai_app_onsite_app_properties_nonce')
            ) {
                wp_send_json_error('Invalid nonce. Please refresh the page and try again.');
                return;
            }


            // Check for file upload
            if (isset($_FILES['app-file']) && ! empty($_FILES['app-file']['name'])) {
                $upload_overrides = array('test_form' => false);
                $movefile = wp_handle_upload($_FILES['app-file'], $upload_overrides);
                if ($movefile && ! isset($movefile['error'])) {
                    // File uploaded successfully
                    $file_path = $movefile['file']; // Local file path
                    $file_url = $movefile['url'];   // File URL

                    // Create attachment
                    $filetype = wp_check_filetype($file_path, null);
                    $attachment = array(
                        'post_mime_type' => $filetype['type'],
                        'post_title'     => sanitize_file_name(basename($file_path)),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );

                    $attachment_id = wp_insert_attachment($attachment, $file_path);

                    // Include the image handling functions
                    require_once ABSPATH . 'wp-admin/includes/image.php';

                    // Generate metadata and update attachment
                    $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path);
                    wp_update_attachment_metadata($attachment_id, $attach_data);
                } else {
                    wp_send_json_error('Error uploading file: ' . $movefile['error']);
                }
            } else {
                wp_send_json_error('No file uploaded.');
            }

            $table_name_settings = $wpdb->prefix . 'ai_app_onsite_app_properties';

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

                $wpdb->update(
                    $table_name_settings,
                    array(
                        'app_logo' => $attachment_id
                    ),
                    array('id' => $existing_settings->id),
                    array('%s'),
                    array('%d')
                );

                // 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(array(
                        'attachment_id' => $attachment_id,
                        'file_url'      => $file_url,
                    ));
                }
            } else {
                // Insert new row
                $wpdb->insert(
                    $table_name_settings,
                    array(
                        'app_id'            => 1,
                        'app_name'          => '',
                        'app_name_show'     => '',
                        'app_logo'          => $attachment_id,
                        'app_description'   => '',
                        'response_message'  => '',
                        'app_disclaimer'    => '',
                        'submit_button_txt' => '',
                        'title_color'       => '',
                        'font_color'        => '',
                        'bg_color'          => '',
                        'app_corner'        => '',
                        'app_height'        => ''
                    ),
                    array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
                );
            }

            $existing_settings = $wpdb->get_row("SELECT * FROM $table_name_settings WHERE app_id = 1");
            $file_url = $existing_settings->app_logo;
            // Check if the database operation was successful
            if ($wpdb->last_error) {
                wp_send_json_error('Error saving data: ' . $wpdb->last_error);
            } else {

                // Send response with the attachment ID
                wp_send_json_success(array(
                    'attachment_id' => $attachment_id,
                    'file_url'      => $file_url,
                ));
            }
        }

        public static function ai_app_onsite_remove_app_logo_callback()
        {
            global $wpdb;
            $table_name_settings = $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.');
            }

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

                $wpdb->update(
                    $table_name_settings,
                    array(
                        'app_logo' => ''
                    ),
                    array('id' => $existing_settings->id),
                    array('%s'),
                    array('%d')
                );

                // 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(array(
                        'status' => '200',
                        'message' => 'Logo removed',
                    ));
                }
            }
            // Don't forget to exit
            exit;
        }
    }

    new AI_APP_ONSITE_App_Properties_Handler(); // Instantiate the class
}
