<?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( '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 Pro', 'teknotok-ai-translator-pro' ),
			__( 'AI Translator', 'teknotok-ai-translator-pro' ),
			$capability,
			'teknotok-ait',
			array( $this, 'render_settings' ),
			'dashicons-translation',
			56
		);

		add_submenu_page(
			'teknotok-ait',
			__( 'Settings', 'teknotok-ai-translator-pro' ),
			__( 'Settings', 'teknotok-ai-translator-pro' ),
			$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;
		}

		if ( empty( $_POST['teknotok_ait_action'] ) ) {
			return;
		}

		$action = sanitize_key( wp_unslash( $_POST['teknotok_ait_action'] ) );

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

	/**
	 * Save settings fields.
	 *
	 * @return void
	 */
	private function save_settings() {
		$current = get_option( 'teknotok_ait_settings', array() );

		// Target languages
		$targets = isset( $_POST['target_languages'] ) && is_array( $_POST['target_languages'] ) ? array_map( 'sanitize_key', $_POST['target_languages'] ) : array();

		// Check license permissions if target count > 1
		if ( count( $targets ) > 1 && ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			// Limit to 1 target language for free/inactive license
			$targets = array_slice( $targets, 0, 1 );
			add_settings_error( 'teknotok_ait_settings', 'license_limit', __( 'An active license key is required to select multiple target languages.', 'teknotok-ai-translator-pro' ), 'error' );
		}

		$settings = array(
			'api_provider'     => 'teknotok',
			'source_language'  => sanitize_key( $_POST['source_language'] ?? 'en' ),
			'target_languages' => $targets,
			'switcher_position'=> sanitize_text_field( $_POST['switcher_position'] ?? 'floating-bottom-right' ),
			'detect_browser'   => ! empty( $_POST['detect_browser'] ) ? '1' : '0',
			'auto_translate'   => ! empty( $_POST['auto_translate'] ) ? '1' : '0',
			'url_mode'         => sanitize_key( $_POST['url_mode'] ?? 'subfolder' ),
			'gateway_base_url' => esc_url_raw( $_POST['gateway_base_url'] ?? 'https://soft.teknotok.com' ),
			'translation_tone' => sanitize_key( $_POST['translation_tone'] ?? 'standard' ),
			'queue_batch_size' => min( 50, max( 1, intval( $_POST['queue_batch_size'] ?? 10 ) ) ),
			'delete_data_on_uninstall' => ! empty( $_POST['delete_data_on_uninstall'] ) ? '1' : '0',
		);

		if ( ! in_array( $settings['url_mode'], array( 'subfolder', 'query' ), true ) ) {
			$settings['url_mode'] = 'subfolder';
		}
		if ( empty( $settings['gateway_base_url'] ) ) {
			$settings['gateway_base_url'] = 'https://soft.teknotok.com';
		}

		update_option( 'teknotok_ait_settings', $settings, 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 );

		if ( ! empty( $added_targets ) ) {
			$this->plugin->queue_existing_content_for_targets( $added_targets );

			// 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( $added_targets ), 'teknotok-ait' );
			} else {
				wp_schedule_single_event( time(), 'teknotok_ait_download_translations', array( $added_targets ) );
				spawn_cron();
			}
		}

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

		add_settings_error( 'teknotok_ait_settings', 'settings_saved', __( 'Settings saved successfully.', 'teknotok-ai-translator-pro' ), '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();

		$languages = array(
			'en' => __( 'English', 'teknotok-ai-translator-pro' ),
			'es' => __( 'Spanish', 'teknotok-ai-translator-pro' ),
			'tr' => __( 'Turkish', 'teknotok-ai-translator-pro' ),
			'zh' => __( 'Chinese', 'teknotok-ai-translator-pro' ),
			'hi' => __( 'Hindi', 'teknotok-ai-translator-pro' ),
			'ar' => __( 'Arabic', 'teknotok-ai-translator-pro' ),
			'pt' => __( 'Portuguese', 'teknotok-ai-translator-pro' ),
			'bn' => __( 'Bengali', 'teknotok-ai-translator-pro' ),
			'ru' => __( 'Russian', 'teknotok-ai-translator-pro' ),
			'ja' => __( 'Japanese', 'teknotok-ai-translator-pro' ),
			'fr' => __( 'French', 'teknotok-ai-translator-pro' ),
		);

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

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

					<div class="teknotok-settings-panel">
						<h2><?php esc_html_e( 'Translation Setup', 'teknotok-ai-translator-pro' ); ?></h2>
						<p class="subtitle"><?php esc_html_e( 'Choose the website language, target languages, translation style, and the visitor language switcher.', 'teknotok-ai-translator-pro' ); ?></p>
						<table class="form-table">
							<tr>
								<th scope="row"><label for="source_language"><?php esc_html_e( 'Source Language', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Target Languages', 'teknotok-ai-translator-pro' ); ?></th>
								<td>
									<div class="teknotok-languages-grid">
										<?php 
										$selected_targets = $settings['target_languages'] ?? array();
										foreach ( $languages as $code => $name ) : 
											if ( $code === ( $settings['source_language'] ?? 'en' ) ) {
												continue;
											}
											$checked = in_array( $code, $selected_targets, true );
											?>
											<label class="teknotok-lang-checkbox-label <?php echo $checked ? 'is-selected' : ''; ?>">
												<input type="checkbox" name="target_languages[]" value="<?php echo esc_attr( $code ); ?>" <?php checked( $checked ); ?> />
												<?php echo esc_html( $name ); ?>
											</label>
										<?php endforeach; ?>
									</div>
									<?php if ( ! $is_premium ) : ?>
										<p class="description teknotok-inline-warning">
											<?php esc_html_e( 'Free version allows 1 target language. Enter a license key in License Manager to unlock all target languages.', 'teknotok-ai-translator-pro' ); ?>
										</p>
									<?php endif; ?>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="auto_translate"><?php esc_html_e( 'Auto-Translate New Content', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?></span>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="translation_tone"><?php esc_html_e( 'Translation Tone', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?></option>
										<option value="formal" <?php selected( $settings['translation_tone'] ?? '', 'formal' ); ?>><?php esc_html_e( 'Formal (Professional/Polite)', 'teknotok-ai-translator-pro' ); ?></option>
										<option value="casual" <?php selected( $settings['translation_tone'] ?? '', 'casual' ); ?>><?php esc_html_e( 'Casual (Friendly/Informal)', 'teknotok-ai-translator-pro' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="switcher_position"><?php esc_html_e( 'Language Switcher', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?></option>
										<option value="floating-bottom-left" <?php selected( $settings['switcher_position'] ?? '', 'floating-bottom-left' ); ?>><?php esc_html_e( 'Floating Bottom Left', 'teknotok-ai-translator-pro' ); ?></option>
										<option value="header" <?php selected( $settings['switcher_position'] ?? '', 'header' ); ?>><?php esc_html_e( 'Header Hook', 'teknotok-ai-translator-pro' ); ?></option>
										<option value="footer" <?php selected( $settings['switcher_position'] ?? '', 'footer' ); ?>><?php esc_html_e( 'Footer Hook', 'teknotok-ai-translator-pro' ); ?></option>
										<option value="shortcode" <?php selected( $settings['switcher_position'] ?? '', 'shortcode' ); ?>><?php esc_html_e( 'Shortcode only ([teknotok_language_switcher])', 'teknotok-ai-translator-pro' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="detect_browser"><?php esc_html_e( 'Detect Browser Language', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?></span>
									</label>
								</td>
							</tr>
						</table>
					</div>

					<details class="teknotok-settings-panel teknotok-settings-advanced">
						<summary><?php esc_html_e( 'Advanced', 'teknotok-ai-translator-pro' ); ?></summary>
						<table class="form-table">
							<tr>
								<th scope="row"><label for="url_mode"><?php esc_html_e( 'URL Mode', 'teknotok-ai-translator-pro' ); ?></label></th>
								<td>
									<select name="url_mode" id="url_mode">
										<option value="subfolder" <?php selected( $settings['url_mode'] ?? 'subfolder', 'subfolder' ); ?>><?php esc_html_e( 'Subfolder (/es/page/)', 'teknotok-ai-translator-pro' ); ?></option>
										<option value="query" <?php selected( $settings['url_mode'] ?? '', 'query' ); ?>><?php esc_html_e( 'Query String (?lang=es)', 'teknotok-ai-translator-pro' ); ?></option>
									</select>
									<p class="description"><?php esc_html_e( 'Choose how translated URLs are generated.', 'teknotok-ai-translator-pro' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="gateway_base_url"><?php esc_html_e( 'Gateway Base URL', 'teknotok-ai-translator-pro' ); ?></label></th>
								<td>
									<input type="url" name="gateway_base_url" id="gateway_base_url" value="<?php echo esc_attr( $settings['gateway_base_url'] ?? 'https://soft.teknotok.com' ); ?>" class="regular-text" placeholder="https://soft.teknotok.com" />
									<p class="description"><?php esc_html_e( 'Central TeknoTok License Manager URL. Use your local License Manager URL for staging tests.', 'teknotok-ai-translator-pro' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="queue_batch_size"><?php esc_html_e( 'Queue Batch Size', 'teknotok-ai-translator-pro' ); ?></label></th>
								<td>
									<input type="number" name="queue_batch_size" id="queue_batch_size" value="<?php echo esc_attr( $settings['queue_batch_size'] ?? 10 ); ?>" min="1" max="50" step="1" class="small-text" />
									<p class="description"><?php esc_html_e( 'Jobs processed per background batch. Lower values are gentler on shared hosting.', 'teknotok-ai-translator-pro' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><label for="delete_data_on_uninstall"><?php esc_html_e( 'Uninstall Clean Up', 'teknotok-ai-translator-pro' ); ?></label></th>
								<td>
									<label class="teknotok-toggle-container">
										<input type="checkbox" name="delete_data_on_uninstall" id="delete_data_on_uninstall" value="1" <?php checked( $settings['delete_data_on_uninstall'] ?? '0', '1' ); ?> class="teknotok-toggle-input" />
										<span class="teknotok-toggle-track"></span>
										<span class="description"><?php esc_html_e( 'Delete translation cache tables, queue jobs, and settings when this plugin is uninstalled.', 'teknotok-ai-translator-pro' ); ?></span>
									</label>
								</td>
							</tr>
						</table>
					</details>

					<?php submit_button( __( 'Save Settings', 'teknotok-ai-translator-pro' ) ); ?>
				</form>
			</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-pro' ) ), 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();
	}
}
