<?php

use JetBrains\PhpStorm\NoReturn;

require_once plugin_dir_path(__FILE__) . '/ai-app-onsite-app-properties.php';

if (! class_exists('AI_APP_ONSITE_App_Preview_Handler')) {
	class AI_APP_ONSITE_App_Preview_Handler
	{
		private array $appProperty;

		public function __construct()
		{
			add_action('wp_ajax_ai_app_onsite_update_style_properties_only', array($this, 'ai_app_onsite_update_style_properties_only_callback'));
			add_action('wp_ajax_nopriv_ai_app_onsite_update_style_properties_only', array($this, 'ai_app_onsite_update_style_properties_only_callback'));

			add_action('wp_ajax_ai_app_onsite_create_app_preview_form', array($this, 'ai_app_onsite_create_app_preview_form'));
			add_action('wp_ajax_nopriv_ai_app_onsite_create_app_preview_form', array($this, 'ai_app_onsite_create_app_preview_form'));


			// Initialize $appProperty array here
			global $wpdb;
			$table_appropriate = $wpdb->prefix . 'ai_app_onsite_app_properties';
			$appropriates = $wpdb->get_results("SELECT * FROM $table_appropriate WHERE app_id = 1", ARRAY_A);
			if (empty($appropriates)) {
				return;
			}

			$table_field_selector = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';
			$app_width = $wpdb->get_var($wpdb->prepare("SELECT app_width FROM $table_field_selector WHERE app_id = %d", 1));
			$app_width = $app_width ? intval($app_width) : 70;
			$appropriates[0]['app_width'] = $app_width;

			$is_preview = isset($_POST['is_preview_button']) && $_POST['is_preview_button'] === 'true';

			$appropriates[0]['title_color']       = ($is_preview && isset($_POST['title_color'])) ? $_POST['title_color'] : $appropriates[0]['title_color'];
			$appropriates[0]['font_color']        = ($is_preview && isset($_POST['font_color'])) ? $_POST['font_color'] : $appropriates[0]['font_color'];
			$appropriates[0]['bg_color']          = ($is_preview && isset($_POST['background_color'])) ? $_POST['background_color'] : $appropriates[0]['bg_color'];
			$appropriates[0]['btn_color']         = ($is_preview && isset($_POST['btn_color'])) ? $_POST['btn_color'] : $appropriates[0]['btn_color'];
			$appropriates[0]['btn_font_color']    = ($is_preview && isset($_POST['btn_font_color'])) ? $_POST['btn_font_color'] : $appropriates[0]['btn_font_color'];
			$appropriates[0]['response_bg_color'] = ($is_preview && isset($_POST['response_bg_color'])) ? $_POST['response_bg_color'] : $appropriates[0]['response_bg_color'];
			$appropriates[0]['app_corner']        = ($is_preview && isset($_POST['app_corner'])) ? $_POST['app_corner'] : $appropriates[0]['app_corner'];
			$appropriates[0]['app_height']        = ($is_preview && isset($_POST['app_height'])) ? $_POST['app_height'] : $appropriates[0]['app_height'];
			$appropriates[0]['app_width']         = ($is_preview && isset($_POST['app_width'])) ? $_POST['app_width'] : $appropriates[0]['app_width'];

			$titleColors      = isset($appropriates[0]['title_color']) ? json_decode($appropriates[0]['title_color'], true) : null;
			$fontColors       = isset($appropriates[0]['font_color']) ? json_decode($appropriates[0]['font_color'], true) : null;
			$bgColors         = isset($appropriates[0]['bg_color']) ?  json_decode($appropriates[0]['bg_color'], true) : null;
			$btnColors        = isset($appropriates[0]['btn_color']) ? json_decode($appropriates[0]['btn_color'], true) : null;
			$btnFontColors    = isset($appropriates[0]['btn_font_color']) ? json_decode($appropriates[0]['btn_font_color'], true) : null;
			$responseBgColors = isset($appropriates[0]['response_bg_color']) ? json_decode($appropriates[0]['response_bg_color'], true) : null;
			$appCorner        = $appropriates[0]['app_corner'];
			$appHeight        = $appropriates[0]['app_height'];
			$appWidth         = isset($appropriates[0]['app_width']) ? $appropriates[0]['app_width'] : null;

			$title_color_selected       = null;
			$font_color_selected        = null;
			$bg_color_selected          = null;
			$btn_color_selected         = null;
			$btn_font_color_selected    = null;
			$response_bg_color_selected = null;
			$app_corner_selected        = null;
			$app_height_selected        = null;
			$app_width_selected         = null;

			if(!is_null($titleColors)) {
				foreach ($titleColors as $color) {
					if (isset($color['title_color_selected'])) {
						$title_color_selected = $color['title_color_selected'];
						break;
					}
				}
			}

			if(!is_null($fontColors)) {
				foreach ($fontColors as $color) {
					if (isset($color['font_color_selected'])) {
						$font_color_selected = $color['font_color_selected'];
						break;
					}
				}
			}

			if(!is_null($bgColors)) {
				foreach ($bgColors as $color) {
					if (isset($color['bg_color_selected'])) {
						$bg_color_selected = $color['bg_color_selected'];
						break;
					}
				}
			}

			if(!is_null($btnColors)) {
				foreach ($btnColors as $color) {
					if (isset($color['btn_color_selected'])) {
						$btn_color_selected = $color['btn_color_selected'];
						break;
					}
				}
			}

			if(!is_null($btnFontColors)) {
				foreach ($btnFontColors as $color) {
					if (isset($color['btn_font_color_selected'])) {
						$btn_font_color_selected = $color['btn_font_color_selected'];
						break;
					}
				}
			}

			if(!is_null($responseBgColors)) {
				foreach ($responseBgColors as $color) {
					if (isset($color['response_bg_color_selected'])) {
						$response_bg_color_selected = $color['response_bg_color_selected'];
						break;
					}
				}
			}

			if(!is_null($appCorner)) {
				$app_corner_selected = $appCorner;
			}

			if(!is_null($appHeight)) {
				$app_height_selected = $appHeight;
			}

			if(!is_null($appWidth)){
				$app_width_selected = $appWidth;
			}


			// Use POST if provided, else fallback to DB values
			$title_color       = self::normalize_color_value($title_color_selected);
			$font_color        = self::normalize_color_value($font_color_selected);
			$background_color  = self::normalize_color_value($bg_color_selected);
			$btn_color         = self::normalize_color_value($btn_color_selected);
			$btn_font_color    = self::normalize_color_value($btn_font_color_selected);
			$response_bg_color = self::normalize_color_value($response_bg_color_selected);
			$app_corner       = $app_corner_selected;
			$app_height       = $app_height_selected;
			$app_width        = $app_width_selected;

			$background_style = self::build_background_style($background_color);
			$response_bg_style = self::build_background_style($response_bg_color);
			$btn_font_color_attr = esc_attr((string) $btn_font_color);
			$btn_background_style = self::build_background_style($btn_color);
			$btn_style = trim($btn_background_style . 'color:' . $btn_font_color_attr . ';');
			$btn_style_attr = $btn_style !== '' ? 'style="' . $btn_style . '"' : '';

			$this->appProperty = [
				'app_name'              => $appropriates[0]['app_name'],
				'app_logo'              => $appropriates[0]['app_logo'],
				'app_disclaimer'        => $appropriates[0]['app_disclaimer'],
				'app_description'       => $appropriates[0]['app_description'],
				'response_header'      	=> $appropriates[0]['response_header'],
				'submit_button_txt'     => $appropriates[0]['submit_button_txt'],
				'title_color'           => 'style="color:' . esc_attr((string) $title_color) . ';"',
				'font_color'            => 'style="color:' . esc_attr((string) $font_color) . ';"',
				'small_font_color'      => 'style="color:' . esc_attr((string) $font_color) . '; opacity:0.5;"',
				'app_description_color' => 'style="color:' . esc_attr((string) $font_color) . '; opacity:0.5; text-align: center; font-size: 20px;"',
				'background_color'      => $background_color,
				'background_style'      => $background_style,
				'btn_color'             => $btn_style_attr,
				'btn_font_color'        => '',
				'response_bg_color'     => $response_bg_color,
				'response_bg_style'     => $response_bg_style,
				'short_code_genrated'   => $appropriates[0]['short_code_genrated']
			];

			switch ($app_corner) {
				case 'sharp-corner':
					$this->appProperty['app_corner'] = 'border-radius: 0px;';
					break;
				case 'soft-corner':
					$this->appProperty['app_corner'] = 'border-radius: 10px;';
					break;
				case 'round-corner':
					$this->appProperty['app_corner'] = 'border-radius: 25px;';
					break;
				default:
					$this->appProperty['app_corner'] = 'border-radius: 10px;';
					break;
			}

			switch ($app_height) {
				case 'no-height':
					$this->appProperty['app_height'] = 'box-shadow: none;';
					break;
				case 'slight-lift':
					$this->appProperty['app_height'] = 'box-shadow: 0px 8px 12px rgba(0, 0, 0, 0.2);';
					break;
				case 'more-lift':
					$this->appProperty['app_height'] = 'box-shadow: 0px 12px 18px rgba(0, 0, 0, 0.3);';
					break;
				default:
					$this->appProperty['app_height'] = 'box-shadow: 0px 8px 12px rgba(0, 0, 0, 0.2);';
					break;
			}

			//New Logic
			$appName = isset($appropriates[0]['app_name']) && !empty($appropriates[0]['app_name']) ? $appropriates[0]['app_name'] : 'aiapp';
			if ($appName == "aiapp") {
				$appName = $appropriates[0]['app_name_show'];
			}
			if ($appName !== "aiapp") {
				$shortCodeGenrated = $appropriates[0]['short_code_genrated'];

				$words = explode(' ', $appName);
				$words = array_map(function ($word) {
					return strtolower($word);
				}, $words);
				$appNameWithShortCode = implode('_', $words) . '_aiao';

				if ($shortCodeGenrated === 'NO' || $shortCodeGenrated === '_aiao' || $shortCodeGenrated === null) {
					// Register shortcode
					add_shortcode($appNameWithShortCode, array($this, 'AI_APP_ONSITE_Create_OpenAi_App_Form_Shortcode'));
					$wpdb->update(
						$table_appropriate,
						array(
							'short_code_genrated' => $appNameWithShortCode,
						),
						array('app_id' => $appropriates[0]['app_id']), // where clause: update based on the existing row's ID
						array('%s'),
						array('%d') // where format
					);
				} else {
					add_shortcode($shortCodeGenrated, array($this, 'AI_APP_ONSITE_Create_OpenAi_App_Form_Shortcode'));
				}
			}
			//End New Logic
		}

		private function ai_app_onsite_json_error_404($message) {
			wp_send_json(array(
				'status'  => '404',
				'message' => $message
			));
		}

		private static function extract_selected_color($json, $key): ?string {
			if (empty($json)) return null;
			$data = json_decode($json, true);
			if (!is_array($data)) return null;
			foreach ($data as $item) {
				if (isset($item[$key])) {
					return self::normalize_color_value($item[$key]);
				}
			}
			return null;
		}

		private static function normalize_color_value($value): ?string {
			if (is_array($value)) {
				return self::build_color_from_array($value);
			}
			if (is_string($value)) {
				$trimmed = trim($value);
				if ($trimmed === '') {
					return null;
				}
				if ($trimmed[0] === '{' || $trimmed[0] === '[') {
					$decoded = json_decode($trimmed, true);
					if (is_array($decoded)) {
						return self::build_color_from_array($decoded);
					}
				}
				if (preg_match('/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+)\s*)?\)$/i', $trimmed, $matches)) {
					$alpha = isset($matches[4]) ? floatval($matches[4]) : 1;
					return self::rgba_to_hex8(
						(int) round(floatval($matches[1])),
						(int) round(floatval($matches[2])),
						(int) round(floatval($matches[3])),
						$alpha
					);
				}
				return self::sanitize_hex_color_value($trimmed);
			}
			return null;
		}

		private static function build_color_from_array(array $value): ?string {
			$type = isset($value['type']) ? $value['type'] : '';
			if ($type === 'gradient') {
				return self::build_gradient_css($value);
			}
			if ($type === 'solid') {
				$color = self::sanitize_hex_color_value((string) ($value['color'] ?? ''));
				if ($color === '') {
					return null;
				}
				$alpha = isset($value['alpha']) ? floatval($value['alpha']) : (isset($value['opacity']) ? floatval($value['opacity']) : 1);
				if ($alpha > 1) {
					$alpha = $alpha / 100;
				}
				$alpha = max(0, min(1, $alpha));
				return $alpha < 1 ? self::hex_to_hex8($color, $alpha) : $color;
			}
			if (isset($value['color'])) {
				$color = self::sanitize_hex_color_value((string) $value['color']);
				if ($color === '') {
					return null;
				}
				$alpha = isset($value['alpha']) ? floatval($value['alpha']) : (isset($value['opacity']) ? floatval($value['opacity']) : 1);
				if ($alpha > 1) {
					$alpha = $alpha / 100;
				}
				$alpha = max(0, min(1, $alpha));
				return $alpha < 1 ? self::hex_to_hex8($color, $alpha) : $color;
			}
			return null;
		}

		private static function sanitize_hex_color_value(string $color): string {
			$color = trim($color);
			if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $color)) {
				return $color;
			}
			return '';
		}

		private static function hex_to_rgba(string $hex, float $alpha): string {
			$hex = ltrim($hex, '#');
			if (strlen($hex) === 3) {
				$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
			}
			if (strlen($hex) !== 6) {
				return '';
			}
			$red   = hexdec(substr($hex, 0, 2));
			$green = hexdec(substr($hex, 2, 2));
			$blue  = hexdec(substr($hex, 4, 2));
			$alpha = max(0, min(1, $alpha));
			return 'rgba(' . $red . ', ' . $green . ', ' . $blue . ', ' . $alpha . ')';
		}

		private static function hex_to_hex8(string $hex, float $alpha): string {
			$hex = ltrim(trim($hex), '#');
			if (strlen($hex) === 3) {
				$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
			}
			if (strlen($hex) !== 6) {
				return '';
			}
			$alpha = max(0, min(1, $alpha));
			$alpha_hex = strtoupper(str_pad(dechex((int) round($alpha * 255)), 2, '0', STR_PAD_LEFT));
			return '#' . strtoupper($hex) . $alpha_hex;
		}

		private static function rgba_to_hex8(int $red, int $green, int $blue, float $alpha): string {
			$red = max(0, min(255, $red));
			$green = max(0, min(255, $green));
			$blue = max(0, min(255, $blue));
			$alpha = max(0, min(1, $alpha));
			return sprintf('#%02X%02X%02X%02X', $red, $green, $blue, (int) round($alpha * 255));
		}

		private static function build_gradient_css(array $value): string {
			if (isset($value['stops']) && is_array($value['stops'])) {
				$mode = isset($value['mode']) && $value['mode'] === 'radial' ? 'radial' : 'linear';
				$angle = isset($value['angle']) ? floatval($value['angle']) : 90;
				$angle = max(0, min(360, $angle));
				$stops = [];
				foreach ($value['stops'] as $index => $stop) {
					if (!is_array($stop)) {
						continue;
					}
					$color = isset($stop['color']) ? self::sanitize_hex_color_value((string) $stop['color']) : '';
					if ($color === '') {
						continue;
					}
					$alpha = isset($stop['alpha']) ? floatval($stop['alpha']) : (isset($stop['opacity']) ? floatval($stop['opacity']) : 1);
					if ($alpha > 1) {
						$alpha = $alpha / 100;
					}
					$alpha = max(0, min(1, $alpha));
					$pos = null;
					if (isset($stop['pos'])) {
						$pos = floatval($stop['pos']);
					} elseif (isset($stop['position'])) {
						$pos = floatval($stop['position']);
					}
					$color_value = $alpha < 1 ? self::hex_to_rgba($color, $alpha) : $color;
					if ($pos !== null) {
						$pos = max(0, min(100, $pos));
						$stops[] = $color_value . ' ' . $pos . '%';
					} else {
						$stops[] = $color_value;
					}
				}
				if (count($stops) === 0) {
					return '';
				}
				if ($mode === 'radial') {
					return 'radial-gradient(circle at center, ' . implode(', ', $stops) . ')';
				}
				return 'linear-gradient(' . $angle . 'deg, ' . implode(', ', $stops) . ')';
			}

			$colors = [];
			if (isset($value['colors']) && is_array($value['colors'])) {
				foreach ($value['colors'] as $color) {
					$sanitized = self::sanitize_hex_color_value((string) $color);
					if ($sanitized !== '') {
						$colors[] = $sanitized;
					}
				}
			}
			if (count($colors) === 0) {
				return '';
			}
			if (count($colors) === 1) {
				$colors[] = $colors[0];
			}
			$positions = isset($value['positions']) && is_array($value['positions']) ? $value['positions'] : [];
			$stops = [];
			foreach ($colors as $index => $color) {
				if (isset($positions[$index]) && is_numeric($positions[$index])) {
					$stops[] = $color . ' ' . floatval($positions[$index]) . '%';
				} else {
					$stops[] = $color;
				}
			}
			$direction = isset($value['direction']) ? $value['direction'] : 'to right';
			return 'linear-gradient(' . $direction . ', ' . implode(', ', $stops) . ')';
		}

		private static function build_background_style(?string $value): string {
			if (empty($value)) {
				return '';
			}
			$style_value = trim($value);
			if (strpos($style_value, 'linear-gradient') === 0 || strpos($style_value, 'radial-gradient') === 0) {
				return 'background-image:' . esc_attr($style_value) . ';';
			}
			return 'background-color:' . esc_attr($style_value) . ';';
		}

		// AJAX callback function
		public function ai_app_onsite_create_app_preview_form()
		{
			global $wpdb;
			$table_name_settings       = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';
			$table_name_app_properties = $wpdb->prefix . 'ai_app_onsite_app_properties';
			$table_name_model_settings = $wpdb->prefix . 'ai_app_onsite_model_settings';

			// Check if the table ai_app_onsite_field_selector_settings exists
			if ($wpdb->get_var("SHOW TABLES LIKE '$table_name_settings'") != $table_name_settings || $wpdb->get_var("SHOW TABLES LIKE '$table_name_model_settings'") != $table_name_model_settings) {
				$this->ai_app_onsite_json_error_404('No App found');
			}

			// Check if the table ai_app_onsite_field_selector_settings has rows
			$rows_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name_settings WHERE app_id = 1");
			$model_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name_model_settings WHERE app_id = 1");
		
			if ($rows_count == 0 || $model_count == 0 ||  empty($this->appProperty)) {
				$this->ai_app_onsite_json_error_404('It looks like some required settings are missing. Please ensure that "App Details," "Model Settings," and "Form Fields" are configured before previewing the form.');
			}

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

			$table_appropriate = $wpdb->prefix . 'ai_app_onsite_app_properties';
			$appropriates = $wpdb->get_results("SELECT * FROM $table_appropriate WHERE app_id = 1", ARRAY_A);
			
			// check if app_corner & app_height is empty
			$updates_needed = array();
			$default_values = array(
				'app_corner' => 'soft-corner',
				'app_height' => 'slight-lift'
			);

			foreach ($default_values as $field => $default_value) {
				if (empty($appropriates[0][$field])) {
					$appropriates[0][$field] = $default_value;
					$updates_needed[$field] = $default_value;
				}
			}
			
			if (!empty($updates_needed)) {
				$format_array = array_fill(0, count($updates_needed), '%s');
				$wpdb->update(
					$table_appropriate,
					$updates_needed,
					array('app_id' => 1),
					$format_array,
					array('%d')
				);
			}
			$app_logo = isset($appropriates[0]['app_logo']) && !empty($appropriates[0]['app_logo'])
				? $appropriates[0]['app_logo']
				: '';

			$app_logo_image_url = wp_get_attachment_url($app_logo);

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

			$background_style = $this->appProperty['background_style'] ?? '';
			$form_style = 'style="' . trim($background_style . ' max-width: ' . $form_width_size . '% ; '.$this->appProperty['app_corner'].' ; '.$this->appProperty['app_height']) . '"';

			$formHTML = '<form class="ai-app-form-wrap aiapp-instance form-width" id="ai-app-openAi-app-form" ' . $form_style . '>';

			// App Logo start
			if (!empty($app_logo_image_url)) {
				$formHTML .= '<div class="ai-app-logo-wrapper">';
				$formHTML .= '<img decoding="async" src="' . esc_url($app_logo_image_url) . '" alt="App Logo" style="width: 100%; height: auto;">';
				$formHTML .= '</div>';
			}
			// App Logo End


			//short code name
			$formHTML .= '<input type="hidden" name="short_code_generated" id="short_code_generated" value="' . $appropriates[0]['short_code_genrated'] . '" />';


			$formHTML .= '<h2 class="ai-app-preview-form-heading" ' . $this->appProperty['title_color'] . '>' . $this->appProperty['app_name'] . '</h2>';

			$formHTML .= '<h2 class="ai-app-app-descipition"' . $this->appProperty['app_description_color'] . '>' . $this->appProperty['app_description'] . '</h2>';

			$formHTML .= wp_nonce_field("ai_app_onsite_properties_nonce", "ai_app_onsite_properties_nonce_field", true, false);


			$formHTML .= '<div id="loader" style="display: none;">
                            <div class="loader"></div>
                        </div>';

			// Add form fields
			foreach ($results as $field) {
				$required_asterisk = ! empty( $field['field_require_field_status'] ) && (int) $field['field_require_field_status'] === 1 
				? ' <span style="color:red;">*</span>' 
				: '';

				$formHTML .= '<div class="form-group mb-3">';
				$formHTML .= '<label class="ai-app-preview-form-label" ' . $this->appProperty['font_color'] . '>' . $field['field_label'] . $required_asterisk . '</label>';
				$formHTML .= '<div class="select-box-icon">';

				if ($field['field_type'] === 'textarea') {
					$formHTML .= '<textarea name="' . $field['field_label'] . '" id="aiaap-form-field-' . $field['field_id'] . '" class="ai-app-preview-form-textarea" placeholder="' . $field['field_sample_text'] . '"  maxlength="' . $field['field_maxchar'] . '"  ' . ($field['field_require_field_status'] ? 'required' : '') . ' ' . $this->appProperty['font_color'] . '></textarea>';
					$formHTML .= '<p id="aiaap-form-field-' . $field['field_id'] . '-error" class="fields-error"></p>';
					$formHTML .= '<p class="app-preview-form-sampletext" ' . $this->appProperty['small_font_color'] . '></p>';
				} elseif ($field['field_type'] === 'dropdown') {
					$formHTML .= '<style>
						#aiaap-form-field-' . $field['field_id'] . ' option {
							background-color: ' . $this->appProperty['background_color'] . ' !important;
							color: ' . $this->appProperty['font_color'] . ' !important;
						}
					</style>';
					$formHTML .= '<select name="' . $field['field_label'] . '" id="aiaap-form-field-' . $field['field_id'] . '" class="ai-app-preview-form-textarea" placeholder=""  maxlength="' . $field['field_maxchar'] . '"  ' . ($field['field_require_field_status'] ? 'required' : '') . ' ' . $this->appProperty['font_color'] . '>';
					$field_dropdown_options = unserialize($field['field_dropdown_options']);
					foreach ($field_dropdown_options as $value) {
						$formHTML .=  '<option value="' . $value . '">' . $value . '</option>';
					}

					$formHTML .=  '</select>';

					$formHTML .= '<p id="aiaap-form-field-' . $field['field_id'] . '-error" class="fields-error"></p>';
					$formHTML .= '<p class="app-preview-form-sampletext" ' . $this->appProperty['small_font_color'] . '>' . $field['field_sample_text'] . '</p>';
				} elseif ($field['field_type'] === 'textbox') {
					$formHTML .= '<input name="' . $field['field_label'] . '" id="aiaap-form-field-' . $field['field_id'] . '" class="ai-app-preview-form-input" placeholder = "' . $field['field_sample_text'] . '" type="' . $field['field_type'] . '" maxlength="' . $field['field_maxchar'] . '" ' . ($field['field_require_field_status'] ? 'required' : '') . ' ' . $this->appProperty['font_color'] . '>';
					$formHTML .= '<p id="aiaap-form-field-' . $field['field_id'] . '-error" class="fields-error"></p>';
					/* $formHTML .= '<p class="ai-app-preview-form-sampletext" '.$this->appProperty['small_font_color'].'>'.$field['field_sample_text'].'</p>';*/
				} else {
					$formHTML .= '<input name="' . $field['field_label'] . '" id="aiaap-form-field-' . $field['field_id'] . '" class="ai-app-preview-form-input wsedrftyuiofedrwerrerr" placeholder="' . $field['field_sample_text'] . '" type="' . $field['field_type'] . '" maxlength="' . $field['field_maxchar'] . '" ' . ($field['field_require_field_status'] ? 'required' : '') . ' ' . $this->appProperty['font_color'] . ' oninput="this.value = this.value.slice(0, ' . $field['field_maxchar'] . ');">';

					$formHTML .= '<p id="aiaap-form-field-' . $field['field_id'] . '-error" class="fields-error"></p>';
					/* $formHTML .= '<p class="ai-app-preview-form-sampletext" '.$this->appProperty['small_font_color'].'>'.$field['field_sample_text'].'</p>';*/
				}

				$formHTML .= '</div></div>';
			}

			// Add buttons
			$formHTML .= '<div class="ai-app-preview-submit-btn-wrap" >';
			$formHTML .= '<button type="button" class="" name="save-plugin-settings" onclick="ai_app_onsite_get_the_ai_response()" ' . $this->appProperty['btn_color'] . $this->appProperty['btn_font_color'] . '>' . $this->appProperty['submit_button_txt'] . '</button>';
			$formHTML .= '</div>';

			$formHTML .= '<div class="ai-app-preview-note-wrapper">
                <p class="example-text" ' . $this->appProperty['small_font_color'] . '><span class="disclaimer-heading">Disclaimer: </span>' . $this->appProperty['app_disclaimer'] . '</p>
            </div>';

			$formHTML .= '<div class="ai-app-preview-powered_by_note-wrapper">
                <p class="powered_by" style="opacity:0.5;text-align: right;margin: 0; color:#159AD7;"><span class="disclaimer-heading"><a href="https://www.aiapponsite.com/" class="open-new-tab">Built with AIappOnsite</a></span>
            </div>';

			// Close form tag
			$formHTML .= '</form>';

			$is_preview = isset($_POST['is_preview_button']) && $_POST['is_preview_button'] === 'true';
			if($is_preview){
				$appropriates[0]['title_color']       = stripslashes($_POST['title_color']);
				$appropriates[0]['font_color']        = stripslashes($_POST['font_color']);
				$appropriates[0]['bg_color']          = stripslashes($_POST['background_color']);
				$appropriates[0]['btn_color']         = stripslashes($_POST['btn_color']);
				$appropriates[0]['btn_font_color']    = stripslashes($_POST['btn_font_color']);
				$appropriates[0]['response_bg_color'] = stripslashes($_POST['response_bg_color']);
				$appropriates[0]['app_corner']        = sanitize_text_field($_POST['app_corner']);
				$appropriates[0]['app_height']        = sanitize_text_field($_POST['app_height']);
				$appropriates[0]['app_width']         = sanitize_text_field($_POST['app_width']);
			}else {
				$appropriates[0]['app_width']         = $form_width_size;
			}

			// Return the data
			wp_send_json([
				'form_html' => $formHTML,
				'appropriates' => $appropriates
			]);

			// Don't forget to exit
			exit;
		}

		// AJAX callback function Update preview styles
		function ai_app_onsite_update_style_properties_only_callback() {
			global $wpdb;

			// Validate AJAX and nonce
			if (
				!isset($_POST['action']) ||
				sanitize_text_field(wp_unslash($_POST['action'])) !== 'ai_app_onsite_update_style_properties_only' ||
				!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');
			}

			// Get sanitized values
			$titleColorsJson   = isset($_POST['titleColors']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['titleColors']))) : '';
			$fontColorsJson    = isset($_POST['fontColor']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['fontColor']))) : '';
			$bgColorsJson      = isset($_POST['bgColor']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['bgColor']))) : '';
			$btnColorsJson     = isset($_POST['btnColor']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['btnColor']))) : '';
			$btnFontColorsJson = isset($_POST['btnFontColor']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['btnFontColor']))) : '';
			$responseBgColor   = isset($_POST['responseBgColor']) ? stripslashes(sanitize_text_field(wp_unslash($_POST['responseBgColor']))) : '';
			$app_corner        = isset($_POST['app-corner']) ? sanitize_text_field(wp_unslash($_POST['app-corner'])) : '';
			$app_height        = isset($_POST['app-height']) ? sanitize_text_field(wp_unslash($_POST['app-height'])) : '';
			$app_width         = isset($_POST['app-width']) ? sanitize_text_field(wp_unslash($_POST['app-width'])) : '';

			$table_name = $wpdb->prefix . 'ai_app_onsite_app_properties';
			$existing_settings = $wpdb->get_row("SELECT * FROM $table_name WHERE app_id = 1");

			if ($existing_settings) {
				$updated = $wpdb->update(
					$table_name,
					array(
						'title_color'       => $titleColorsJson,
						'font_color'        => $fontColorsJson,
						'bg_color'          => $bgColorsJson,
						'btn_color'         => $btnColorsJson,
						'btn_font_color'    => $btnFontColorsJson,
						'response_bg_color' => $responseBgColor,
						'app_corner'        => $app_corner,
						'app_height'        => $app_height
					),
					array('id' => $existing_settings->id),
					array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'),
					array('%d')
				);

				// Update app_width in field selector table
				$table_field_selector = $wpdb->prefix . 'ai_app_onsite_field_selector_settings';
				$wpdb->update(
					$table_field_selector,
					array(
						'app_width' => $app_width
					),
					array('app_id' => "1"),
					array('%d'),
					array('%d')
				);	

				if ($wpdb->last_error) {
					wp_send_json_error('Error saving data: ' . $wpdb->last_error);
				}

				wp_send_json_success('Settings updated successfully.');
			} else {
				wp_send_json_error('No existing settings found to update.');
			}
		}

		// Define shortcode function
		public function ai_app_onsite_create_openAi_app_form_shortcode(): string {
			global $wpdb;
			$table_appropriate = $wpdb->prefix . 'ai_app_onsite_app_properties';
			$appropriates = $wpdb->get_results("SELECT * FROM $table_appropriate WHERE app_id = 1", ARRAY_A);

			// Check if agree_terms from plugin settings table is set to true
			$table_plugin_settings = $wpdb->prefix . 'ai_app_onsite_plugin_settings';
			$agree_terms = false;
			if ($wpdb->get_var("SHOW TABLES LIKE '$table_plugin_settings'") == $table_plugin_settings) {
				$plugin_settings = $wpdb->get_row("SELECT agree_terms FROM $table_plugin_settings WHERE id = 1", ARRAY_A);
				if ($plugin_settings && isset($plugin_settings['agree_terms']) && $plugin_settings['agree_terms'] === '1') {
					$agree_terms = true;
				} 

			}

			// If agree_terms is false, return an error message
			if (!$agree_terms) {
				return '';
			}
			

			// Make AJAX call to retrieve form HTML
			$form_html_json = wp_remote_get(admin_url('admin-ajax.php') . '?action=ai_app_onsite_create_app_preview_form');

			// Check if request was successful and data is available
			if (!is_wp_error($form_html_json) && $form_html_json['response']['code'] == 200) {
				// Decode JSON response
				$form_html = json_decode($form_html_json['body'], true);
				$form_html = $form_html['form_html'];

				// Check if decoding was successful
				if ($form_html !== null) {
				$background_style = $this->appProperty['background_style'] ?? self::build_background_style($this->appProperty['background_color']);
				$response_bg_style = $this->appProperty['response_bg_style'] ?? self::build_background_style($this->appProperty['response_bg_color']);
				$response_container_style_parts = array_filter([
					$background_style,
					$this->appProperty['app_corner'] ?? '',
					$this->appProperty['app_height'] ?? '',
				]);
				$response_container_style = trim(implode(' ', $response_container_style_parts));

				// Use $this->appProperty here
				$form_html .= '<div id="ai-app-result-wrapper" class="ai-app-form-wrap" style="' . esc_attr($response_container_style) . '">
                    <div id="ai-app-motivational-heading"  style="margin-bottom: 10px;">
						<h6>' . (!empty($this->appProperty['response_header']) ? esc_html($this->appProperty['response_header']) : esc_html($this->appProperty['app_name'] . ' Feedback:')) . '</h6>
                    </div>
            
                    <div id="ai-app-result" style="' . esc_attr($response_bg_style) . '"></div>
                    <input type="hidden" id="ai_response_id" value="">

                    <div class="ai-app-feedback-section" id="ai-app-feedback-section">
                        <div class="align-items-center text-center" id="ai-app-feedback-btns">
                        <div class="like grow">
                            <i class="fa fa-thumbs-up fa-2x like" aria-hidden="true"></i>
                        </div>
                        <div class="dislike grow">
                            <i class="fa fa-thumbs-down fa-2x like" aria-hidden="true"></i>
                        </div>
                        </div>
                        <p id="ai-feedback-response" style="display:none; color:#000; margin-top:10px;text-align:center">Thank you for your feedback!</p>
                    </div>
					<h2 id="ai-app-result-message" class="ai-app-result-message" ' . $this->appProperty['app_description_color'] . '></h2>
            
                    <div class="ai-app-refresh-btn">
                        <button id="ai-app-refresh" onClick="refreshPage()" ' . $this->appProperty['btn_color'] . $this->appProperty['btn_font_color'] . '>Try ' . $this->appProperty['app_name'] . ' Again</button>
                    </div>
            
                    <p class="ai-app-disclaimer-text example-text" ' . $this->appProperty['small_font_color'] . '><span class="disclaimer-heading">Disclaimer: </span>' . $this->appProperty['app_disclaimer'] . '</p>
                </div>';

					return $form_html; // Return decoded form HTML
				} else {
					return 'Error decoding JSON'; // Return error message if decoding failed
				}
			} else {
				return 'Error fetching form HTML'; // Return error message if AJAX request failed
			}
		}

		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' => 'No rows found in the table.');

				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;
		}
	}

	new AI_APP_ONSITE_App_Preview_Handler(); // Instantiate the class
}
