<?php
/**
 * AI Forms module settings.
 *
 * @package BasicForms
 */

use BasicForms\AiSettings;
use BasicForms\FeatureGate;
use BasicForms\FormAiModels;
use WP_PowerSuite\AI\ConnectionSettings;

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

require_once __DIR__ . '/includes/FeatureGate.php';

if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

if ( ! isset( $module_id ) || $module_id === '' ) {
	$module_id = AiSettings::MODULE_ID;
}

$premium_unlocked   = FeatureGate::isPro();
$license_page_url   = admin_url( 'admin.php?page=powersuite-license' );
$settings           = AiSettings::get();
$ai_enabled         = $premium_unlocked && AiSettings::isEnabled();
$provider           = (string) ( $settings['provider'] ?? 'openai' );
$model              = FormAiModels::sanitize( (string) ( $settings['model'] ?? '' ), $provider );
$providers          = ConnectionSettings::providerLabels();
$configured_providers = ConnectionSettings::getModuleConfiguredProviders();
$connections_url    = admin_url( 'admin.php?page=powersuite-settings&tab=ai-connections' );
$selected_has_key   = ConnectionSettings::hasApiKey( $provider );

$all_model_groups = [];
foreach ( array_keys( $providers ) as $provider_id ) {
	$all_model_groups[ $provider_id ] = FormAiModels::getGroups( $provider_id );
}
$model_groups = $all_model_groups[ $provider ] ?? [];
?>
<div class="wp-powersuite-module-settings wpps-bf-module-settings">
	<p class="description">
		<?php esc_html_e( 'Choose which connected AI provider and model power the AI Form Builder. API keys are managed under Settings → AI Connections.', 'wp-powersuite' ); ?>
	</p>

	<?php if ( ! $premium_unlocked ) : ?>
		<div class="notice notice-info inline">
			<p>
				<?php
				printf(
					/* translators: %s: link to license page */
					esc_html__( 'The AI Form Builder, CAPTCHA modules, conditional logic, form design, auto-replies, and redirects are Premium features. All field types are available on free plans. %s', 'wp-powersuite' ),
					'<a href="' . esc_url( $license_page_url ) . '">' . esc_html__( 'Activate your license', 'wp-powersuite' ) . '</a>'
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'AI Assistant', 'wp-powersuite' ); ?>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<label for="<?php echo esc_attr( $module_id ); ?>_ai_enabled">
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_ai_enabled"
								name="ai_enabled"
								class="wp-powersuite-advanced-setting"
								data-setting-key="ai_enabled"
								value="1"
								<?php checked( $ai_enabled ); ?>
								<?php disabled( ! $premium_unlocked ); ?>
							>
							<?php esc_html_e( 'Enable the AI Form Builder assistant', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When disabled, the "Generate/Modify with AI" buttons and chat assistant are hidden everywhere in AI Forms.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_provider"><?php esc_html_e( 'AI provider', 'wp-powersuite' ); ?></label>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_provider"
							name="provider"
							class="wpps-bf-input wpps-bf-ai-settings-provider wp-powersuite-advanced-setting"
							data-setting-key="provider"
							<?php disabled( ! $premium_unlocked ); ?>
						>
							<?php foreach ( $providers as $id => $label ) : ?>
								<?php
								$has_key      = in_array( $id, $configured_providers, true );
								$option_label = $label;
								if ( ! $has_key ) {
									$option_label .= ' (' . __( 'not connected', 'wp-powersuite' ) . ')';
								}
								?>
								<option value="<?php echo esc_attr( $id ); ?>" <?php selected( $provider, $id ); ?> <?php disabled( ! $has_key && $id !== $provider ); ?>>
									<?php echo esc_html( $option_label ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<p class="description">
							<?php
							printf(
								/* translators: %s: link to AI Connections settings */
								esc_html__( 'Manage API keys in %s.', 'wp-powersuite' ),
								'<a href="' . esc_url( $connections_url ) . '">' . esc_html__( 'Settings → AI Connections', 'wp-powersuite' ) . '</a>'
							);
							?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_model"><?php esc_html_e( 'Model', 'wp-powersuite' ); ?></label>
						<?php if ( ! $premium_unlocked ) : ?>
							<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
						<?php endif; ?>
					</th>
					<td>
						<select
							id="<?php echo esc_attr( $module_id ); ?>_model"
							name="model"
							class="wpps-bf-input wpps-bf-ai-settings-model wp-powersuite-advanced-setting"
							data-setting-key="model"
							data-model-groups="<?php echo esc_attr( wp_json_encode( $all_model_groups ) ); ?>"
							<?php disabled( ! $premium_unlocked ); ?>
						>
							<?php foreach ( $model_groups as $group ) : ?>
								<?php if ( empty( $group['models'] ) || ! is_array( $group['models'] ) ) : continue; endif; ?>
								<optgroup label="<?php echo esc_attr( (string) ( $group['label'] ?? '' ) ); ?>">
									<?php foreach ( $group['models'] as $val => $label ) : ?>
										<option value="<?php echo esc_attr( (string) $val ); ?>" <?php selected( $model, (string) $val ); ?>><?php echo esc_html( (string) $label ); ?></option>
									<?php endforeach; ?>
								</optgroup>
							<?php endforeach; ?>
						</select>
						<p class="description" id="<?php echo esc_attr( $module_id ); ?>_model_hint"><?php echo esc_html( FormAiModels::getSettingsHint( $provider ) ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<?php if ( $premium_unlocked && $configured_providers === [] ) : ?>
			<div class="notice notice-warning inline">
				<p>
					<?php
					printf(
						/* translators: %s: link to AI Connections settings */
						esc_html__( 'No AI providers are connected yet. Add at least one API key in %s before using the AI Form Builder.', 'wp-powersuite' ),
						'<a href="' . esc_url( $connections_url ) . '">' . esc_html__( 'Settings → AI Connections', 'wp-powersuite' ) . '</a>'
					);
					?>
				</p>
			</div>
		<?php elseif ( $premium_unlocked && ! $selected_has_key ) : ?>
			<div class="notice notice-warning inline">
				<p>
					<?php
					printf(
						/* translators: %s: link to AI Connections settings */
						esc_html__( 'The selected provider is not connected. Choose a connected provider or add its key in %s.', 'wp-powersuite' ),
						'<a href="' . esc_url( $connections_url ) . '">' . esc_html__( 'Settings → AI Connections', 'wp-powersuite' ) . '</a>'
					);
					?>
				</p>
			</div>
		<?php elseif ( $premium_unlocked ) : ?>
			<p class="description">
				<?php
				printf(
					/* translators: 1: provider label, 2: model id */
					esc_html__( '%1$s (%2$s) is connected and will be used for all AI form prompts.', 'wp-powersuite' ),
					esc_html( $providers[ $provider ] ?? $provider ),
					esc_html( $model )
				);
				?>
			</p>
		<?php endif; ?>
	</form>
</div>
<script>
(function () {
	var providerSelect = document.getElementById('<?php echo esc_js( $module_id ); ?>_provider');
	var modelSelect = document.getElementById('<?php echo esc_js( $module_id ); ?>_model');
	var hint = document.getElementById('<?php echo esc_js( $module_id ); ?>_model_hint');
	if (!providerSelect || !modelSelect) {
		return;
	}
	var groups = {};
	try {
		groups = JSON.parse(modelSelect.getAttribute('data-model-groups') || '{}');
	} catch (e) {
		groups = {};
	}
	var hints = <?php echo wp_json_encode(
		[
			'openai' => FormAiModels::getSettingsHint( 'openai' ),
			'gemini' => FormAiModels::getSettingsHint( 'gemini' ),
			'claude' => FormAiModels::getSettingsHint( 'claude' ),
		]
	); ?>;

	function normalizeGroups(providerGroups) {
		if (!providerGroups) {
			return [];
		}
		return Array.isArray(providerGroups) ? providerGroups : Object.values(providerGroups);
	}

	function rebuildModels(provider, preferred) {
		var providerGroups = normalizeGroups(groups[provider]);
		var previous = preferred || modelSelect.value;
		modelSelect.innerHTML = '';
		providerGroups.forEach(function (group) {
			if (!group || !group.models) {
				return;
			}
			var optgroup = document.createElement('optgroup');
			optgroup.label = group.label || '';
			Object.keys(group.models).forEach(function (id) {
				var option = document.createElement('option');
				option.value = id;
				option.textContent = group.models[id];
				if (id === previous) {
					option.selected = true;
				}
				optgroup.appendChild(option);
			});
			modelSelect.appendChild(optgroup);
		});
		if (!modelSelect.value && modelSelect.options.length) {
			modelSelect.selectedIndex = 0;
		}
		if (hint && hints[provider]) {
			hint.textContent = hints[provider];
		}
	}

	providerSelect.addEventListener('change', function () {
		rebuildModels(providerSelect.value, '');
	});

	rebuildModels(providerSelect.value, modelSelect.value);
})();
</script>
