<?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', 'wppowersuite-lite' ); ?></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.', 'wppowersuite-lite' ); ?>
	</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 );
				$has_site_key = ConnectionSettings::hasSiteKey( $provider_id );
				$from_config  = ConnectionSettings::isApiKeyFromConfig( $provider_id );
				$from_network = ConnectionSettings::isApiKeyFromNetwork( $provider_id ) && ! $has_site_key;
				$description  = (string) ( $provider_meta['description'] ?? '' );
				$status       = ConnectionSettings::getProviderDisplayStatus( $provider_id );
				$status_class = match ( $status ) {
					'verified' => 'is-connected',
					'saved'    => 'is-saved',
					'failed'   => 'is-failed',
					default    => 'is-disconnected',
				};
				$status_label = match ( $status ) {
					'verified' => __( 'Connected', 'wppowersuite-lite' ),
					'saved'    => __( 'Key saved', 'wppowersuite-lite' ),
					'failed'   => __( 'Invalid key', 'wppowersuite-lite' ),
					default    => __( 'Not connected', 'wppowersuite-lite' ),
				};
				?>
				<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 esc_attr( $status_class ); ?>">
								<?php echo esc_html( $status_label ); ?>
							</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', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?></label>
						<p class="description"><?php esc_html_e( 'Leave blank to keep the saved key.', 'wppowersuite-lite' ); ?></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).', 'wppowersuite-lite' ),
									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.', 'wppowersuite-lite' ); ?></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_site_key ? '••••••••••••••••' : (string) $provider_meta['placeholder'] ); ?>"
								autocomplete="new-password"
							/>
							<p class="wpps-ai-connections-key-actions" style="<?php echo esc_attr( $has_site_key ? '' : 'display:none;' ); ?>">
								<button type="button" class="button-link-delete wpps-ai-connections-remove-key" data-provider="<?php echo esc_attr( $provider_id ); ?>" data-field="<?php echo esc_attr( $field ); ?>" data-scope="site">
									<?php esc_html_e( 'Remove saved key', 'wppowersuite-lite' ); ?>
								</button>
							</p>
						<?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', 'wppowersuite-lite' ),
									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', 'wppowersuite-lite' ); ?></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.', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Optional fallback keys for all subsites on this network.', 'wppowersuite-lite' ); ?></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'];
							?>
							<?php
							$has_network_key = NetworkSettings::getNetworkKey( $field ) !== '';
							?>
							<section class="wpps-ai-connections-provider" data-provider="<?php echo esc_attr( $provider_id ); ?>">
								<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( $has_network_key ? '••••••••••••••••' : sprintf(
										/* translators: %s: provider name */
										__( 'Enter network %s key', 'wppowersuite-lite' ),
										$label
									) ); ?>"
									autocomplete="new-password"
								/>
								<p class="wpps-ai-connections-key-actions" style="<?php echo esc_attr( $has_network_key ? '' : 'display:none;' ); ?>">
									<button type="button" class="button-link-delete wpps-ai-connections-remove-key" data-provider="<?php echo esc_attr( $provider_id ); ?>" data-field="<?php echo esc_attr( $field ); ?>" data-scope="network">
										<?php esc_html_e( 'Remove network key', 'wppowersuite-lite' ); ?>
									</button>
								</p>
							</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', 'wppowersuite-lite' ); ?></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.', 'wppowersuite-lite' ); ?></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', 'wppowersuite-lite' ); ?></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.', 'wppowersuite-lite' ); ?></p>
	<ul class="wpps-ai-connections-modules-list">
		<li><?php esc_html_e( 'AI Alt Text Generator', 'wppowersuite-lite' ); ?></li>
		<li><?php esc_html_e( 'Basic Forms — AI Form Builder', 'wppowersuite-lite' ); ?></li>
	</ul>
	<p class="description">
		<?php
		$constant_markup = implode(
			', ',
			array_map(
				static fn( string $constant ): string => '<code>' . esc_html( $constant ) . '</code>',
				$config_constants
			)
		);
		echo wp_kses(
			sprintf(
				/* translators: %s: wp-config.php constant names */
				__( 'Optional: define keys in wp-config.php using %s for environment-managed secrets.', 'wppowersuite-lite' ),
				$constant_markup
			),
			[ 'code' => [] ]
		);
		?>
	</p>
</div>
