<?php
namespace TeknoTok\AiTranslator\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Controller to manage plugin admin settings and menus.
 */
class SettingsController {
	/**
	 * Plugin coordinator.
	 *
	 * @var \TeknoTok\AiTranslator\Plugin
	 */
	private $plugin;

	/**
	 * Constructor.
	 *
	 * @param \TeknoTok\AiTranslator\Plugin $plugin Plugin instance.
	 */
	public function __construct( $plugin ) {
		$this->plugin = $plugin;

		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'admin_post_teknotok_ait_save_settings', array( $this, 'handle_admin_post' ) );
		add_action( 'wp_ajax_teknotok_ait_save_settings', array( $this, 'ajax_save_settings' ) );
		add_action( 'wp_ajax_teknotok_ait_set_uninstall_cleanup', array( $this, 'ajax_set_uninstall_cleanup' ) );
	}

	/**
	 * Register administration menus.
	 *
	 * @return void
	 */
	public function register_menu() {
		$capability = 'manage_options';

		add_menu_page(
			__( 'AI Translator', 'teknotok-ai-translator' ),
			__( 'AI Translator', 'teknotok-ai-translator' ),
			$capability,
			'teknotok-ait',
			array( $this, 'render_settings' ),
			'dashicons-translation',
			56
		);

		add_submenu_page(
			'teknotok-ait',
			__( 'Settings', 'teknotok-ai-translator' ),
			__( 'Settings', 'teknotok-ai-translator' ),
			$capability,
			'teknotok-ait',
			array( $this, 'render_settings' )
		);
	}

	/**
	 * Enqueue admin CSS and JS.
	 *
	 * @param string $hook Hook suffix.
	 * @return void
	 */
	public function enqueue_assets( $hook ) {
		$is_settings_page = false !== strpos( $hook, 'teknotok-ait' );
		$is_plugins_page  = 'plugins.php' === $hook;

		if ( ! $is_settings_page && ! $is_plugins_page ) {
			return;
		}

		wp_enqueue_style( 'teknotok-ait-admin', TEKNOTOK_AIT_URL . 'assets/css/admin.css', array(), TEKNOTOK_AIT_VERSION );
		wp_enqueue_script( 'teknotok-ait-admin', TEKNOTOK_AIT_URL . 'assets/js/admin.js', array( 'jquery' ), TEKNOTOK_AIT_VERSION, true );

		wp_localize_script(
			'teknotok-ait-admin',
			'teknotokAitAdmin',
			array(
				'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
				'nonce'         => wp_create_nonce( 'teknotok_ait_ajax' ),
				'isPluginsPage' => $is_plugins_page ? 1 : 0,
			)
		);
	}

	/**
	 * Handle settings post actions.
	 *
	 * @return void
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$action = sanitize_key( wp_unslash( $_POST['teknotok_ait_action'] ?? '' ) );
		if ( empty( $action ) ) {
			return;
		}

		if ( 'save_settings' === $action ) {
			check_admin_referer( 'teknotok_ait_save_settings' );
			$this->save_settings();
		}

	}

	/**
	 * Handle settings saves through admin-post.php.
	 *
	 * @return void
	 */
	public function handle_admin_post() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'teknotok-ai-translator' ), 403 );
		}

		check_admin_referer( 'teknotok_ait_save_settings' );
		$this->save_settings();

		wp_safe_redirect( admin_url( 'admin.php?page=teknotok-ait&settings-updated=1' ) );
		exit;
	}

	/**
	 * AJAX handler for saving settings without starting translation.
	 *
	 * @return void
	 */
	public function ajax_save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'teknotok-ai-translator' ) ), 403 );
		}

		$nonce = sanitize_key( wp_unslash( $_POST['_wpnonce'] ?? '' ) );
		if ( ! wp_verify_nonce( $nonce, 'teknotok_ait_save_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'teknotok-ai-translator' ) ), 403 );
		}

		unset( $_POST['teknotok_ait_start_translation'] );
		$_POST['teknotok_ait_action'] = 'save_settings';

		$this->save_settings();

		wp_send_json_success( array( 'message' => __( 'Settings saved successfully.', 'teknotok-ai-translator' ) ) );
	}

	/**
	 * Save settings fields.
	 *
	 * @return void
	 */
	private function save_settings() {
		$current = get_option( 'teknotok_ait_settings', array() );
		$is_premium = \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active();
		$source_language = sanitize_key( wp_unslash( $_POST['source_language'] ?? 'en' ) );

		// Target languages
		$targets = array();
		if ( isset( $_POST['target_languages'] ) && is_array( $_POST['target_languages'] ) ) {
			$targets = array_values( array_unique( array_filter( array_map( 'sanitize_key', wp_unslash( $_POST['target_languages'] ) ) ) ) );
		}

		$targets = \TeknoTok\AiTranslator\Plugin::normalize_target_languages( $targets, $source_language, $is_premium );

		$start_translation = ! empty( $_POST['teknotok_ait_start_translation'] );
		if ( $start_translation && empty( $targets ) ) {
			add_settings_error( 'teknotok_ait_settings', 'no_targets_selected', __( 'Select at least one target language before starting translation.', 'teknotok-ai-translator' ), 'error' );
			return;
		}

		// Force TeknoTok API provider and clear any stored OpenAI settings
		$api_provider = 'teknotok';
		$openai_key   = '';
		$openai_model = 'gpt-4o-mini';

		$design_settings = \TeknoTok\AiTranslator\Frontend\SwitcherController::sanitize_design_settings(
			array(
				'switcher_design_preset' => wp_unslash( $_POST['switcher_design_preset'] ?? ( $current['switcher_design_preset'] ?? 'glass' ) ),
				'switcher_show_flags'    => ! empty( $_POST['switcher_show_flags'] ) ? '1' : '0',
				'switcher_opacity'       => wp_unslash( $_POST['switcher_opacity'] ?? ( $current['switcher_opacity'] ?? 92 ) ),
				'switcher_text_color'    => wp_unslash( $_POST['switcher_text_color'] ?? ( $current['switcher_text_color'] ?? '#1e293b' ) ),
				'switcher_bg_color'      => wp_unslash( $_POST['switcher_bg_color'] ?? ( $current['switcher_bg_color'] ?? '#ffffff' ) ),
				'switcher_border_color'  => wp_unslash( $_POST['switcher_border_color'] ?? ( $current['switcher_border_color'] ?? '#93c5fd' ) ),
				'switcher_accent_color'  => wp_unslash( $_POST['switcher_accent_color'] ?? ( $current['switcher_accent_color'] ?? '#2563eb' ) ),
				'switcher_shape'         => wp_unslash( $_POST['switcher_shape'] ?? ( $current['switcher_shape'] ?? 'pill' ) ),
				'switcher_border_width'  => wp_unslash( $_POST['switcher_border_width'] ?? ( $current['switcher_border_width'] ?? 1 ) ),
			)
		);

		$settings = array_merge( array(
			'api_provider'     => $api_provider,
			'openai_key'       => $openai_key,
			'openai_model'     => $openai_model,
			'source_language'  => $source_language,
			'target_languages' => $targets,
			'switcher_position'=> sanitize_text_field( wp_unslash( $_POST['switcher_position'] ?? 'floating-bottom-right' ) ),
			'hide_powered_by'  => ( $is_premium && ! empty( $_POST['hide_powered_by'] ) ) ? '1' : '0',
			'detect_browser'   => ! empty( $_POST['detect_browser'] ) ? '1' : '0',
			'auto_translate'   => ! empty( $_POST['auto_translate'] ) ? '1' : '0',
			'url_mode'         => 'subfolder',
			'gateway_base_url' => 'https://soft.teknotok.com',
			'translation_tone' => sanitize_key( wp_unslash( $_POST['translation_tone'] ?? 'standard' ) ),
			'queue_batch_size' => 10,
			'delete_data_on_uninstall' => $current['delete_data_on_uninstall'] ?? '0',
		), $design_settings );

		update_option( 'teknotok_ait_settings', $settings, false );
		if ( \TeknoTok\AiTranslator\Plugin::has_valid_target_language_configured() ) {
			update_option( 'teknotok_ait_setup_complete', '1', false );
		}

		// Check if target languages changed and schedule background download
		$old_targets = $current['target_languages'] ?? array();
		$new_targets = $settings['target_languages'] ?? array();
		$added_targets = array_diff( $new_targets, $old_targets );
		$removed_targets = array_diff( $old_targets, $new_targets );
		$queue_targets = ! empty( $added_targets ) ? $added_targets : ( $start_translation ? $new_targets : array() );
		$queued_translation = ! empty( $queue_targets );
		$cancelled_removed_jobs = 0;
		$deleted_removed_translations = 0;

		if ( ! empty( $removed_targets ) ) {
			$cancelled_removed_jobs = \TeknoTok\AiTranslator\Queue\QueueManager::cancel_jobs_for_languages( $removed_targets );
			$deleted_removed_translations = \TeknoTok\AiTranslator\Database\MemoryRepository::delete_translations_for_languages( $removed_targets );
			if ( $cancelled_removed_jobs > 0 ) {
				add_settings_error(
					'teknotok_ait_settings',
					'removed_language_jobs_cancelled',
					sprintf(
						/* translators: 1: number of jobs, 2: comma-separated language codes */
						_n(
							'Cancelled %1$d unfinished translation job for removed language: %2$s.',
							'Cancelled %1$d unfinished translation jobs for removed languages: %2$s.',
							$cancelled_removed_jobs,
							'teknotok-ai-translator'
						),
						$cancelled_removed_jobs,
						implode( ', ', array_map( 'sanitize_key', $removed_targets ) )
					),
					'success'
				);
			}

			if ( $deleted_removed_translations > 0 ) {
				add_settings_error(
					'teknotok_ait_settings',
					'removed_language_translations_deleted',
					sprintf(
						/* translators: 1: number of translations, 2: comma-separated language codes */
						_n(
							'Deleted %1$d saved translation for removed language: %2$s.',
							'Deleted %1$d saved translations for removed languages: %2$s.',
							$deleted_removed_translations,
							'teknotok-ai-translator'
						),
						$deleted_removed_translations,
						implode( ', ', array_map( 'sanitize_key', $removed_targets ) )
					),
					'success'
				);
			}
		}

		if ( $queued_translation ) {
			if ( $start_translation && get_option( 'teknotok_ait_queue_paused', '0' ) === '1' ) {
				$pause_reason = get_option( 'teknotok_ait_queue_pause_reason', '' );
				if ( ! \TeknoTok\AiTranslator\Utils\ErrorSanitizer::is_limit_message( $pause_reason ) ) {
					\TeknoTok\AiTranslator\Queue\QueueManager::resume_after_provider_limit();
				}
			}

			// Try WooCommerce's Action Scheduler first for instant background execution, fallback to WP Cron + spawn_cron
			if ( function_exists( 'as_enqueue_async_action' ) && ! \TeknoTok\AiTranslator\Queue\QueueManager::is_sqlite_active() ) {
				as_enqueue_async_action( 'teknotok_ait_download_translations', array( $queue_targets ), 'teknotok-ait' );
			} else {
				wp_schedule_single_event( time(), 'teknotok_ait_download_translations', array( $queue_targets ) );
				$site_url = get_site_url();
				$is_localhost = ( strpos( $site_url, 'localhost' ) !== false || strpos( $site_url, '127.0.0.1' ) !== false );
				if ( ! $is_localhost ) {
					spawn_cron();
				}
			}

			$this->plugin->queue_existing_content_for_targets( $queue_targets );
		}

		// Flush rewrite rules dynamically when URL mode or target languages change
		if ( ( $current['url_mode'] ?? 'query' ) !== $settings['url_mode'] || $old_targets !== $new_targets ) {
			flush_rewrite_rules();
		}

		if ( $queued_translation ) {
			add_settings_error(
				'teknotok_ait_settings',
				'translation_started',
				sprintf(
					wp_kses_post( __( 'Translation started successfully. You can monitor the progress on the <a href="%s">Translation Status</a> page.', 'teknotok-ai-translator' ) ),
					admin_url( 'admin.php?page=teknotok-ait-diagnostics' )
				),
				'success'
			);

			if ( $start_translation ) {
				wp_safe_redirect( admin_url( 'admin.php?page=teknotok-ait-diagnostics&setup=start' ) );
				exit;
			}
		} else {
			add_settings_error( 'teknotok_ait_settings', 'settings_saved', __( 'Settings saved successfully.', 'teknotok-ai-translator' ), 'success' );
		}
	}

	/**
	 * Render settings screen.
	 *
	 * @return void
	 */
	public function render_settings() {
		$settings = get_option( 'teknotok_ait_settings', array() );
		$is_premium = \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active();
		$max_target_languages = \TeknoTok\AiTranslator\Plugin::get_max_target_languages( $is_premium );

		$source_language = $settings['source_language'] ?? 'en';
		$languages = \TeknoTok\AiTranslator\Plugin::get_supported_languages_by_priority();
		$selected_targets = \TeknoTok\AiTranslator\Plugin::normalize_target_languages( $settings['target_languages'] ?? array(), $source_language, $is_premium );
		$target_language_options = array_diff_key( $languages, array( $source_language => true ) );
		$design_presets = \TeknoTok\AiTranslator\Frontend\SwitcherController::get_design_presets();
		$design_settings = \TeknoTok\AiTranslator\Frontend\SwitcherController::sanitize_design_settings( $settings );

		// Render main container
		?>
		<div class="wrap teknotok-ait-wrap">
			<h1><?php esc_html_e( 'TeknoTok AI Translator', 'teknotok-ai-translator' ); ?></h1>
			<?php settings_errors(); ?>

			<div class="teknotok-ait-container">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( 'teknotok_ait_save_settings' ); ?>
					<input type="hidden" name="action" value="teknotok_ait_save_settings" />
					<input type="hidden" name="teknotok_ait_action" value="save_settings" />

					<div class="teknotok-settings-panel teknotok-start-panel">
						<h2><?php esc_html_e( 'Start translating your site', 'teknotok-ai-translator' ); ?></h2>
						<p class="subtitle"><?php esc_html_e( 'Choose your original language and the languages you want visitors to use. TeknoTok will translate existing content in the background.', 'teknotok-ai-translator' ); ?></p>
						<table class="form-table">
							<tr>
								<th scope="row"><label for="source_language"><?php esc_html_e( 'Source Language', 'teknotok-ai-translator' ); ?></label></th>
								<td>
									<select name="source_language" id="source_language">
										<?php foreach ( $languages as $code => $name ) : ?>
											<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $settings['source_language'] ?? 'en', $code ); ?>><?php echo esc_html( $name ); ?></option>
										<?php endforeach; ?>
									</select>
									<p class="description"><?php esc_html_e( 'Original language of your WordPress website.', 'teknotok-ai-translator' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Target Languages', 'teknotok-ai-translator' ); ?></th>
								<td>
									<div class="teknotok-language-picker" data-is-premium="<?php echo esc_attr( $is_premium ? '1' : '0' ); ?>" data-max-target-languages="<?php echo esc_attr( $max_target_languages ); ?>">
										<div class="teknotok-language-picker-head">
											<div>
												<strong><?php esc_html_e( 'Target languages', 'teknotok-ai-translator' ); ?></strong>
												<span class="teknotok-language-total-count">
													<?php
													printf(
														esc_html__( '%d selected', 'teknotok-ai-translator' ),
														count( $selected_targets )
													);
													?>
												</span>
											</div>
											<button type="button" class="button button-secondary teknotok-open-language-drawer">
												<?php esc_html_e( 'Choose languages', 'teknotok-ai-translator' ); ?>
											</button>
										</div>
										<div class="teknotok-selected-languages">
											<?php if ( empty( $selected_targets ) ) : ?>
												<span class="teknotok-selected-empty"><?php esc_html_e( 'No target language selected yet.', 'teknotok-ai-translator' ); ?></span>
											<?php endif; ?>
											<?php foreach ( $selected_targets as $code ) : ?>
												<?php if ( isset( $languages[ $code ] ) ) : ?>
													<span class="teknotok-selected-language" data-language-code="<?php echo esc_attr( $code ); ?>"><?php echo esc_html( $languages[ $code ] ); ?></span>
												<?php endif; ?>
											<?php endforeach; ?>
										</div>
										<div class="teknotok-language-drawer" aria-hidden="true">
											<div class="teknotok-language-drawer-backdrop"></div>
											<div class="teknotok-language-drawer-panel" role="dialog" aria-modal="true" aria-labelledby="teknotok-language-drawer-title">
												<div class="teknotok-language-drawer-header">
													<div>
														<h3 id="teknotok-language-drawer-title"><?php esc_html_e( 'Select target languages', 'teknotok-ai-translator' ); ?></h3>
														<p>
															<?php
															echo esc_html(
																$is_premium
																	? sprintf(
																		/* translators: %d: maximum premium target language count */
																		__( 'Search and select up to %d languages your customers can use.', 'teknotok-ai-translator' ),
																		$max_target_languages
																	)
																	: __( 'Free stores can select one target language.', 'teknotok-ai-translator' )
															);
															?>
														</p>
													</div>
													<button type="button" class="button-link teknotok-close-language-drawer" aria-label="<?php esc_attr_e( 'Close language picker', 'teknotok-ai-translator' ); ?>">
														<span class="dashicons dashicons-no-alt"></span>
													</button>
												</div>
												<label class="screen-reader-text" for="teknotok-language-search"><?php esc_html_e( 'Search target languages', 'teknotok-ai-translator' ); ?></label>
												<input type="search" id="teknotok-language-search" class="teknotok-language-search" placeholder="<?php esc_attr_e( 'Search language...', 'teknotok-ai-translator' ); ?>" />
												<p class="teknotok-inline-warning teknotok-language-warning teknotok-free-language-warning" role="alert" aria-live="polite" style="display: none;"><?php esc_html_e( 'Free stores can select just one target language.', 'teknotok-ai-translator' ); ?></p>
												<p class="teknotok-inline-warning teknotok-language-warning teknotok-max-language-warning" role="alert" aria-live="polite" style="display: none;">
													<?php
													printf(
														/* translators: %d: maximum premium target language count */
														esc_html__( 'You can select up to %d target languages. Remove one selected language before adding another.', 'teknotok-ai-translator' ),
														$max_target_languages
													);
													?>
												</p>
												<div class="teknotok-language-groups">
													<div class="teknotok-language-list-card">
														<div class="teknotok-languages-grid teknotok-languages-grid-simple">
															<?php foreach ( $target_language_options as $code => $name ) : ?>
																<?php $checked = in_array( $code, $selected_targets, true ); ?>
																<label class="teknotok-lang-checkbox-label <?php echo esc_attr( $checked ? 'is-selected' : '' ); ?>" data-language-name="<?php echo esc_attr( strtolower( $name . ' ' . $code ) ); ?>">
																	<input type="checkbox" name="target_languages[]" value="<?php echo esc_attr( $code ); ?>" data-language-name="<?php echo esc_attr( $name ); ?>" <?php checked( $checked ); ?> />
																	<span><?php echo esc_html( $name ); ?></span>
																</label>
															<?php endforeach; ?>
														</div>
													</div>
													<p class="teknotok-language-empty-search" style="display: none;"><?php esc_html_e( 'No languages match your search.', 'teknotok-ai-translator' ); ?></p>
												</div>
												<div class="teknotok-language-drawer-footer">
													<button type="button" class="button button-primary teknotok-close-language-drawer"><?php esc_html_e( 'Apply selection', 'teknotok-ai-translator' ); ?></button>
												</div>
											</div>
										</div>
									</div>
								</td>
							</tr>
						</table>

						<details class="teknotok-settings-advanced">
							<summary><?php esc_html_e( 'Advanced settings', 'teknotok-ai-translator' ); ?></summary>
							<table class="form-table">
								<tr>
									<th scope="row"><label for="auto_translate"><?php esc_html_e( 'Auto-Translate New Content', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<label class="teknotok-toggle-container">
											<input type="checkbox" name="auto_translate" id="auto_translate" value="1" <?php checked( $settings['auto_translate'] ?? '1', '1' ); ?> class="teknotok-toggle-input" />
											<span class="teknotok-toggle-track"></span>
											<span class="description"><?php esc_html_e( 'Automatically queue translation jobs when saving or updating posts/products.', 'teknotok-ai-translator' ); ?></span>
										</label>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="translation_tone"><?php esc_html_e( 'Translation Tone', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<select name="translation_tone" id="translation_tone">
											<option value="standard" <?php selected( $settings['translation_tone'] ?? 'standard', 'standard' ); ?>><?php esc_html_e( 'Standard (Natural)', 'teknotok-ai-translator' ); ?></option>
											<option value="formal" <?php selected( $settings['translation_tone'] ?? '', 'formal' ); ?>><?php esc_html_e( 'Formal (Professional/Polite)', 'teknotok-ai-translator' ); ?></option>
											<option value="casual" <?php selected( $settings['translation_tone'] ?? '', 'casual' ); ?>><?php esc_html_e( 'Casual (Friendly/Informal)', 'teknotok-ai-translator' ); ?></option>
										</select>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="switcher_position"><?php esc_html_e( 'Language Switcher', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<select name="switcher_position" id="switcher_position">
											<option value="floating-bottom-right" <?php selected( $settings['switcher_position'] ?? 'floating-bottom-right', 'floating-bottom-right' ); ?>><?php esc_html_e( 'Floating Bottom Right', 'teknotok-ai-translator' ); ?></option>
											<option value="floating-bottom-left" <?php selected( $settings['switcher_position'] ?? '', 'floating-bottom-left' ); ?>><?php esc_html_e( 'Floating Bottom Left', 'teknotok-ai-translator' ); ?></option>
											<option value="header" <?php selected( $settings['switcher_position'] ?? '', 'header' ); ?>><?php esc_html_e( 'Header Hook', 'teknotok-ai-translator' ); ?></option>
											<option value="footer" <?php selected( $settings['switcher_position'] ?? '', 'footer' ); ?>><?php esc_html_e( 'Footer Hook', 'teknotok-ai-translator' ); ?></option>
											<option value="shortcode" <?php selected( $settings['switcher_position'] ?? '', 'shortcode' ); ?>><?php esc_html_e( 'Shortcode only ([teknotok_language_switcher])', 'teknotok-ai-translator' ); ?></option>
										</select>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="switcher_design_preset"><?php esc_html_e( 'Switcher Design', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<div class="teknotok-widget-designer" data-presets="<?php echo esc_attr( wp_json_encode( $design_presets ) ); ?>">
											<div class="teknotok-widget-designer-controls">
												<label>
													<span><?php esc_html_e( 'Ready design', 'teknotok-ai-translator' ); ?></span>
													<select name="switcher_design_preset" id="switcher_design_preset" data-teknotok-widget-control="preset">
														<?php foreach ( $design_presets as $preset_key => $preset ) : ?>
															<option value="<?php echo esc_attr( $preset_key ); ?>" <?php selected( $design_settings['switcher_design_preset'], $preset_key ); ?>><?php echo esc_html( $preset['label'] ); ?></option>
														<?php endforeach; ?>
													</select>
												</label>
												<label class="teknotok-widget-toggle">
													<input type="checkbox" name="switcher_show_flags" value="1" <?php checked( $design_settings['switcher_show_flags'], '1' ); ?> data-teknotok-widget-control="show_flags" />
													<span><?php esc_html_e( 'Show icons', 'teknotok-ai-translator' ); ?></span>
												</label>
												<label>
													<span><?php esc_html_e( 'Opacity', 'teknotok-ai-translator' ); ?></span>
													<input type="range" name="switcher_opacity" min="40" max="100" step="1" value="<?php echo esc_attr( $design_settings['switcher_opacity'] ); ?>" data-teknotok-widget-control="opacity" />
												</label>
												<div class="teknotok-widget-colors">
													<label>
														<span><?php esc_html_e( 'Text', 'teknotok-ai-translator' ); ?></span>
														<input type="color" name="switcher_text_color" value="<?php echo esc_attr( $design_settings['switcher_text_color'] ); ?>" data-teknotok-widget-control="text_color" />
													</label>
													<label>
														<span><?php esc_html_e( 'Background', 'teknotok-ai-translator' ); ?></span>
														<input type="color" name="switcher_bg_color" value="<?php echo esc_attr( $design_settings['switcher_bg_color'] ); ?>" data-teknotok-widget-control="background_color" />
													</label>
													<label>
														<span><?php esc_html_e( 'Accent', 'teknotok-ai-translator' ); ?></span>
														<input type="color" name="switcher_accent_color" value="<?php echo esc_attr( $design_settings['switcher_accent_color'] ); ?>" data-teknotok-widget-control="accent_color" />
													</label>
													<label>
														<span><?php esc_html_e( 'Border', 'teknotok-ai-translator' ); ?></span>
														<input type="color" name="switcher_border_color" value="<?php echo esc_attr( $design_settings['switcher_border_color'] ); ?>" data-teknotok-widget-control="border_color" />
													</label>
												</div>
												<label>
													<span><?php esc_html_e( 'Shape', 'teknotok-ai-translator' ); ?></span>
													<select name="switcher_shape" data-teknotok-widget-control="shape">
														<option value="pill" <?php selected( $design_settings['switcher_shape'], 'pill' ); ?>><?php esc_html_e( 'Pill', 'teknotok-ai-translator' ); ?></option>
														<option value="rounded" <?php selected( $design_settings['switcher_shape'], 'rounded' ); ?>><?php esc_html_e( 'Rounded', 'teknotok-ai-translator' ); ?></option>
														<option value="square" <?php selected( $design_settings['switcher_shape'], 'square' ); ?>><?php esc_html_e( 'Square', 'teknotok-ai-translator' ); ?></option>
													</select>
												</label>
												<label>
													<span><?php esc_html_e( 'Border size', 'teknotok-ai-translator' ); ?></span>
													<input type="number" name="switcher_border_width" min="0" max="4" step="1" value="<?php echo esc_attr( $design_settings['switcher_border_width'] ); ?>" data-teknotok-widget-control="border_width" />
												</label>
											</div>
											<div class="teknotok-widget-preview" aria-live="polite">
												<div class="teknotok-widget-preview-surface">
													<div class="teknotok-ait-switcher-container teknotok-ait-design-<?php echo esc_attr( sanitize_html_class( $design_settings['switcher_design_preset'] ) ); ?> teknotok-ait-shape-<?php echo esc_attr( sanitize_html_class( $design_settings['switcher_shape'] ) ); ?> <?php echo esc_attr( '0' === $design_settings['switcher_show_flags'] ? 'teknotok-ait-no-flags' : '' ); ?>">
														<div class="teknotok-ait-selected-lang" role="presentation">
															<img src="<?php echo esc_url( \TeknoTok\AiTranslator\Frontend\SwitcherController::get_flag_url( $source_language ) ); ?>" class="teknotok-ait-flag" alt="<?php echo esc_attr( $source_language ); ?>" />
															<span class="teknotok-ait-label">English</span>
															<span class="teknotok-ait-arrow" aria-hidden="true"></span>
														</div>
														<ul class="teknotok-ait-languages-dropdown" role="presentation">
															<li class="active"><a><img src="<?php echo esc_url( \TeknoTok\AiTranslator\Frontend\SwitcherController::get_flag_url( 'en' ) ); ?>" class="teknotok-ait-flag" alt="en" />English</a></li>
															<li><a><img src="<?php echo esc_url( \TeknoTok\AiTranslator\Frontend\SwitcherController::get_flag_url( 'es' ) ); ?>" class="teknotok-ait-flag" alt="es" />Español</a></li>
															<li><a><img src="<?php echo esc_url( \TeknoTok\AiTranslator\Frontend\SwitcherController::get_flag_url( 'fr' ) ); ?>" class="teknotok-ait-flag" alt="fr" />Français</a></li>
															<li class="teknotok-ait-referral-item"><a><span class="teknotok-ait-referral-title">Powered by TeknoTok</span></a></li>
														</ul>
													</div>
												</div>
											</div>
										</div>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="hide_powered_by"><?php esc_html_e( 'Powered by TeknoTok', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<label class="teknotok-toggle-container">
											<input type="checkbox" name="hide_powered_by" id="hide_powered_by" value="1" <?php checked( $settings['hide_powered_by'] ?? '0', '1' ); ?> <?php disabled( ! $is_premium ); ?> class="teknotok-toggle-input" />
											<span class="teknotok-toggle-track"></span>
											<span class="description">
												<?php
												echo esc_html(
													$is_premium
														? __( 'Hide the small switcher attribution link on your frontend.', 'teknotok-ai-translator' )
														: __( 'Free sites keep the small switcher attribution link. Pro sites can hide it.', 'teknotok-ai-translator' )
												);
												?>
											</span>
										</label>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="detect_browser"><?php esc_html_e( 'Detect Browser Language', 'teknotok-ai-translator' ); ?></label></th>
									<td>
										<label class="teknotok-toggle-container">
											<input type="checkbox" name="detect_browser" id="detect_browser" value="1" <?php checked( $settings['detect_browser'] ?? '1', '1' ); ?> class="teknotok-toggle-input" />
											<span class="teknotok-toggle-track"></span>
											<span class="description"><?php esc_html_e( 'Ask visitors to switch language when their browser language matches a target language.', 'teknotok-ai-translator' ); ?></span>
										</label>
									</td>
								</tr>
							</table>
						</details>

						<p id="teknotok-start-translation" class="submit teknotok-start-actions">
							<button type="submit" name="teknotok_ait_save_settings" value="1" class="button button-secondary button-hero">
								<?php esc_html_e( 'Save settings', 'teknotok-ai-translator' ); ?>
							</button>
							<button type="submit" name="teknotok_ait_start_translation" value="1" class="button button-primary button-hero">
								<?php esc_html_e( 'Save and start translating my site', 'teknotok-ai-translator' ); ?>
							</button>
						</p>
					</div>



				</form>

				<div class="teknotok-settings-panel teknotok-service-panel">
					<div class="teknotok-service-content">
						<span class="teknotok-service-kicker"><?php esc_html_e( 'TeknoTok Soft', 'teknotok-ai-translator' ); ?></span>
						<h2><?php echo esc_html( $is_premium ? __( 'TeknoTok Support and Services', 'teknotok-ai-translator' ) : __( 'Need More From TeknoTok?', 'teknotok-ai-translator' ) ); ?></h2>
						<p>
							<?php
							echo esc_html(
								$is_premium
									? __( 'TeknoTok builds custom software services for websites, mobile apps, WordPress, WooCommerce, AI automation, and business systems.', 'teknotok-ai-translator' )
									: __( 'TeknoTok builds custom software services for websites, mobile apps, WordPress, WooCommerce, AI automation, and business systems.', 'teknotok-ai-translator' )
							);
							?>
						</p>
					</div>
					<div class="teknotok-service-actions">
						<a class="button button-primary teknotok-service-main-link" href="<?php echo esc_url( 'https://soft.teknotok.com/' ); ?>" target="_blank" rel="noopener noreferrer">
							<?php esc_html_e( 'Visit TeknoTok', 'teknotok-ai-translator' ); ?>
						</a>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * AJAX handler to save the uninstall cleanup preference.
	 *
	 * @return void
	 */
	public function ajax_set_uninstall_cleanup() {
		check_ajax_referer( 'teknotok_ait_ajax', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'teknotok-ai-translator' ) ), 403 );
		}

		$delete_data = ! empty( $_POST['delete_data'] ) ? '1' : '0';

		$settings = get_option( 'teknotok_ait_settings', array() );
		$settings['delete_data_on_uninstall'] = $delete_data;

		update_option( 'teknotok_ait_settings', $settings, false );

		wp_send_json_success();
	}
}
