<?php
/**
 * General AI Settings Page UI.
 *
 * This file contains the markup and logic for rendering the "General AI Settings"
 * page in the WordPress admin. It includes the OpenAI API key input, model selection,
 * temperature, language, and recommendation prompt settings.
 *
 * @package Magecomp AI Description Generator for WooCommerce
 * @since 1.0.0
 * @return void
 */

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

// Restrict access.
if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'magecomp-ai-description-generator-for-woocommerce' ) );
}

/**
 * Renders the General AI Settings page UI.
 *
 * @since 1.0.0
 * @return void
 */
function descgpt_render_general_settings_ui() {

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'magecomp-ai-description-generator-for-woocommerce' ) );
	}

	// Load current values.
	$settings = descgpt_get_general_settings();

	// Extract settings into local variables.
	$api_key               = $settings['api_key'] ?? '';
	$model                 = $settings['model'] ?? '';
	$temperature           = $settings['temperature'] ?? 0.5;
	$language              = $settings['language'] ?? '';
	$recommendation_prompt = defined( 'MCADGW_DESC_GEN_CHTGPT_PRO' )
		? ( $settings['recommendation_prompt'] ?? MCADGW_DESC_GEN_CHTGPT_DEFAULT_RECOMMENDATION_PROMPT )
		: '';
	$models                = $settings['models'] ?? array();
	$languages             = $settings['languages'] ?? array();

	$has_api_key = ! empty( $api_key );
	$masked_key  = $has_api_key ? str_repeat( '•', max( 0, strlen( $api_key ) - 4 ) ) . substr( $api_key, -4 ) : '';

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$settings_updated = isset( $_GET['settings-updated'] ) ? sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) : '';

	if ( $settings_updated ) {
		$errors = get_transient( 'settings_errors' );
		if ( $errors ) {
			$settings_errors = $errors;
			delete_transient( 'settings_errors' );
		}
	}
	?>

	<div class="descgpt-admin-wrap">
		<div class="max-w-7xl mx-auto mb-8 bg-white rounded-xl p-8 border border-gray-200 overflow-hidden">
			<!--===== Header with icons & title =====-->
			<div class="flex items-center justify-between">
				<div class="flex items-center space-x-4">
					<div class="p-3 bg-blue-100 from-blue-100 to-blue-200 rounded-xl shadow-sm">
						<svg class="w-10 h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
						</svg>
					</div>
					<div>
						<h1 class="text-3xl font-bold text-gray-900">General AI Settings</h1>
						<p class="text-sm text-gray-500 mt-1">Configure core AI parameters for content generation.</p>
					</div>
				</div>
			</div>
		</div>

		<div class="max-w-7xl mx-auto mb-8 bg-white rounded-xl p-8 border border-gray-200 overflow-hidden">
			<form method="post"
				action="<?php echo esc_url( admin_url( 'admin-post.php?action=descgpt_save_settings' ) ); ?>"
				class="descgpt-settings-form space-y-8">
				<?php wp_nonce_field( 'descgpt_save_settings' ); ?>

				<input type="hidden" id="descgpt_verify_key_nonce" value="<?php echo esc_attr( wp_create_nonce( 'descgpt_verify_key_nonce' ) ); ?>">

				<?php if ( ! empty( $settings_errors ) ) : ?>
					<?php foreach ( $settings_errors as $index => $error ) : ?>
						<?php
						$type = $error['type'] ?? 'success';
						$toast_id = 'descgpt_toast_' . $index;
						$toast_classes = array(
							'success' => 'text-green-800 bg-green-50 border-green-200',
							'error'   => 'text-red-800 bg-red-50 border-red-200',
							'warning' => 'text-yellow-800 bg-yellow-50 border-yellow-200',
							'info'    => 'text-blue-800 bg-blue-50 border-blue-200',
						);
						$toast_class = $toast_classes[ $type ] ?? $toast_classes['success'];
						?>
						<!--===== STATUS TOAST UI =====-->
						<div id="<?php echo esc_attr( $toast_id ); ?>" class="mb-6 p-4 text-sm rounded-xl border flex items-center justify-between <?php echo esc_attr( $toast_class ); ?>" role="alert">
							<div class="flex items-center">
								<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
									<path fill-rule="evenodd"
										d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
										clip-rule="evenodd" />
								</svg>
								<span class="font-medium">
									<?php echo wp_kses_post( $error['message'] ); ?>
								</span>
							</div>

							<button type="button"
								onclick="document.getElementById('<?php echo esc_attr( $toast_id ); ?>').classList.add('opacity-0','scale-95'); setTimeout(()=>document.getElementById('<?php echo esc_attr( $toast_id ); ?>').remove(),150);"
								class="ml-4 transition">
								<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
									<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
								</svg>
							</button>
						</div>
					<?php endforeach; ?>
				<?php endif; ?>

				<!--===== Fields Grid =====-->
				<div class="grid grid-cols-1 md:grid-cols-2 gap-6">

					<!--===== OpenAI API Key =====-->
					<div class="space-y-3">
						<div class="border border-gray-200 rounded-xl p-6 bg-white hover:shadow-md transition-shadow">
							<label for="descgpt_api_key" class="block text-sm font-semibold text-gray-900 mb-3">
								<?php esc_html_e( 'OpenAI API Key', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</label>

							<div class="flex flex-col items-start items-start gap-3">
								<!--===== Hidden input for saved key =====-->
								<?php if ( $has_api_key ) : ?>
									<input type="hidden" name="descgpt_api_key" value="<?php echo esc_attr( $api_key ); ?>">
								<?php endif; ?>

								<!--===== Masked display =====-->
								<input type="text" id="descgpt_api_key_masked"
									class="block w-full sm:w-64 rounded-lg border-gray-300 bg-gray-100 px-3 py-2 text-sm"
									value="<?php echo esc_attr( $masked_key ); ?>" readonly
									<?php echo ! $has_api_key ? 'style="display:none;"' : ''; ?> />

								<input type="text" id="descgpt_api_key"
									class="block w-full sm:w-64 rounded-lg border-gray-300 px-3 py-2 text-sm"
									placeholder="<?php esc_attr_e( 'Enter your OpenAI API key...', 'magecomp-ai-description-generator-for-woocommerce' ); ?>"
									<?php echo $has_api_key ? 'style="display:none;"' : ''; ?> />

								<div class="flex gap-2 mt-2 sm:mt-0">
									<?php if ( $has_api_key ) : ?>
										<button type="button" id="descgpt_update_api_key"
											class="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg shadow-sm transition">
											<?php esc_html_e( 'Update API Key', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
										</button>
									<?php endif; ?>

									<button type="button" id="descgpt_verify_api_key"
										class="px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg shadow-sm transition <?php echo $has_api_key ? 'hidden' : ''; ?>">
										<?php esc_html_e( 'Verify', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
									</button>

									<button type="button" id="descgpt_cancel_api_key"
										class="hidden px-3 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 text-sm font-medium rounded-lg shadow-sm transition">
										<?php esc_html_e( 'Cancel', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
									</button>
								</div>
							</div>
							<p id="descgpt_api_key_message" class="text-xs mt-2 text-gray-500"></p>
						</div>
					</div>

					<!--====== Model =====-->
					<div class="space-y-3">
						<div class="border border-gray-200 rounded-xl p-6 bg-white hover:shadow-md transition-shadow">
							<label for="descgpt_model" class="block text-sm font-semibold text-gray-900 mb-3">
								<?php esc_html_e( 'Model Selection', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</label>
							<select name="descgpt_model" id="descgpt_model"
								class="block w-full rounded-lg border-gray-300 shadow-sm px-3 py-2 text-sm">
								<option value=""><?php esc_html_e( 'Select an option', 'magecomp-ai-description-generator-for-woocommerce' ); ?></option>
								<?php foreach ( $models as $m ) : ?>
									<option value="<?php echo esc_attr( $m['id'] ); ?>" <?php selected( $model, $m['id'] ); ?>>
										<?php echo esc_html( $m['name'] ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="text-xs text-gray-500 mt-2">
								<?php esc_html_e( 'Select from available OpenAI models.', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</p>
						</div>
					</div>

					<!--===== Temperature =====-->
					<div class="space-y-3">
						<div class="border border-gray-200 rounded-xl p-6 bg-white hover:shadow-md transition-shadow">
							<label for="descgpt_temperature" class="block text-sm font-semibold text-gray-900 mb-3">
								<?php esc_html_e( 'Temperature', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</label>
							<input type="number" name="descgpt_temperature" id="descgpt_temperature"
								min="0" max="1" step="0.1" value="<?php echo esc_attr( $temperature ); ?>"
								class="block w-full rounded-lg border-gray-300 shadow-sm px-3 py-2 text-sm" />
							<p class="text-xs text-gray-500 mt-2">
								<?php esc_html_e( 'Controls randomness: lower = focused, higher = creative.', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</p>
						</div>
					</div>

					<!--===== Language =====-->
					<div class="space-y-3">
						<div class="border border-gray-200 rounded-xl p-6 bg-white hover:shadow-md transition-shadow">
							<label for="descgpt_language" class="block text-sm font-semibold text-gray-900 mb-3">
								<?php esc_html_e( 'Language', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</label>
							<select name="descgpt_language" id="descgpt_language"
								class="block w-full rounded-lg border-gray-300 shadow-sm px-3 py-2 text-sm">
								<option value=""><?php esc_html_e( 'Select an option', 'magecomp-ai-description-generator-for-woocommerce' ); ?></option>
								<?php foreach ( $languages as $lang ) : ?>
									<option value="<?php echo esc_attr( $lang['id'] ); ?>" <?php selected( $language, $lang['id'] ); ?>>
										<?php echo esc_html( $lang['name'] ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="text-xs text-gray-500 mt-2">
								<?php esc_html_e( 'Select the language for generated content.', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
							</p>
						</div>
					</div>

					<?php if ( defined( 'MCADGW_DESC_GEN_CHTGPT_PRO' ) ) : ?>
						<!--===== Recommendation Prompt =====-->
						<div class="space-y-3 md:col-span-2">
							<div class="border border-gray-200 rounded-xl p-6 bg-white hover:shadow-md transition-shadow">
								<label for="descgpt_recommendation_prompt" class="block text-sm font-semibold text-gray-900 mb-3">
									<?php esc_html_e( 'Recommendation Prompt', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
								</label>
								<textarea name="descgpt_recommendation_prompt" id="descgpt_recommendation_prompt" rows="10"
									class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50 px-3 py-2 text-sm">
								<?php
								echo esc_textarea( get_option( 'descgpt_recommendation_prompt', MCADGW_DESC_GEN_CHTGPT_DEFAULT_RECOMMENDATION_PROMPT ) );
								?>
							</textarea>
								<p class="text-xs text-gray-500 mt-2">
									<?php esc_html_e( 'Custom prompt for generating product recommendations. (Add " Wrap in ```json\n[...]\n``` " at the end of your prompt to ensure suggestions display correctly. If no prompt provided, default prompt will be used. Available placeholders: [order items], [categories], [tags], [catalog], [language], [num_suggestions].)', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
								</p>
							</div>
						</div>
					<?php endif; ?>

				</div>

				<!--===== Submit buttons =====-->
				<div class="flex flex-col sm:flex-row items-center justify-between pt-6 border-t border-gray-200 space-y-4 sm:space-y-0">
					<div class="text-sm text-gray-500">
						<?php esc_html_e( 'Last updated:', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
						<?php
						$updated_timestamp = strtotime( current_time( 'mysql' ) );
						echo esc_html( date_i18n( 'F j, Y g:i a', $updated_timestamp ) );
						?>
					</div>
					<div class="flex items-center space-x-3">
						<button type="submit"
							class="px-6 py-3 text-white bg-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 font-semibold rounded-xl shadow-lg focus:ring-4 focus:ring-blue-300 focus:ring-opacity-50 transition-all duration-300 transform hover:scale-105 flex items-center gap-2">
							<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
							</svg>
							<?php esc_html_e( 'Save Settings', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
						</button>
						<button type="button"
							class="px-6 py-3 text-gray-700 bg-gray-200 hover:bg-gray-300 font-medium rounded-xl transition">
							<?php esc_html_e( 'Reset to Defaults', 'magecomp-ai-description-generator-for-woocommerce' ); ?>
						</button>
					</div>
				</div>
			</form>
		</div>

		<div id="descgpt-unsaved-warning" class="fixed bottom-8 right-8 bg-yellow-50 border border-yellow-300 text-yellow-800 text-base font-semibold px-6 py-4 rounded-xl shadow-lg hidden flex items-center gap-2 z-50">
			<svg class="w-6 h-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
					d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0zM12 9v4m0 4h.01" />
			</svg>
			Hold Up! You have unsaved changes. Don’t forget to click “Save Settings”.
		</div>
	</div>

	<?php
}
