<?php
/**
 * Admin settings class.
 *
 * @package Altify_AI
 */

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

/**
 * Settings and admin page rendering.
 */
class Altify_AI_Settings {
	/**
	 * Client instance.
	 *
	 * @var Altify_AI_Client
	 */
	private $client;

	/**
	 * Bulk instance.
	 *
	 * @var Altify_AI_Bulk
	 */
	private $bulk;

	/**
	 * Woo helper.
	 *
	 * @var Altify_AI_WooCommerce
	 */
	private $woocommerce;

	/**
	 * Logger.
	 *
	 * @var Altify_AI_Logger
	 */
	private $logger;

	/**
	 * Constructor.
	 *
	 * @param Altify_AI_Client      $client      Client.
	 * @param Altify_AI_Bulk        $bulk        Bulk processor.
	 * @param Altify_AI_WooCommerce $woocommerce Woo helper.
	 * @param Altify_AI_Logger      $logger      Logger.
	 */
	public function __construct($client, $bulk, $woocommerce, $logger) {
		$this->client      = $client;
		$this->bulk        = $bulk;
		$this->woocommerce = $woocommerce;
		$this->logger      = $logger;

		add_action('admin_menu', array($this, 'register_menu'));
		add_action('admin_init', array($this, 'register_settings'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
		add_action('wp_ajax_altify_ai_test_api', array($this, 'ajax_test_api'));
		add_action('wp_ajax_altify_ai_manage_logs', array($this, 'ajax_manage_logs'));
		add_action('wp_ajax_altify_ai_run_scan_now', array($this, 'ajax_run_scan_now'));
		add_action('wp_ajax_altify_ai_save_settings', array($this, 'ajax_save_settings'));
	}

	/**
	 * Register top-level admin menu and submenus.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_menu_page(
			__('Altify AI', 'altify-ai-auto-alt-text-generator'),
			__('Altify AI', 'altify-ai-auto-alt-text-generator'),
			'manage_options',
			'altify-ai-settings',
			array($this, 'render_page'),
			'dashicons-format-image',
			4.9
		);

		add_submenu_page(
			'altify-ai-settings',
			__('Settings', 'altify-ai-auto-alt-text-generator'),
			__('Settings', 'altify-ai-auto-alt-text-generator'),
			'manage_options',
			'altify-ai-settings',
			array($this, 'render_page')
		);

		add_submenu_page(
			'altify-ai-settings',
			__('Generate History', 'altify-ai-auto-alt-text-generator'),
			__('Generate History', 'altify-ai-auto-alt-text-generator'),
			'manage_options',
			'altify-ai-history',
			array($this, 'render_history_page')
		);
	}

	/**
	 * Register plugin settings.
	 *
	 * @return void
	 */
	public function register_settings() {
		register_setting('altify_ai_settings_group', 'altify_ai_settings', array($this, 'sanitize_settings'));
	}

	/**
	 * Sanitize settings payload.
	 *
	 * @param array $input Raw input.
	 *
	 * @return array
	 */
	public function sanitize_settings($input) {
		$defaults = altify_ai_get_default_settings();
		$current  = altify_ai_get_settings();
		$input    = is_array($input) ? $input : array();

		$output = $current;

		if (!empty($input['openai_api_key'])) {
			$output['openai_api_key'] = sanitize_text_field((string) $input['openai_api_key']);
		} elseif (!isset($current['openai_api_key'])) {
			$output['openai_api_key'] = '';
		}

		if (isset($input['model'])) {
			$model            = sanitize_text_field((string) $input['model']);
			$output['model']  = ('' !== $model) ? $model : $defaults['model'];
		}

		if (isset($input['temperature'])) {
			$temperature = (float) $input['temperature'];
			$temperature = max(0.0, min(2.0, $temperature));
			$output['temperature'] = $temperature;
		}

		if (isset($input['max_tokens'])) {
			$max_tokens            = absint($input['max_tokens']);
			$output['max_tokens']  = max(1, min(300, $max_tokens));
		}

		if (isset($input['alt_language'])) {
			$language = sanitize_key((string) $input['alt_language']);
			if ('english' === $language) {
				$language = 'en';
			} elseif ('nepali' === $language) {
				$language = 'ne';
			}
			$allowed_languages = array_keys(altify_ai_get_language_options());
			if (!in_array($language, $allowed_languages, true)) {
				$language = 'auto';
			}
			$output['alt_language'] = $language;
		}

		if (isset($input['alt_language_custom'])) {
			$custom_language = sanitize_text_field((string) $input['alt_language_custom']);
			$custom_language = preg_replace('/\s+/', ' ', (string) $custom_language);
			$custom_language = trim((string) $custom_language);
			$output['alt_language_custom'] = altify_ai_truncate_text((string) $custom_language, 60);
		}

		if (isset($input['max_alt_length'])) {
			$max_alt_length            = absint($input['max_alt_length']);
			$output['max_alt_length']  = max(30, min(300, $max_alt_length));
		}

		$checkbox_keys = array(
			'only_fill_empty_alt',
			'overwrite_existing_alt',
			'offline_mode',
			'use_vision_analysis',
			'enable_woo_support',
			'auto_generate_on_upload',
			'daily_scan_enabled',
		);

		foreach ($checkbox_keys as $checkbox_key) {
			if (array_key_exists($checkbox_key, $input)) {
				$output[$checkbox_key] = !empty($input[$checkbox_key]) ? 1 : 0;
			} elseif (isset($current[$checkbox_key])) {
				$output[$checkbox_key] = !empty($current[$checkbox_key]) ? 1 : 0;
			}
		}

		if (isset($input['upload_generation_mode'])) {
			$output['upload_generation_mode'] = altify_ai_normalize_generation_mode($input['upload_generation_mode'], 'offline_first');
		}

		if (isset($input['daily_scan_time'])) {
			$output['daily_scan_time'] = altify_ai_normalize_time_hhmm($input['daily_scan_time'], '02:00');
		}

		if (isset($input['daily_scan_scope'])) {
			$output['daily_scan_scope'] = altify_ai_normalize_scan_scope($input['daily_scan_scope']);
		}

		if (isset($input['daily_scan_max_images'])) {
			$max_images = absint($input['daily_scan_max_images']);
			$output['daily_scan_max_images'] = max(1, min(500, $max_images));
		}

		if (isset($input['daily_scan_mode'])) {
			$output['daily_scan_mode'] = altify_ai_normalize_generation_mode($input['daily_scan_mode'], 'offline_first');
		}

		if (isset($input['requests_per_minute'])) {
			$rpm            = absint($input['requests_per_minute']);
			$output['requests_per_minute'] = max(1, min(600, $rpm));
		}

		$output = wp_parse_args($output, $defaults);
		if (class_exists('Altify_AI_Plugin') && method_exists('Altify_AI_Plugin', 'reschedule_daily_scan')) {
			Altify_AI_Plugin::reschedule_daily_scan($output);
		}

		return $output;
	}

	/**
	 * Enqueue admin assets on plugin settings page.
	 *
	 * @param string $hook_suffix Admin hook.
	 *
	 * @return void
	 */
	public function enqueue_assets($hook_suffix) {
		$allowed_hooks = array(
			'toplevel_page_altify-ai-settings',
			'altify-ai_page_altify-ai-history',
		);
		if (!in_array($hook_suffix, $allowed_hooks, true)) {
			return;
		}

		wp_enqueue_style(
			'altify-ai-admin',
			ALTIFY_AI_PLUGIN_URL . 'assets/admin.css',
			array(),
			ALTIFY_AI_VERSION
		);

		wp_enqueue_script(
			'altify-ai-admin',
			ALTIFY_AI_PLUGIN_URL . 'assets/admin.js',
			array('jquery'),
			ALTIFY_AI_VERSION,
			true
		);

		wp_localize_script(
			'altify-ai-admin',
			'AltifyAIAdmin',
			array(
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce'   => wp_create_nonce('altify_ai_admin_nonce'),
				'initialLogs' => $this->logger->get_logs(Altify_AI_Logger::MAX_LOGS),
				'automationStatus' => $this->get_automation_status_payload(),
				'strings' => array(
					'processing'       => __('Processing...', 'altify-ai-auto-alt-text-generator'),
					'paused'           => __('Paused.', 'altify-ai-auto-alt-text-generator'),
					'resuming'         => __('Resuming...', 'altify-ai-auto-alt-text-generator'),
					'stopped'          => __('Stopped.', 'altify-ai-auto-alt-text-generator'),
					'completed'        => __('Completed.', 'altify-ai-auto-alt-text-generator'),
					'requestFailed'    => __('Request failed.', 'altify-ai-auto-alt-text-generator'),
					'testing'          => __('Testing API...', 'altify-ai-auto-alt-text-generator'),
					'startFirst'       => __('Click Start to begin.', 'altify-ai-auto-alt-text-generator'),
					'permissionDenied' => __('Permission or nonce check failed.', 'altify-ai-auto-alt-text-generator'),
					'presetApplied'    => __('Preset applied. Review and click Save Settings.', 'altify-ai-auto-alt-text-generator'),
					'qualityPresetWarning' => __('Quality preset applied. If your API key does not support this model, switch to gpt-4o-mini or use the Balanced preset.', 'altify-ai-auto-alt-text-generator'),
					'runStarted'       => __('Run started.', 'altify-ai-auto-alt-text-generator'),
					'runStopped'       => __('Run stopped.', 'altify-ai-auto-alt-text-generator'),
					'noRowsSelected'   => __('Select at least one history row.', 'altify-ai-auto-alt-text-generator'),
					'deletingHistory'  => __('Updating history...', 'altify-ai-auto-alt-text-generator'),
					'confirmClearHistory' => __('Clear all history rows?', 'altify-ai-auto-alt-text-generator'),
					'historyUpdated'   => __('History updated.', 'altify-ai-auto-alt-text-generator'),
					'noHistoryRows'    => __('No history found.', 'altify-ai-auto-alt-text-generator'),
					'selectHistoryRow' => __('Select history row', 'altify-ai-auto-alt-text-generator'),
					'runningScanNow'   => __('Running scan now...', 'altify-ai-auto-alt-text-generator'),
					'runScanNow'       => __('Run scan now', 'altify-ai-auto-alt-text-generator'),
					'runScanComplete'  => __('Scan completed.', 'altify-ai-auto-alt-text-generator'),
					'pauseDailyScan'   => __('Pause Daily Scan', 'altify-ai-auto-alt-text-generator'),
					'resumeDailyScan'  => __('Resume Daily Scan', 'altify-ai-auto-alt-text-generator'),
					'savingSettings'   => __('Saving settings...', 'altify-ai-auto-alt-text-generator'),
					'settingsSaved'    => __('Settings saved.', 'altify-ai-auto-alt-text-generator'),
					'settingsSaveFailed' => __('Unable to save settings right now.', 'altify-ai-auto-alt-text-generator'),
				),
			)
		);
	}

	/**
	 * Render settings page with tabs.
	 *
	 * @return void
	 */
	public function render_page() {
		if (!current_user_can('manage_options')) {
			return;
		}

		$tab = filter_input(INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$tab = is_string($tab) ? sanitize_key($tab) : 'settings';
		if (!in_array($tab, array('settings', 'automation', 'bulk', 'offline', 'woocommerce'), true)) {
			$tab = 'settings';
		}

		echo '<div class="wrap">';
		if ('settings' !== $tab) {
			echo '<h1>' . esc_html__('Altify AI – Auto ALT Text Generator', 'altify-ai-auto-alt-text-generator') . '</h1>';
		}

		if ('settings' !== $tab) {
			$this->render_tabs($tab);
		}

		switch ($tab) {
			case 'automation':
				$this->render_automation_tab();
				break;
			case 'bulk':
				$this->render_bulk_tab();
				break;
			case 'offline':
				$this->render_offline_tab();
				break;
			case 'woocommerce':
				$this->render_woocommerce_tab();
				break;
			case 'settings':
			default:
				$this->render_settings_tab();
				break;
		}

		echo '</div>';
	}

	/**
	 * Render dedicated generation history menu page.
	 *
	 * @return void
	 */
	public function render_history_page() {
		if (!current_user_can('manage_options')) {
			return;
		}
		?>
		<div class="wrap">
			<div class="altify-wrap" id="settings-form">
				<header class="header">
					<h1>
						<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
							<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
							<circle cx="8.5" cy="8.5" r="1.5"></circle>
							<polyline points="21 15 16 10 5 21"></polyline>
						</svg>
						<?php esc_html_e('Altify AI - Generate History', 'altify-ai-auto-alt-text-generator'); ?>
					</h1>
					<p class="subtitle"><?php esc_html_e('View and manage generated ALT history entries.', 'altify-ai-auto-alt-text-generator'); ?></p>
				</header>

				<div class="altify-card altify-mb-0">
					<div class="history-header">
						<div>
							<h2 class="history-title"><?php esc_html_e('Generation History', 'altify-ai-auto-alt-text-generator'); ?></h2>
							<p class="helper-text history-subtitle"><?php esc_html_e('A log of the images processed by upload automation, daily scan, and bulk runs.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</div>
						<div class="flex-row">
							<button type="button" class="button button-secondary" id="altify-history-log-delete-selected"><?php esc_html_e('Remove Selected', 'altify-ai-auto-alt-text-generator'); ?></button>
							<button type="button" class="button button-danger" id="altify-history-log-clear-all"><?php esc_html_e('Clear All', 'altify-ai-auto-alt-text-generator'); ?></button>
						</div>
					</div>

					<div class="table-responsive">
						<table class="wp-list-table altify-settings-table">
							<thead>
								<tr>
									<th class="check-col"><input type="checkbox" id="altify-history-log-select-all" /></th>
									<th><?php esc_html_e('Date/Time', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Mode', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Source', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Attachment', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('ALT Preview', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Status', 'altify-ai-auto-alt-text-generator'); ?></th>
								</tr>
							</thead>
							<tbody id="altify-history-logs"></tbody>
						</table>
					</div>
					<p class="helper-text altify-inline-status" id="altify-history-status" aria-live="polite"></p>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Handle Test API AJAX.
	 *
	 * @return void
	 */
	public function ajax_test_api() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('Insufficient permissions.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$nonce_ok = check_ajax_referer('altify_ai_admin_nonce', 'nonce', false);
		if (!$nonce_ok) {
			wp_send_json_error(array('message' => __('Invalid nonce.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$result = $this->client->test_api_connection();
		if (!empty($result['success'])) {
			wp_send_json_success(array('message' => $result['message']));
		}

		wp_send_json_error(
			array(
				'message' => !empty($result['message']) ? $result['message'] : __('API test failed.', 'altify-ai-auto-alt-text-generator'),
			)
		);
	}

	/**
	 * Handle history delete/clear AJAX.
	 *
	 * @return void
	 */
	public function ajax_manage_logs() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('Insufficient permissions.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$nonce_ok = check_ajax_referer('altify_ai_admin_nonce', 'nonce', false);
		if (!$nonce_ok) {
			wp_send_json_error(array('message' => __('Invalid nonce.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$operation = sanitize_key((string) $this->get_post_scalar('operation', ''));

		if ('clear_all' === $operation) {
			$this->logger->clear();
			wp_send_json_success(
				array(
					'message' => __('History cleared.', 'altify-ai-auto-alt-text-generator'),
					'removed' => 0,
					'logs'    => array(),
				)
			);
		}

		$log_ids = $this->get_post_array('log_ids');
		$removed = $this->logger->delete_logs_by_ids($log_ids);
		$message = sprintf(
			/* translators: %d: number of removed history rows */
			__('Removed %d history row(s).', 'altify-ai-auto-alt-text-generator'),
			$removed
		);

		wp_send_json_success(
			array(
				'message' => $message,
				'removed' => $removed,
				'logs'    => $this->logger->get_logs(Altify_AI_Logger::MAX_LOGS),
			)
		);
	}

	/**
	 * Handle AJAX settings save.
	 *
	 * @return void
	 */
	public function ajax_save_settings() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('Insufficient permissions.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$nonce_ok = check_ajax_referer('altify_ai_admin_nonce', 'nonce', false);
		if (!$nonce_ok) {
			wp_send_json_error(array('message' => __('Invalid nonce.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$form_data = $this->get_post_scalar('form_data', '');
		if (!is_string($form_data) || '' === $form_data) {
			wp_send_json_error(array('message' => __('Nothing to save.', 'altify-ai-auto-alt-text-generator')), 400);
		}

		$parsed = array();
		parse_str((string) wp_unslash($form_data), $parsed);
		$raw_settings = (isset($parsed['altify_ai_settings']) && is_array($parsed['altify_ai_settings'])) ? $parsed['altify_ai_settings'] : array();

		$sanitized = $this->sanitize_settings($raw_settings);
		update_option('altify_ai_settings', $sanitized, false);

		wp_send_json_success(
			array(
				'message' => __('Settings saved.', 'altify-ai-auto-alt-text-generator'),
				'status'  => $this->get_automation_status_payload(),
			)
		);
	}

	/**
	 * Handle Run Scan Now AJAX request.
	 *
	 * @return void
	 */
	public function ajax_run_scan_now() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('Insufficient permissions.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$nonce_ok = check_ajax_referer('altify_ai_admin_nonce', 'nonce', false);
		if (!$nonce_ok) {
			wp_send_json_error(array('message' => __('Invalid nonce.', 'altify-ai-auto-alt-text-generator')), 403);
		}

		$result = altify_ai()->run_daily_scan('manual');
		$status = $this->get_automation_status_payload();

		if (!empty($result['success'])) {
			wp_send_json_success(
				array(
					'message' => !empty($result['message']) ? sanitize_text_field((string) $result['message']) : __('Scan completed.', 'altify-ai-auto-alt-text-generator'),
					'status'  => $status,
				)
			);
		}

		wp_send_json_error(
			array(
				'message' => !empty($result['message']) ? sanitize_text_field((string) $result['message']) : __('Unable to run scan right now.', 'altify-ai-auto-alt-text-generator'),
				'status'  => $status,
			)
		);
	}

	/**
	 * Get automation status payload for UI.
	 *
	 * @return array
	 */
	private function get_automation_status_payload() {
		$status = altify_ai()->get_daily_scan_status();
		$status = is_array($status) ? $status : array();
		$processed = !empty($status['processed']) ? absint($status['processed']) : 0;
		$success   = !empty($status['success']) ? absint($status['success']) : 0;
		$skipped   = !empty($status['skipped']) ? absint($status['skipped']) : 0;
		$failed    = !empty($status['failed']) ? absint($status['failed']) : 0;
		$mode_label = !empty($status['last_mode_label']) ? sanitize_text_field((string) $status['last_mode_label']) : '';
		$scope_label = !empty($status['last_scope_label']) ? sanitize_text_field((string) $status['last_scope_label']) : '';

		return array(
			'last_run_display' => !empty($status['last_run_display']) ? sanitize_text_field((string) $status['last_run_display']) : __('Never', 'altify-ai-auto-alt-text-generator'),
			'next_run_display' => !empty($status['next_run_display']) ? sanitize_text_field((string) $status['next_run_display']) : __('Not scheduled', 'altify-ai-auto-alt-text-generator'),
			'processed'        => $processed,
			'success'          => $success,
			'skipped'          => $skipped,
			'failed'           => $failed,
			'last_mode_label'  => $mode_label,
			'last_scope_label' => $scope_label,
			'counters_display' => sprintf(
				/* translators: 1: processed count, 2: success count, 3: skipped count, 4: failed count */
				__('Processed %1$d, Success %2$d, Skipped %3$d, Failed %4$d', 'altify-ai-auto-alt-text-generator'),
				$processed,
				$success,
				$skipped,
				$failed
			),
			'mode_scope_display' => sprintf(
				/* translators: 1: mode label, 2: scope label */
				__('%1$s / %2$s', 'altify-ai-auto-alt-text-generator'),
				$mode_label,
				$scope_label
			),
		);
	}

	/**
	 * Render top tab navigation.
	 *
	 * @param string $active Active tab.
	 *
	 * @return void
	 */
	private function render_tabs($active) {
		$base = admin_url('admin.php?page=altify-ai-settings');

		$tabs = array(
			'settings'    => __('Settings', 'altify-ai-auto-alt-text-generator'),
			'automation'  => __('Automation', 'altify-ai-auto-alt-text-generator'),
			'bulk'        => __('Bulk Generator', 'altify-ai-auto-alt-text-generator'),
			'offline'     => __('Offline Mode', 'altify-ai-auto-alt-text-generator'),
			'woocommerce' => __('WooCommerce', 'altify-ai-auto-alt-text-generator'),
		);

		echo '<div class="altify-ai-tabs" role="tablist" aria-label="' . esc_attr__('Altify settings tabs', 'altify-ai-auto-alt-text-generator') . '">';
		foreach ($tabs as $key => $label) {
			$class = ('altify-ai-tab' . (($active === $key) ? ' is-active' : ''));
			$url   = add_query_arg('tab', $key, $base);
			echo '<a class="' . esc_attr($class) . '" href="' . esc_url($url) . '">' . esc_html($label) . '</a>';
		}
		echo '</div>';
	}

	/**
	 * Render automation tab.
	 *
	 * @return void
	 */
	private function render_automation_tab() {
		$settings = altify_ai_get_settings();
		$status   = $this->get_automation_status_payload();
		$mode_options = altify_ai_get_generation_mode_options();
		$scope_options = altify_ai_get_scan_scope_options();
		$timezone = wp_timezone_string();
		if ('' === $timezone) {
			$timezone = 'UTC';
		}

		$upload_mode = altify_ai_normalize_generation_mode(
			isset($settings['upload_generation_mode']) ? $settings['upload_generation_mode'] : 'offline_first',
			'offline_first'
		);
		$daily_mode = altify_ai_normalize_generation_mode(
			isset($settings['daily_scan_mode']) ? $settings['daily_scan_mode'] : 'offline_first',
			'offline_first'
		);
		$daily_scope = altify_ai_normalize_scan_scope(isset($settings['daily_scan_scope']) ? $settings['daily_scan_scope'] : 'missing');
		$daily_time  = altify_ai_normalize_time_hhmm(isset($settings['daily_scan_time']) ? $settings['daily_scan_time'] : '02:00', '02:00');
		$daily_max   = isset($settings['daily_scan_max_images']) ? absint($settings['daily_scan_max_images']) : 50;
		$daily_max   = max(1, min(500, $daily_max));
		?>
		<form method="post" action="options.php" class="altify-ai-settings-form altify-ai-automation-form">
			<?php settings_fields('altify_ai_settings_group'); ?>

			<div class="altify-ai-panel altify-ai-automation-panel">
				<div class="altify-ai-automation-header">
					<h2><?php esc_html_e('Automation Rules', 'altify-ai-auto-alt-text-generator'); ?></h2>
					<p><?php esc_html_e('Set once, then let Altify keep image ALT text up to date for you.', 'altify-ai-auto-alt-text-generator'); ?></p>
				</div>

				<div class="altify-ai-automation-grid">
					<div class="altify-ai-automation-card">
						<label class="altify-ai-toggle-wrapper">
							<span class="altify-ai-switch">
								<input type="hidden" name="altify_ai_settings[auto_generate_on_upload]" value="0" />
								<input type="checkbox" name="altify_ai_settings[auto_generate_on_upload]" value="1" <?php checked(!empty($settings['auto_generate_on_upload'])); ?> />
								<span class="altify-ai-slider"></span>
							</span>
							<span class="altify-ai-toggle-text">
								<span class="altify-ai-main-label"><?php esc_html_e('Auto-generate ALT on media upload', 'altify-ai-auto-alt-text-generator'); ?></span>
								<span class="description"><?php esc_html_e('What this does: generates ALT text automatically each time you upload a new image.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</span>
						</label>

						<div class="altify-ai-field altify-ai-indent">
							<label for="altify-upload-generation-mode"><?php esc_html_e('Upload generation mode', 'altify-ai-auto-alt-text-generator'); ?></label>
							<select id="altify-upload-generation-mode" name="altify_ai_settings[upload_generation_mode]">
								<?php foreach ($mode_options as $mode_key => $mode_label) : ?>
									<option value="<?php echo esc_attr($mode_key); ?>" <?php selected($upload_mode, $mode_key); ?>><?php echo esc_html($mode_label); ?></option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e('What this does: chooses whether Offline or AI runs first for each new upload.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</div>
					</div>

					<div class="altify-ai-automation-card">
						<label class="altify-ai-toggle-wrapper">
							<span class="altify-ai-switch">
								<input type="hidden" name="altify_ai_settings[daily_scan_enabled]" value="0" />
								<input type="checkbox" name="altify_ai_settings[daily_scan_enabled]" value="1" <?php checked(!empty($settings['daily_scan_enabled'])); ?> />
								<span class="altify-ai-slider"></span>
							</span>
							<span class="altify-ai-toggle-text">
								<span class="altify-ai-main-label"><?php esc_html_e('Daily scan for missing ALT', 'altify-ai-auto-alt-text-generator'); ?></span>
								<span class="description"><?php esc_html_e('What this does: runs a background scan every day and fills ALT text automatically.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</span>
						</label>

						<div class="altify-ai-automation-inline-grid altify-ai-indent">
							<div class="altify-ai-field">
								<label for="altify-daily-scan-time"><?php esc_html_e('Daily scan time', 'altify-ai-auto-alt-text-generator'); ?></label>
								<input id="altify-daily-scan-time" name="altify_ai_settings[daily_scan_time]" type="time" value="<?php echo esc_attr($daily_time); ?>" />
								<p class="description">
									<?php
									printf(
										/* translators: %s: site timezone */
										esc_html__('What this does: sets the daily run time using your site timezone (%s).', 'altify-ai-auto-alt-text-generator'),
										esc_html($timezone)
									);
									?>
								</p>
							</div>
							<div class="altify-ai-field">
								<label for="altify-daily-scan-max-images"><?php esc_html_e('Max images per daily run', 'altify-ai-auto-alt-text-generator'); ?></label>
								<input id="altify-daily-scan-max-images" name="altify_ai_settings[daily_scan_max_images]" type="number" min="1" max="500" value="<?php echo esc_attr((string) $daily_max); ?>" />
								<p class="description"><?php esc_html_e('What this does: limits each run to protect server performance on large libraries.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</div>
						</div>

						<div class="altify-ai-field altify-ai-indent">
							<label for="altify-daily-scan-scope"><?php esc_html_e('Daily scan scope', 'altify-ai-auto-alt-text-generator'); ?></label>
							<select id="altify-daily-scan-scope" name="altify_ai_settings[daily_scan_scope]">
								<?php foreach ($scope_options as $scope_key => $scope_label) : ?>
									<option value="<?php echo esc_attr($scope_key); ?>" <?php selected($daily_scope, $scope_key); ?>><?php echo esc_html($scope_label); ?></option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e('What this does: choose whether to process only missing ALT text or all images.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</div>

						<div class="altify-ai-field altify-ai-indent">
							<label for="altify-daily-scan-mode"><?php esc_html_e('Daily scan mode', 'altify-ai-auto-alt-text-generator'); ?></label>
							<select id="altify-daily-scan-mode" name="altify_ai_settings[daily_scan_mode]">
								<?php foreach ($mode_options as $mode_key => $mode_label) : ?>
									<option value="<?php echo esc_attr($mode_key); ?>" <?php selected($daily_mode, $mode_key); ?>><?php echo esc_html($mode_label); ?></option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e('What this does: chooses whether Offline or AI runs first during the daily scan.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</div>
					</div>
				</div>

				<div class="altify-ai-automation-status-wrap">
					<h3><?php esc_html_e('Daily Scan Status', 'altify-ai-auto-alt-text-generator'); ?></h3>
					<div class="altify-ai-automation-status-grid">
						<div class="altify-ai-status-item">
							<span class="altify-ai-status-label"><?php esc_html_e('Last run time', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span id="altify-ai-auto-last-run"><?php echo esc_html($status['last_run_display']); ?></span>
						</div>
						<div class="altify-ai-status-item">
							<span class="altify-ai-status-label"><?php esc_html_e('Next scheduled run', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span id="altify-ai-auto-next-run"><?php echo esc_html($status['next_run_display']); ?></span>
						</div>
						<div class="altify-ai-status-item">
							<span class="altify-ai-status-label"><?php esc_html_e('Last run counters', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span id="altify-ai-auto-counters">
								<?php echo esc_html($status['counters_display']); ?>
							</span>
						</div>
						<div class="altify-ai-status-item">
							<span class="altify-ai-status-label"><?php esc_html_e('Last run mode and scope', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span id="altify-ai-auto-mode-scope">
								<?php echo esc_html($status['mode_scope_display']); ?>
							</span>
						</div>
					</div>
					<p class="altify-ai-inline-message" id="altify-ai-automation-result" aria-live="polite"></p>
					<p>
						<button type="button" class="button button-secondary" id="altify-ai-run-scan-now"><?php esc_html_e('Run scan now', 'altify-ai-auto-alt-text-generator'); ?></button>
					</p>
				</div>
			</div>

			<?php submit_button(__('Save Automation Settings', 'altify-ai-auto-alt-text-generator')); ?>
		</form>
		<?php
	}

	/**
	 * Render settings tab.
	 *
	 * @return void
	 */
	private function render_settings_tab() {
		$settings          = altify_ai_get_settings();
		$status            = $this->get_automation_status_payload();
		$language_options  = altify_ai_get_language_options();
		$mode_options      = altify_ai_get_generation_mode_options();
		$scope_options     = altify_ai_get_scan_scope_options();
		$selected_language = isset($settings['alt_language']) ? sanitize_key((string) $settings['alt_language']) : 'auto';
		$is_offline_mode   = !empty($settings['offline_mode']);
		$is_ai_mode        = !$is_offline_mode;
		$upload_mode       = altify_ai_normalize_generation_mode(isset($settings['upload_generation_mode']) ? $settings['upload_generation_mode'] : 'offline_first', 'offline_first');
		$daily_mode        = altify_ai_normalize_generation_mode(isset($settings['daily_scan_mode']) ? $settings['daily_scan_mode'] : 'offline_first', 'offline_first');
		$daily_scope       = altify_ai_normalize_scan_scope(isset($settings['daily_scan_scope']) ? $settings['daily_scan_scope'] : 'missing');
		$daily_time        = altify_ai_normalize_time_hhmm(isset($settings['daily_scan_time']) ? $settings['daily_scan_time'] : '02:00', '02:00');
		$daily_max         = isset($settings['daily_scan_max_images']) ? absint($settings['daily_scan_max_images']) : 50;
		$daily_max         = max(1, min(500, $daily_max));
		$timezone          = wp_timezone_string();

		if ('' === $timezone) {
			$timezone = 'UTC';
		}

		if ('english' === $selected_language) {
			$selected_language = 'en';
		} elseif ('nepali' === $selected_language) {
			$selected_language = 'ne';
		}

		if (!isset($language_options[$selected_language])) {
			$selected_language = 'auto';
		}
		?>
		<form method="post" action="options.php" class="altify-ai-settings-form" id="altify-ai-settings-form">
			<?php settings_fields('altify_ai_settings_group'); ?>

			<div class="altify-wrap" id="settings-form">
				<header class="header">
					<h1>
						<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
							<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
							<circle cx="8.5" cy="8.5" r="1.5"></circle>
							<polyline points="21 15 16 10 5 21"></polyline>
						</svg>
						<?php esc_html_e('Altify AI Settings', 'altify-ai-auto-alt-text-generator'); ?>
					</h1>
					<p class="subtitle"><?php esc_html_e('Set up your automated image descriptions. We recommend starting simple.', 'altify-ai-auto-alt-text-generator'); ?></p>
				</header>

				<div class="altify-card altify-card-hero">
					<h2><?php esc_html_e('1. Quick Start', 'altify-ai-auto-alt-text-generator'); ?></h2>
					<p class="mb-2">
						<?php esc_html_e('How do you want to generate your ALT text?', 'altify-ai-auto-alt-text-generator'); ?>
						<span class="subtle-text"><?php esc_html_e('You can start with Offline and enable AI later.', 'altify-ai-auto-alt-text-generator'); ?></span>
					</p>

					<div class="mode-card-container">
						<label class="mode-card <?php echo $is_offline_mode ? 'active' : ''; ?>" id="card-offline" data-mode="offline">
							<input type="radio" name="altify_ai_primary_mode" value="offline" <?php checked($is_offline_mode); ?> />
							<h3><?php esc_html_e('Offline Mode (Recommended)', 'altify-ai-auto-alt-text-generator'); ?></h3>
							<p class="helper-text"><?php esc_html_e('100% free and instant. Creates ALT text by cleaning up image filenames.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</label>

						<label class="mode-card <?php echo $is_ai_mode ? 'active' : ''; ?>" id="card-ai" data-mode="ai">
							<input type="radio" name="altify_ai_primary_mode" value="ai" <?php checked($is_ai_mode); ?> />
							<h3><?php esc_html_e('AI Mode (Advanced)', 'altify-ai-auto-alt-text-generator'); ?></h3>
							<p class="helper-text"><?php esc_html_e('Uses OpenAI to write accurate, human-like descriptions. Requires an API key.', 'altify-ai-auto-alt-text-generator'); ?></p>
						</label>
					</div>

					<button type="button" class="button button-primary mt-4 altify-ai-save-start" id="altify-save-start"><?php esc_html_e('Save & Start', 'altify-ai-auto-alt-text-generator'); ?></button>
				</div>

				<div class="altify-card">
					<h2><?php esc_html_e('2. Automation rules', 'altify-ai-auto-alt-text-generator'); ?></h2>
					<p class="helper-text mb-2"><?php esc_html_e('Tell the plugin when it should do the work for you.', 'altify-ai-auto-alt-text-generator'); ?></p>

					<div class="grid-2 mt-4">
						<div>
							<label class="toggle-wrapper form-row">
								<span class="switch">
									<input type="hidden" name="altify_ai_settings[auto_generate_on_upload]" value="0" />
									<input type="checkbox" id="auto_upload" class="track-change" name="altify_ai_settings[auto_generate_on_upload]" value="1" <?php checked(!empty($settings['auto_generate_on_upload'])); ?> />
									<span class="slider"></span>
								</span>
								<span class="toggle-text">
									<span class="main-label"><?php esc_html_e('Auto-generate ALT when media is uploaded', 'altify-ai-auto-alt-text-generator'); ?></span>
									<span class="helper-text"><?php esc_html_e('What this does: automatically writes ALT text for new images as soon as they are uploaded.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</span>
							</label>

							<div class="form-row indent">
								<label class="main-label" for="upload_mode"><?php esc_html_e('Upload generation mode', 'altify-ai-auto-alt-text-generator'); ?></label>
								<select id="upload_mode" class="track-change" name="altify_ai_settings[upload_generation_mode]">
									<option value="offline_first" <?php selected($upload_mode, 'offline_first'); ?>><?php esc_html_e('Try Offline first, fallback to AI', 'altify-ai-auto-alt-text-generator'); ?></option>
									<option value="ai_first" <?php selected($upload_mode, 'ai_first'); ?>><?php esc_html_e('Try AI first, fallback to Offline', 'altify-ai-auto-alt-text-generator'); ?></option>
									<option value="offline_only" <?php selected($upload_mode, 'offline_only'); ?>><?php esc_html_e('Offline only', 'altify-ai-auto-alt-text-generator'); ?></option>
									<option value="ai_only" <?php selected($upload_mode, 'ai_only'); ?>><?php esc_html_e('AI only', 'altify-ai-auto-alt-text-generator'); ?></option>
								</select>
								<span class="helper-text"><?php esc_html_e('What this does: chooses which method is attempted first on upload.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</div>
						</div>

						<div>
							<label class="toggle-wrapper form-row">
								<span class="switch">
									<input type="hidden" name="altify_ai_settings[daily_scan_enabled]" value="0" />
									<input type="checkbox" id="daily_scan" class="track-change" name="altify_ai_settings[daily_scan_enabled]" value="1" <?php checked(!empty($settings['daily_scan_enabled'])); ?> />
									<span class="slider"></span>
								</span>
								<span class="toggle-text">
									<span class="main-label"><?php esc_html_e('Daily scan for missing ALT', 'altify-ai-auto-alt-text-generator'); ?></span>
									<span class="helper-text"><?php esc_html_e('What this does: runs a background task daily to fill ALT text for older images.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</span>
							</label>

							<div class="form-row indent split-grid">
								<div>
									<label class="main-label" for="scan_time"><?php esc_html_e('Daily scan time', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="time" id="scan_time" class="track-change" name="altify_ai_settings[daily_scan_time]" value="<?php echo esc_attr($daily_time); ?>" />
									<span class="helper-text">
										<?php
										printf(
											/* translators: %s: site timezone */
											esc_html__('Uses your site timezone (%s).', 'altify-ai-auto-alt-text-generator'),
											esc_html($timezone)
										);
										?>
									</span>
								</div>
								<div>
									<label class="main-label" for="scan_max"><?php esc_html_e('Max images per daily run', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="number" id="scan_max" class="track-change" name="altify_ai_settings[daily_scan_max_images]" min="1" max="500" value="<?php echo esc_attr((string) $daily_max); ?>" />
									<span class="helper-text"><?php esc_html_e('What this does: limits work per run to avoid server overload.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</div>
							</div>

							<div class="form-row indent">
								<label class="main-label" for="scan_scope"><?php esc_html_e('Daily scan scope', 'altify-ai-auto-alt-text-generator'); ?></label>
								<select id="scan_scope" class="track-change" name="altify_ai_settings[daily_scan_scope]">
									<?php foreach ($scope_options as $scope_key => $scope_label) : ?>
										<option value="<?php echo esc_attr($scope_key); ?>" <?php selected($daily_scope, $scope_key); ?>><?php echo esc_html($scope_label); ?></option>
									<?php endforeach; ?>
								</select>
								<span class="helper-text"><?php esc_html_e('What this does: choose whether daily scan touches only missing ALT text or all images.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</div>

							<div class="form-row indent">
								<label class="main-label" for="scan_mode"><?php esc_html_e('Daily scan mode', 'altify-ai-auto-alt-text-generator'); ?></label>
								<select id="scan_mode" class="track-change" name="altify_ai_settings[daily_scan_mode]">
									<?php foreach ($mode_options as $mode_key => $mode_label) : ?>
										<option value="<?php echo esc_attr($mode_key); ?>" <?php selected($daily_mode, $mode_key); ?>><?php echo esc_html($mode_label); ?></option>
									<?php endforeach; ?>
								</select>
								<span class="helper-text"><?php esc_html_e('What this does: chooses whether Offline or AI runs first during daily scans.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</div>
						</div>
					</div>

					<hr />

					<h3><?php esc_html_e('Daily Scan Status', 'altify-ai-auto-alt-text-generator'); ?></h3>
					<div class="status-row">
						<div class="status-item">
							<strong><?php esc_html_e('Last run', 'altify-ai-auto-alt-text-generator'); ?></strong>
							<span id="altify-ai-auto-last-run"><?php echo esc_html($status['last_run_display']); ?></span>
						</div>
						<div class="status-item">
							<strong><?php esc_html_e('Next run', 'altify-ai-auto-alt-text-generator'); ?></strong>
							<span id="altify-ai-auto-next-run"><?php echo esc_html($status['next_run_display']); ?></span>
						</div>
						<div class="status-item">
							<strong><?php esc_html_e('Last result', 'altify-ai-auto-alt-text-generator'); ?></strong>
							<span id="altify-ai-auto-counters"><?php echo esc_html($status['counters_display']); ?></span>
						</div>
						<div class="status-item">
							<strong><?php esc_html_e('Mode & scope', 'altify-ai-auto-alt-text-generator'); ?></strong>
							<span id="altify-ai-auto-mode-scope"><?php echo esc_html($status['mode_scope_display']); ?></span>
						</div>
					</div>

					<p class="helper-text altify-inline-status" id="altify-ai-automation-result" aria-live="polite"></p>
					<div class="flex-row">
						<button type="button" class="button button-secondary" id="altify-ai-run-scan-now"><?php esc_html_e('Run Scan Now', 'altify-ai-auto-alt-text-generator'); ?></button>
						<button type="button" class="button button-danger" id="altify-ai-toggle-daily-scan"><?php echo !empty($settings['daily_scan_enabled']) ? esc_html__('Pause Daily Scan', 'altify-ai-auto-alt-text-generator') : esc_html__('Resume Daily Scan', 'altify-ai-auto-alt-text-generator'); ?></button>
					</div>
				</div>

				<div class="altify-card">
					<div class="altify-card-header-row">
						<h2><?php esc_html_e('3. Offline Mode Settings', 'altify-ai-auto-alt-text-generator'); ?></h2>
						<label class="toggle-wrapper toggle-inline">
							<span class="main-label"><?php esc_html_e('Enable Offline Mode', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span class="switch">
								<input type="hidden" name="altify_ai_settings[offline_mode]" value="0" />
								<input type="checkbox" id="enable_offline" class="track-change" name="altify_ai_settings[offline_mode]" value="1" <?php checked($is_offline_mode); ?> />
								<span class="slider"></span>
							</span>
						</label>
					</div>

					<div class="grid-2">
						<div class="form-row">
							<label class="main-label" for="offline_lang"><?php esc_html_e('ALT Language', 'altify-ai-auto-alt-text-generator'); ?></label>
							<select id="offline_lang" class="track-change" name="altify_ai_settings[alt_language]">
								<?php foreach ($language_options as $language_code => $language_label) : ?>
									<option value="<?php echo esc_attr($language_code); ?>" <?php selected($selected_language, $language_code); ?>><?php echo esc_html($language_label); ?></option>
								<?php endforeach; ?>
							</select>
							<input type="text" id="offline_lang_custom" class="track-change altify-inline-custom-language" name="altify_ai_settings[alt_language_custom]" value="<?php echo esc_attr(isset($settings['alt_language_custom']) ? (string) $settings['alt_language_custom'] : ''); ?>" placeholder="<?php esc_attr_e('Enter custom language name', 'altify-ai-auto-alt-text-generator'); ?>" />
							<span class="helper-text"><?php esc_html_e('What this does: sets the language used when cleaning up filenames.', 'altify-ai-auto-alt-text-generator'); ?></span>
						</div>

						<div class="form-row">
							<label class="main-label" for="offline_max_len"><?php esc_html_e('Max ALT Length', 'altify-ai-auto-alt-text-generator'); ?></label>
							<input type="number" id="offline_max_len" class="track-change" name="altify_ai_settings[max_alt_length]" min="30" max="300" value="<?php echo esc_attr((string) $settings['max_alt_length']); ?>" />
							<span class="helper-text"><?php esc_html_e('What this does: cuts ALT text if it is longer than your target limit.', 'altify-ai-auto-alt-text-generator'); ?></span>
						</div>

						<label class="toggle-wrapper form-row">
							<span class="switch">
								<input type="hidden" name="altify_ai_settings[only_fill_empty_alt]" value="0" />
								<input type="checkbox" id="off_only_empty" class="track-change" name="altify_ai_settings[only_fill_empty_alt]" value="1" <?php checked(!empty($settings['only_fill_empty_alt'])); ?> />
								<span class="slider"></span>
							</span>
							<span class="toggle-text">
								<span class="main-label"><?php esc_html_e('Only fill empty ALT tags', 'altify-ai-auto-alt-text-generator'); ?></span>
								<span class="helper-text"><?php esc_html_e('What this does: keeps images with existing ALT text unchanged.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</span>
						</label>

						<label class="toggle-wrapper form-row">
							<span class="switch">
								<input type="hidden" name="altify_ai_settings[overwrite_existing_alt]" value="0" />
								<input type="checkbox" id="off_overwrite" class="track-change" name="altify_ai_settings[overwrite_existing_alt]" value="1" <?php checked(!empty($settings['overwrite_existing_alt'])); ?> />
								<span class="slider"></span>
							</span>
							<span class="toggle-text">
								<span class="main-label"><?php esc_html_e('Overwrite existing ALT text', 'altify-ai-auto-alt-text-generator'); ?></span>
								<span class="helper-text"><?php esc_html_e('What this does: rewrites ALT text for all images, even if ALT already exists.', 'altify-ai-auto-alt-text-generator'); ?></span>
							</span>
						</label>
					</div>
				</div>

				<div class="altify-card">
					<div class="altify-card-header-row">
						<h2><?php esc_html_e('4. AI Mode Settings', 'altify-ai-auto-alt-text-generator'); ?></h2>
						<label class="toggle-wrapper toggle-inline">
							<span class="main-label"><?php esc_html_e('Enable AI Mode', 'altify-ai-auto-alt-text-generator'); ?></span>
							<span class="switch">
								<input type="checkbox" id="enable_ai" class="track-change" value="1" <?php checked($is_ai_mode); ?> />
								<span class="slider"></span>
							</span>
						</label>
					</div>

					<div class="form-row">
						<label class="main-label"><?php esc_html_e('Quality Presets', 'altify-ai-auto-alt-text-generator'); ?></label>
						<span class="helper-text mb-2"><?php esc_html_e('Click a preset to automatically configure the AI settings.', 'altify-ai-auto-alt-text-generator'); ?></span>
						<div class="grid-3">
							<button type="button" class="preset-card altify-ai-preset-button" data-preset="budget">
								<h4><?php esc_html_e('Budget', 'altify-ai-auto-alt-text-generator'); ?></h4>
								<p><?php esc_html_e('Fast and low-cost for large media libraries.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</button>
							<button type="button" class="preset-card altify-ai-preset-button is-active" data-preset="balanced">
								<h4><?php esc_html_e('Balanced (Recommended)', 'altify-ai-auto-alt-text-generator'); ?></h4>
								<p><?php esc_html_e('Best mix of quality and cost.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</button>
							<button type="button" class="preset-card altify-ai-preset-button" data-preset="quality">
								<h4><?php esc_html_e('Quality', 'altify-ai-auto-alt-text-generator'); ?></h4>
								<p><?php esc_html_e('Higher-quality output with image analysis.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</button>
						</div>
						<p class="helper-text altify-inline-status" id="altify-ai-preset-result" aria-live="polite"></p>
					</div>

					<div class="form-row mt-4">
						<label class="main-label" for="api_key"><?php esc_html_e('OpenAI API Key', 'altify-ai-auto-alt-text-generator'); ?></label>
						<div class="flex-row">
							<input type="password" id="api_key" class="track-change" name="altify_ai_settings[openai_api_key]" value="" placeholder="sk-..." autocomplete="off" />
							<button type="button" class="button button-secondary" id="altify-ai-test-api"><?php esc_html_e('Test Connection', 'altify-ai-auto-alt-text-generator'); ?></button>
						</div>
						<span class="helper-text"><?php esc_html_e('What this does: connects your site to OpenAI for AI-generated ALT text.', 'altify-ai-auto-alt-text-generator'); ?></span>
						<p class="helper-text">
							<?php
							printf(
								wp_kses(
									/* translators: 1: OpenAI API keys URL, 2: OpenAI quickstart URL. */
									__('Need an API key? Create one here: <a href="%1$s" target="_blank" rel="noopener noreferrer">OpenAI API keys</a>. Setup help: <a href="%2$s" target="_blank" rel="noopener noreferrer">OpenAI Quickstart</a>.', 'altify-ai-auto-alt-text-generator'),
									array(
										'a' => array(
											'href'   => array(),
											'target' => array(),
											'rel'    => array(),
										),
									)
								),
								esc_url('https://platform.openai.com/api-keys'),
								esc_url('https://platform.openai.com/docs/quickstart')
							);
							?>
						</p>
						<div id="altify-ai-test-api-result" class="altify-ai-test-api-result" aria-live="polite"></div>
					</div>

					<div class="accordion altify-ai-accordion" id="altify-ai-advanced-accordion">
						<button type="button" class="accordion-header altify-ai-accordion-header" id="altify-ai-advanced-toggle" aria-expanded="false" aria-controls="altify-ai-advanced-content">
							<span><?php esc_html_e('Advanced AI Settings (For technical users)', 'altify-ai-auto-alt-text-generator'); ?></span>
							<svg class="accordion-icon altify-ai-accordion-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
								<polyline points="6 9 12 15 18 9"></polyline>
							</svg>
						</button>
						<div class="accordion-content altify-ai-accordion-content" id="altify-ai-advanced-content" hidden>
							<div class="altify-notice altify-notice-warning">
								<p><strong><?php esc_html_e('Note:', 'altify-ai-auto-alt-text-generator'); ?></strong> <?php esc_html_e('Changing these settings may affect OpenAI billing costs or rate-limit behavior.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</div>

							<div class="grid-2">
								<div class="form-row">
									<label class="main-label" for="ai_model"><?php esc_html_e('Model', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="text" id="ai_model" class="track-change" name="altify_ai_settings[model]" value="<?php echo esc_attr((string) $settings['model']); ?>" />
									<span class="helper-text"><?php esc_html_e('What this does: selects the OpenAI model used for ALT generation.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</div>
								<div class="form-row">
									<label class="main-label" for="ai_temp"><?php esc_html_e('Creativity level (Temperature)', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="number" id="ai_temp" class="track-change" name="altify_ai_settings[temperature]" min="0" max="2" step="0.1" value="<?php echo esc_attr((string) $settings['temperature']); ?>" />
									<span class="helper-text"><?php esc_html_e('What this does: lower values are stricter; higher values are more varied.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</div>
								<div class="form-row">
									<label class="main-label" for="ai_tokens"><?php esc_html_e('Max response size (Tokens)', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="number" id="ai_tokens" class="track-change" name="altify_ai_settings[max_tokens]" min="1" max="300" value="<?php echo esc_attr((string) $settings['max_tokens']); ?>" />
									<span class="helper-text"><?php esc_html_e('What this does: limits response size to help control cost and output length.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</div>
								<div class="form-row">
									<label class="main-label" for="ai_rpm"><?php esc_html_e('Requests per minute', 'altify-ai-auto-alt-text-generator'); ?></label>
									<input type="number" id="ai_rpm" class="track-change" name="altify_ai_settings[requests_per_minute]" min="1" max="600" value="<?php echo esc_attr((string) $settings['requests_per_minute']); ?>" />
									<span class="helper-text"><?php esc_html_e('What this does: throttles API calls to reduce rate-limit issues.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</div>
							</div>

							<label class="toggle-wrapper form-row mt-4">
								<span class="switch">
									<input type="hidden" name="altify_ai_settings[use_vision_analysis]" value="0" />
									<input type="checkbox" id="ai_vision" class="track-change" name="altify_ai_settings[use_vision_analysis]" value="1" <?php checked(!empty($settings['use_vision_analysis'])); ?> />
									<span class="slider"></span>
								</span>
								<span class="toggle-text">
									<span class="main-label"><?php esc_html_e('Enable Vision (Image analysis)', 'altify-ai-auto-alt-text-generator'); ?></span>
									<span class="helper-text"><?php esc_html_e('What this does: allows AI to inspect image content, not only filename and metadata.', 'altify-ai-auto-alt-text-generator'); ?></span>
								</span>
							</label>
						</div>
					</div>

					<hr />
				</div>

				<div class="altify-card altify-mb-0">
						<div class="history-header">
							<div>
								<h2 class="history-title"><?php esc_html_e('6. Generation History', 'altify-ai-auto-alt-text-generator'); ?></h2>
								<p class="helper-text history-subtitle"><?php esc_html_e('A log of the images we have processed for you.', 'altify-ai-auto-alt-text-generator'); ?></p>
							</div>
							<div class="flex-row">
								<button type="button" class="button button-success" id="altify-open-bulk-tab-history"><?php esc_html_e('Run AI Bulk Generator Now', 'altify-ai-auto-alt-text-generator'); ?></button>
								<button type="button" class="button button-secondary" id="altify-settings-log-delete-selected"><?php esc_html_e('Remove Selected', 'altify-ai-auto-alt-text-generator'); ?></button>
								<button type="button" class="button button-danger" id="altify-settings-log-clear-all"><?php esc_html_e('Clear All', 'altify-ai-auto-alt-text-generator'); ?></button>
							</div>
						</div>

					<div class="table-responsive">
						<table class="wp-list-table altify-settings-table">
							<thead>
								<tr>
									<th class="check-col"><input type="checkbox" id="altify-settings-log-select-all" /></th>
									<th><?php esc_html_e('Date/Time', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Mode', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Source', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Attachment', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('ALT Preview', 'altify-ai-auto-alt-text-generator'); ?></th>
									<th><?php esc_html_e('Status', 'altify-ai-auto-alt-text-generator'); ?></th>
								</tr>
							</thead>
							<tbody id="altify-settings-logs"></tbody>
						</table>
					</div>
					<p class="helper-text altify-inline-status" id="altify-settings-history-status" aria-live="polite"></p>
				</div>
			</div>

			<div class="sticky-footer">
					<div class="footer-inner">
						<div class="unsaved-hint" id="unsaved-hint">
							<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
								<circle cx="12" cy="12" r="10"></circle>
								<line x1="12" y1="8" x2="12" y2="12"></line>
								<line x1="12" y1="16" x2="12.01" y2="16"></line>
							</svg>
							<?php esc_html_e('You have unsaved changes', 'altify-ai-auto-alt-text-generator'); ?>
						</div>
						<div class="altify-save-message" id="altify-settings-save-message" aria-live="polite"></div>
						<div class="flex-row">
							<button type="button" class="button button-secondary" id="altify-reset-recommended"><?php esc_html_e('Reset to Recommended', 'altify-ai-auto-alt-text-generator'); ?></button>
							<button type="button" class="button button-primary altify-save-button" id="altify-save-settings"><?php esc_html_e('Save Settings', 'altify-ai-auto-alt-text-generator'); ?></button>
						</div>
					</div>
				</div>
		</form>
		<?php
	}

	/**
	 * Render bulk media tab.
	 *
	 * @return void
	 */
	private function render_bulk_tab() {
		$settings     = altify_ai_get_settings();
		$default_mode = !empty($settings['only_fill_empty_alt']) ? 'missing' : 'all';
		?>
		<div class="altify-ai-panel">
			<h2><?php esc_html_e('Bulk ALT Generator (Media Library)', 'altify-ai-auto-alt-text-generator'); ?></h2>
			<div class="altify-ai-filters">
				<div class="altify-ai-field">
					<label for="altify-media-mode"><?php esc_html_e('Process', 'altify-ai-auto-alt-text-generator'); ?></label>
					<select id="altify-media-mode">
						<option value="missing" <?php selected($default_mode, 'missing'); ?>><?php esc_html_e('Only missing ALT', 'altify-ai-auto-alt-text-generator'); ?></option>
						<option value="all" <?php selected($default_mode, 'all'); ?>><?php esc_html_e('All images', 'altify-ai-auto-alt-text-generator'); ?></option>
					</select>
				</div>
				<div class="altify-ai-field">
					<label for="altify-media-date-from"><?php esc_html_e('Date from', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-media-date-from" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-media-date-to"><?php esc_html_e('Date to', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-media-date-to" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-media-batch-size"><?php esc_html_e('Batch size', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-media-batch-size" type="number" min="1" max="100" value="10" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-media-start-offset"><?php esc_html_e('Start offset', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-media-start-offset" type="number" min="0" step="1" value="0" />
				</div>
			</div>
			<p class="description"><?php esc_html_e('Start offset helps resume large runs from a specific point (best with Process = All). Leave 0 for normal runs.', 'altify-ai-auto-alt-text-generator'); ?></p>

			<div class="altify-ai-actions">
				<button type="button" class="button button-primary" id="altify-media-start"><?php esc_html_e('Start', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-media-pause"><?php esc_html_e('Pause', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-media-resume"><?php esc_html_e('Resume', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-media-stop"><?php esc_html_e('Stop', 'altify-ai-auto-alt-text-generator'); ?></button>
				<span class="altify-ai-status" id="altify-media-status"><?php esc_html_e('Click Start to begin.', 'altify-ai-auto-alt-text-generator'); ?></span>
			</div>

			<div class="altify-ai-counters">
				<span><?php esc_html_e('Processed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-processed">0</strong></span>
				<span><?php esc_html_e('Success', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-success">0</strong></span>
				<span><?php esc_html_e('Skipped', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-skipped">0</strong></span>
				<span><?php esc_html_e('Failed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-failed">0</strong></span>
				<span><?php esc_html_e('AI generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-ai">0</strong></span>
				<span><?php esc_html_e('Offline generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-offline">0</strong></span>
				<span><?php esc_html_e('Offline fallback', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-offline-fallback">0</strong></span>
				<span><?php esc_html_e('Fallback used', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-fallback">0</strong></span>
				<span><?php esc_html_e('From cache', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-cached">0</strong></span>
			</div>

			<div class="altify-ai-summary">
				<h3><?php esc_html_e('Run Summary', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<div class="altify-ai-summary-grid">
					<span><?php esc_html_e('Started', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-summary-started">-</strong></span>
					<span><?php esc_html_e('Elapsed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-summary-elapsed">-</strong></span>
					<span><?php esc_html_e('Average speed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-summary-speed">-</strong></span>
					<span><?php esc_html_e('Last error', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-media-summary-error">-</strong></span>
				</div>
			</div>

			<div class="altify-ai-log-wrap">
				<h3><?php esc_html_e('Generation History', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<p class="description"><?php esc_html_e('Shows source, method (AI/Offline/Cache), and ALT preview text.', 'altify-ai-auto-alt-text-generator'); ?></p>
				<p class="description"><?php printf(esc_html__('Up to %d rows are stored.', 'altify-ai-auto-alt-text-generator'), absint(Altify_AI_Logger::MAX_LOGS)); ?></p>
				<div class="altify-ai-log-controls">
					<label><input type="checkbox" id="altify-media-log-select-all" /> <?php esc_html_e('Select all', 'altify-ai-auto-alt-text-generator'); ?></label>
					<button type="button" class="button" id="altify-media-log-delete-selected"><?php esc_html_e('Remove Selected', 'altify-ai-auto-alt-text-generator'); ?></button>
					<button type="button" class="button button-link-delete" id="altify-media-log-clear-all"><?php esc_html_e('Clear All', 'altify-ai-auto-alt-text-generator'); ?></button>
				</div>
				<div class="altify-ai-log-panel">
					<table class="wp-list-table widefat striped altify-ai-log-table">
						<thead>
							<tr>
								<th scope="col" class="check-column"><?php esc_html_e('Select', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Date/Time', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Level', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Source', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Method', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Attachment', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('ALT Preview', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Message', 'altify-ai-auto-alt-text-generator'); ?></th>
							</tr>
						</thead>
						<tbody id="altify-media-logs"></tbody>
					</table>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render offline bulk media tab.
	 *
	 * @return void
	 */
	private function render_offline_tab() {
		$settings     = altify_ai_get_settings();
		$default_mode = !empty($settings['only_fill_empty_alt']) ? 'missing' : 'all';
		?>
		<div class="altify-ai-panel">
			<h2><?php esc_html_e('Offline ALT Generator (No API)', 'altify-ai-auto-alt-text-generator'); ?></h2>
			<p class="description"><?php esc_html_e('This tab never calls OpenAI. ALT text is generated from attachment metadata (title, caption, description, filename).', 'altify-ai-auto-alt-text-generator'); ?></p>
			<p class="description"><?php esc_html_e('Use this when API quota is unavailable, or when you want a safe metadata-based run.', 'altify-ai-auto-alt-text-generator'); ?></p>
			<div class="altify-ai-filters">
				<div class="altify-ai-field">
					<label for="altify-offline-mode"><?php esc_html_e('Process', 'altify-ai-auto-alt-text-generator'); ?></label>
					<select id="altify-offline-mode">
						<option value="missing" <?php selected($default_mode, 'missing'); ?>><?php esc_html_e('Only missing ALT', 'altify-ai-auto-alt-text-generator'); ?></option>
						<option value="all" <?php selected($default_mode, 'all'); ?>><?php esc_html_e('All images', 'altify-ai-auto-alt-text-generator'); ?></option>
					</select>
				</div>
				<div class="altify-ai-field">
					<label for="altify-offline-date-from"><?php esc_html_e('Date from', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-offline-date-from" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-offline-date-to"><?php esc_html_e('Date to', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-offline-date-to" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-offline-batch-size"><?php esc_html_e('Batch size', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-offline-batch-size" type="number" min="1" max="100" value="10" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-offline-start-offset"><?php esc_html_e('Start offset', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-offline-start-offset" type="number" min="0" step="1" value="0" />
				</div>
			</div>
			<p class="description"><?php esc_html_e('Start offset helps resume large runs from a specific point (best with Process = All). Leave 0 for normal runs.', 'altify-ai-auto-alt-text-generator'); ?></p>

			<div class="altify-ai-actions">
				<button type="button" class="button button-primary" id="altify-offline-start"><?php esc_html_e('Start', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-offline-pause"><?php esc_html_e('Pause', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-offline-resume"><?php esc_html_e('Resume', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-offline-stop"><?php esc_html_e('Stop', 'altify-ai-auto-alt-text-generator'); ?></button>
				<span class="altify-ai-status" id="altify-offline-status"><?php esc_html_e('Click Start to begin.', 'altify-ai-auto-alt-text-generator'); ?></span>
			</div>

			<div class="altify-ai-counters">
				<span><?php esc_html_e('Processed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-processed">0</strong></span>
				<span><?php esc_html_e('Success', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-success">0</strong></span>
				<span><?php esc_html_e('Skipped', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-skipped">0</strong></span>
				<span><?php esc_html_e('Failed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-failed">0</strong></span>
				<span><?php esc_html_e('AI generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-ai">0</strong></span>
				<span><?php esc_html_e('Offline generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-offline">0</strong></span>
				<span><?php esc_html_e('Offline fallback', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-offline-fallback">0</strong></span>
				<span><?php esc_html_e('Fallback used', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-fallback">0</strong></span>
				<span><?php esc_html_e('From cache', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-cached">0</strong></span>
			</div>

			<div class="altify-ai-summary">
				<h3><?php esc_html_e('Run Summary', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<div class="altify-ai-summary-grid">
					<span><?php esc_html_e('Started', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-summary-started">-</strong></span>
					<span><?php esc_html_e('Elapsed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-summary-elapsed">-</strong></span>
					<span><?php esc_html_e('Average speed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-summary-speed">-</strong></span>
					<span><?php esc_html_e('Last error', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-offline-summary-error">-</strong></span>
				</div>
			</div>

			<div class="altify-ai-log-wrap">
				<h3><?php esc_html_e('Generation History', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<p class="description"><?php esc_html_e('Shows source, method (AI/Offline/Cache), and ALT preview text.', 'altify-ai-auto-alt-text-generator'); ?></p>
				<p class="description"><?php printf(esc_html__('Up to %d rows are stored.', 'altify-ai-auto-alt-text-generator'), absint(Altify_AI_Logger::MAX_LOGS)); ?></p>
				<div class="altify-ai-log-controls">
					<label><input type="checkbox" id="altify-offline-log-select-all" /> <?php esc_html_e('Select all', 'altify-ai-auto-alt-text-generator'); ?></label>
					<button type="button" class="button" id="altify-offline-log-delete-selected"><?php esc_html_e('Remove Selected', 'altify-ai-auto-alt-text-generator'); ?></button>
					<button type="button" class="button button-link-delete" id="altify-offline-log-clear-all"><?php esc_html_e('Clear All', 'altify-ai-auto-alt-text-generator'); ?></button>
				</div>
				<div class="altify-ai-log-panel">
					<table class="wp-list-table widefat striped altify-ai-log-table">
						<thead>
							<tr>
								<th scope="col" class="check-column"><?php esc_html_e('Select', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Date/Time', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Level', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Source', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Method', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Attachment', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('ALT Preview', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Message', 'altify-ai-auto-alt-text-generator'); ?></th>
							</tr>
						</thead>
						<tbody id="altify-offline-logs"></tbody>
					</table>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render WooCommerce tab.
	 *
	 * @return void
	 */
	private function render_woocommerce_tab() {
		$settings = altify_ai_get_settings();
		$default_mode = !empty($settings['only_fill_empty_alt']) ? 'missing' : 'all';
		?>
		<form method="post" action="options.php" class="altify-ai-settings-form">
			<?php settings_fields('altify_ai_settings_group'); ?>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><?php esc_html_e('Enable WooCommerce features', 'altify-ai-auto-alt-text-generator'); ?></th>
					<td>
						<label>
							<input name="altify_ai_settings[enable_woo_support]" type="hidden" value="0" />
							<input name="altify_ai_settings[enable_woo_support]" type="checkbox" value="1" <?php checked(!empty($settings['enable_woo_support'])); ?> />
							<?php esc_html_e('Enable product image ALT generation features.', 'altify-ai-auto-alt-text-generator'); ?>
						</label>
					</td>
				</tr>
			</table>
			<?php submit_button(__('Save WooCommerce Settings', 'altify-ai-auto-alt-text-generator')); ?>
		</form>

		<?php if (!$this->woocommerce->is_active()) : ?>
			<div class="notice notice-warning inline"><p><?php esc_html_e('WooCommerce is not active. Activate WooCommerce to use this tab.', 'altify-ai-auto-alt-text-generator'); ?></p></div>
			<?php return; ?>
		<?php endif; ?>

		<?php if (!$this->woocommerce->is_enabled()) : ?>
			<div class="notice notice-info inline"><p><?php esc_html_e('WooCommerce support is currently disabled in settings.', 'altify-ai-auto-alt-text-generator'); ?></p></div>
			<?php return; ?>
		<?php endif; ?>

		<div class="altify-ai-panel">
			<h2><?php esc_html_e('WooCommerce Product Image Bulk Tool', 'altify-ai-auto-alt-text-generator'); ?></h2>
			<p class="description"><?php esc_html_e('For large catalogs, start with a smaller batch size (5-10) and use Start offset to resume safely.', 'altify-ai-auto-alt-text-generator'); ?></p>
			<div class="altify-ai-filters">
				<div class="altify-ai-field">
					<label for="altify-woo-mode"><?php esc_html_e('Process', 'altify-ai-auto-alt-text-generator'); ?></label>
					<select id="altify-woo-mode">
						<option value="missing" <?php selected($default_mode, 'missing'); ?>><?php esc_html_e('Only missing ALT', 'altify-ai-auto-alt-text-generator'); ?></option>
						<option value="all" <?php selected($default_mode, 'all'); ?>><?php esc_html_e('All product images', 'altify-ai-auto-alt-text-generator'); ?></option>
					</select>
				</div>
				<div class="altify-ai-field">
					<label for="altify-woo-category"><?php esc_html_e('Product category', 'altify-ai-auto-alt-text-generator'); ?></label>
					<select id="altify-woo-category">
						<option value=""><?php esc_html_e('All categories', 'altify-ai-auto-alt-text-generator'); ?></option>
						<?php
						$terms = $this->woocommerce->get_product_categories();
						if (!empty($terms) && is_array($terms)) {
							foreach ($terms as $term) {
								if (empty($term->slug) || empty($term->name)) {
									continue;
								}
								echo '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
							}
						}
						?>
					</select>
				</div>
				<div class="altify-ai-field">
					<label for="altify-woo-date-from"><?php esc_html_e('Date from', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-woo-date-from" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-woo-date-to"><?php esc_html_e('Date to', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-woo-date-to" type="date" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-woo-batch-size"><?php esc_html_e('Batch size', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-woo-batch-size" type="number" min="1" max="50" value="10" />
				</div>
				<div class="altify-ai-field">
					<label for="altify-woo-start-offset"><?php esc_html_e('Start offset (products)', 'altify-ai-auto-alt-text-generator'); ?></label>
					<input id="altify-woo-start-offset" type="number" min="0" step="1" value="0" />
				</div>
			</div>

			<div class="altify-ai-actions">
				<button type="button" class="button button-primary" id="altify-woo-start"><?php esc_html_e('Start', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-woo-pause"><?php esc_html_e('Pause', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-woo-resume"><?php esc_html_e('Resume', 'altify-ai-auto-alt-text-generator'); ?></button>
				<button type="button" class="button" id="altify-woo-stop"><?php esc_html_e('Stop', 'altify-ai-auto-alt-text-generator'); ?></button>
				<span class="altify-ai-status" id="altify-woo-status"><?php esc_html_e('Click Start to begin.', 'altify-ai-auto-alt-text-generator'); ?></span>
			</div>

			<div class="altify-ai-counters">
				<span><?php esc_html_e('Processed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-processed">0</strong></span>
				<span><?php esc_html_e('Success', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-success">0</strong></span>
				<span><?php esc_html_e('Skipped', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-skipped">0</strong></span>
				<span><?php esc_html_e('Failed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-failed">0</strong></span>
				<span><?php esc_html_e('AI generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-ai">0</strong></span>
				<span><?php esc_html_e('Offline generated', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-offline">0</strong></span>
				<span><?php esc_html_e('Offline fallback', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-offline-fallback">0</strong></span>
				<span><?php esc_html_e('Fallback used', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-fallback">0</strong></span>
				<span><?php esc_html_e('From cache', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-cached">0</strong></span>
			</div>

			<div class="altify-ai-summary">
				<h3><?php esc_html_e('Run Summary', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<div class="altify-ai-summary-grid">
					<span><?php esc_html_e('Started', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-summary-started">-</strong></span>
					<span><?php esc_html_e('Elapsed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-summary-elapsed">-</strong></span>
					<span><?php esc_html_e('Average speed', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-summary-speed">-</strong></span>
					<span><?php esc_html_e('Last error', 'altify-ai-auto-alt-text-generator'); ?>: <strong id="altify-woo-summary-error">-</strong></span>
				</div>
			</div>

			<div class="altify-ai-log-wrap">
				<h3><?php esc_html_e('Generation History', 'altify-ai-auto-alt-text-generator'); ?></h3>
				<p class="description"><?php esc_html_e('Shows source, method (AI/Offline/Cache), and ALT preview text.', 'altify-ai-auto-alt-text-generator'); ?></p>
				<p class="description"><?php printf(esc_html__('Up to %d rows are stored.', 'altify-ai-auto-alt-text-generator'), absint(Altify_AI_Logger::MAX_LOGS)); ?></p>
				<div class="altify-ai-log-controls">
					<label><input type="checkbox" id="altify-woo-log-select-all" /> <?php esc_html_e('Select all', 'altify-ai-auto-alt-text-generator'); ?></label>
					<button type="button" class="button" id="altify-woo-log-delete-selected"><?php esc_html_e('Remove Selected', 'altify-ai-auto-alt-text-generator'); ?></button>
					<button type="button" class="button button-link-delete" id="altify-woo-log-clear-all"><?php esc_html_e('Clear All', 'altify-ai-auto-alt-text-generator'); ?></button>
				</div>
				<div class="altify-ai-log-panel">
					<table class="wp-list-table widefat striped altify-ai-log-table">
						<thead>
							<tr>
								<th scope="col" class="check-column"><?php esc_html_e('Select', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Date/Time', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Level', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Source', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Method', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Attachment', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('ALT Preview', 'altify-ai-auto-alt-text-generator'); ?></th>
								<th scope="col"><?php esc_html_e('Message', 'altify-ai-auto-alt-text-generator'); ?></th>
							</tr>
						</thead>
						<tbody id="altify-woo-logs"></tbody>
					</table>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Retrieve a scalar POST value.
	 *
	 * @param string $key     Field key.
	 * @param mixed  $default Default value.
	 *
	 * @return mixed
	 */
	private function get_post_scalar($key, $default = '') {
		$value = filter_input(INPUT_POST, $key, FILTER_UNSAFE_RAW);
		if (null === $value || false === $value || is_array($value)) {
			return $default;
		}

		return wp_unslash($value);
	}

	/**
	 * Retrieve a string array from POST.
	 *
	 * @param string $key Field key.
	 *
	 * @return array
	 */
	private function get_post_array($key) {
		$values = filter_input(INPUT_POST, $key, FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY);
		if (!is_array($values)) {
			return array();
		}

		$output = array();
		foreach ($values as $value) {
			if (is_array($value)) {
				continue;
			}
			$output[] = wp_unslash((string) $value);
		}

		return $output;
	}
}
