<?php
/**
 * AI Connections settings tab partial.
 *
 * @package WP_PowerSuite\Admin\Views
 */

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

use WP_PowerSuite\AI\ConnectionSettings;
use WP_PowerSuite\AI\NetworkSettings;
use WP_PowerSuite\AI\ProviderRegistry;

$ai_settings      = ConnectionSettings::get();
$ai_provider      = (string) ( $ai_settings['provider'] ?? 'openai' );
$ai_providers     = ConnectionSettings::providerLabels();
$provider_fields  = ConnectionSettings::providerFieldMeta();
$config_constants = [];
foreach ( ProviderRegistry::definitions() as $definition ) {
	$constant = (string) ( $definition['config_constant'] ?? '' );
	if ( $constant !== '' ) {
		$config_constants[] = $constant;
	}
}
?>

<div class="wp-powersuite-settings__card card wpps-settings-card--section wpps-ai-connections-card">
	<h2 class="wp-powersuite-settings__card-title wpps-settings-section-title"><?php esc_html_e( 'AI providers', 'wp-powersuite' ); ?></h2>
	<p class="wpps-settings-section-desc">
		<?php esc_html_e( 'Add API keys for each provider you want to use. Modules pick from these connections — they do not store their own keys.', 'wp-powersuite' ); ?>
	</p>

	<div class="wpps-ai-connections-form">
		<div class="wpps-ai-connections-providers">
			<?php foreach ( $provider_fields as $provider_id => $provider_meta ) : ?>
				<?php
				$label        = $ai_providers[ $provider_id ] ?? $provider_id;
				$field        = (string) $provider_meta['field'];
				$has_key      = ConnectionSettings::hasApiKey( $provider_id );
				$from_config  = ConnectionSettings::isApiKeyFromConfig( $provider_id );
				$from_network = ConnectionSettings::isApiKeyFromNetwork( $provider_id ) && trim( (string) ( $ai_settings[ $field ] ?? '' ) ) === '';
				$description  = (string) ( $provider_meta['description'] ?? '' );
				?>
				<section class="wpps-ai-connections-provider" data-provider="<?php echo esc_attr( $provider_id ); ?>">
					<div class="wpps-ai-connections-provider__header">
						<div class="wpps-ai-connections-provider__title-wrap">
							<h3 class="wpps-ai-connections-provider__title"><?php echo esc_html( $label ); ?></h3>
							<span class="wpps-ai-connections-provider__status<?php echo $has_key ? ' is-connected' : ' is-disconnected'; ?>">
								<?php echo esc_html( $has_key ? __( 'Connected', 'wp-powersuite' ) : __( 'Not connected', 'wp-powersuite' ) ); ?>
							</span>
						</div>
						<label class="wpps-ai-connections-default">
							<input type="radio" name="wpps_ai_connections_default_provider" class="wpps-ai-connections-field-input wpps-ai-connections-default-input" value="<?php echo esc_attr( $provider_id ); ?>" <?php checked( $ai_provider, $provider_id ); ?> />
							<span><?php esc_html_e( 'Default provider', 'wp-powersuite' ); ?></span>
						</label>
					</div>

					<div class="wpps-ai-connections-provider__body">
						<?php if ( $description !== '' ) : ?>
							<p class="description"><?php echo esc_html( $description ); ?></p>
						<?php endif; ?>

						<label class="wpps-settings-row__label" for="<?php echo esc_attr( (string) $provider_meta['input_id'] ); ?>"><?php esc_html_e( 'API key', 'wp-powersuite' ); ?></label>
						<p class="description"><?php esc_html_e( 'Leave blank to keep the saved key.', 'wp-powersuite' ); ?></p>

						<?php if ( $from_config ) : ?>
							<p class="description wpps-ai-connections-key-notice">
								<?php
								printf(
									/* translators: %s: wp-config constant name */
									esc_html__( 'Managed via wp-config.php (%s).', 'wp-powersuite' ),
									esc_html( (string) $provider_meta['config_constant'] )
								);
								?>
							</p>
						<?php elseif ( $from_network ) : ?>
							<p class="description wpps-ai-connections-key-notice"><?php esc_html_e( 'Using network-level API key.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<input
								type="password"
								id="<?php echo esc_attr( (string) $provider_meta['input_id'] ); ?>"
								class="regular-text wpps-ai-connections-field-input wpps-ai-connections-site-key"
								data-field="<?php echo esc_attr( $field ); ?>"
								value=""
								placeholder="<?php echo esc_attr( $has_key ? '••••••••••••••••' : (string) $provider_meta['placeholder'] ); ?>"
								autocomplete="new-password"
							/>
						<?php endif; ?>

						<div class="wpps-ai-connections-provider__test">
							<button type="button" class="button wpps-ai-connections-test-provider" data-provider="<?php echo esc_attr( $provider_id ); ?>" data-key-input="<?php echo esc_attr( (string) $provider_meta['input_id'] ); ?>">
								<?php
								printf(
									/* translators: %s: provider name */
									esc_html__( 'Test %s', 'wp-powersuite' ),
									esc_html( $label )
								);
								?>
							</button>
							<span id="wpps-ai-connections-test-result-<?php echo esc_attr( $provider_id ); ?>" class="wpps-ai-connections-test-result" aria-live="polite"></span>
						</div>
					</div>
				</section>
			<?php endforeach; ?>
		</div>

		<?php if ( NetworkSettings::isMultisite() ) : ?>
			<div class="wpps-settings-row">
				<div class="wpps-settings-row__content">
					<strong class="wpps-settings-row__label"><?php esc_html_e( 'Use network API keys', 'wp-powersuite' ); ?></strong>
					<p class="description"><?php esc_html_e( 'When a site has no local key, fall back to network-level keys configured by a super admin.', 'wp-powersuite' ); ?></p>
				</div>
				<div class="wpps-settings-row__control">
					<label class="wpps-settings-toggle">
						<input type="checkbox" id="wpps-ai-connections-use-network" class="wpps-ai-connections-field-input" value="1" <?php checked( ! empty( $ai_settings['use_network_api_keys'] ) ); ?> />
						<span><?php esc_html_e( 'Enabled', 'wp-powersuite' ); ?></span>
					</label>
				</div>
			</div>

			<?php if ( NetworkSettings::canManageNetworkKeys() ) : ?>
				<div class="wpps-ai-connections-network-keys">
					<h3 class="wpps-settings-section-title"><?php esc_html_e( 'Network API keys', 'wp-powersuite' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Optional fallback keys for all subsites on this network.', 'wp-powersuite' ); ?></p>
					<div class="wpps-ai-connections-providers wpps-ai-connections-providers--network">
						<?php foreach ( $provider_fields as $provider_id => $provider_meta ) : ?>
							<?php
							$label = $ai_providers[ $provider_id ] ?? $provider_id;
							$field = (string) $provider_meta['field'];
							?>
							<section class="wpps-ai-connections-provider">
								<h3 class="wpps-ai-connections-provider__title"><?php echo esc_html( $label ); ?></h3>
								<input
									type="password"
									id="<?php echo esc_attr( (string) $provider_meta['network_input_id'] ); ?>"
									class="regular-text wpps-ai-connections-field-input wpps-ai-connections-network-key"
									data-field="<?php echo esc_attr( $field ); ?>"
									value=""
									placeholder="<?php echo esc_attr( NetworkSettings::getNetworkKey( $field ) !== '' ? '••••••••••••••••' : sprintf(
										/* translators: %s: provider name */
										__( 'Enter network %s key', 'wp-powersuite' ),
										$label
									) ); ?>"
									autocomplete="new-password"
								/>
							</section>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>
		<?php endif; ?>

		<div class="wpps-ai-connections-actions">
			<button type="button" class="button button-primary" id="wpps-ai-connections-save"><?php esc_html_e( 'Save connections', 'wp-powersuite' ); ?></button>
		</div>

		<p class="description wpps-ai-connections-privacy"><?php esc_html_e( 'Content sent to AI modules may be transmitted to your chosen provider. Only use providers and data you are allowed to share externally.', 'wp-powersuite' ); ?></p>
	</div>
</div>

<div class="wp-powersuite-settings__card card wpps-settings-card--section">
	<h2 class="wp-powersuite-settings__card-title wpps-settings-section-title"><?php esc_html_e( 'Using these connections', 'wp-powersuite' ); ?></h2>
	<p class="wpps-settings-section-desc"><?php esc_html_e( 'Modules with AI features choose one of the providers configured above. Add keys here first, then pick a provider in each module.', 'wp-powersuite' ); ?></p>
	<ul class="wpps-ai-connections-modules-list">
		<li><?php esc_html_e( 'AI Alt Text Generator', 'wp-powersuite' ); ?></li>
		<li><?php esc_html_e( 'Basic Forms — AI Form Builder', 'wp-powersuite' ); ?></li>
	</ul>
	<p class="description">
		<?php
		$constant_markup = implode(
			', ',
			array_map(
				static fn( string $constant ): string => '<code>' . esc_html( $constant ) . '</code>',
				$config_constants
			)
		);
		printf(
			/* translators: %s: wp-config.php constant names */
			esc_html__( 'Optional: define keys in wp-config.php using %s for environment-managed secrets.', 'wp-powersuite' ),
			$constant_markup // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above.
		);
		?>
	</p>
</div>
