<?php
namespace Pay4All\Pro\Integrations\Twint\Backend;

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

/**
 * "Configurer TWINT" settings page.
 *
 * Served at admin.php?page=pay4all-twint-woo, exposed under WooCommerce as
 * « Configurer TWINT ». Three sections :
 *
 *   1) Activation de TWINT — toggle the WC payment gateway on/off. When TWINT
 *      is not yet enrolled (credentials + certificate) sections 2 and 3 are
 *      disabled and a call-to-action links to the free wizard.
 *   2) Textes du moyen de paiement (par langue) — title + description in
 *      fr / de / it / en. Save mirrors the current locale into
 *      `woocommerce_t4a_twint_settings` so the WC admin list shows them.
 *   3) Statut de la commande après paiement — physical / virtual / deferred /
 *      failed / cancelled. Same option keys the moved
 *      `WooBridge::update_order_successful()` already reads, so writing them
 *      here is enough to change the auto-completion behaviour.
 *
 * Booted from Bootstrap::register() only when WC + pay4all-for-twint are both
 * active.
 */
final class WcSettings {

	const SLUG = 'pay4all-twint-woo';

	public static function langs() : array {
		return [ 'fr', 'de', 'it', 'en' ];
	}

	public static function lang_labels() : array {
		return [
			'fr' => __( 'Français', 'pay4all-pro' ),
			'de' => __( 'Allemand', 'pay4all-pro' ),
			'it' => __( 'Italien', 'pay4all-pro' ),
			'en' => __( 'Anglais', 'pay4all-pro' ),
		];
	}

	public static function defaults() : array {
		return [
			'fr' => [ 'title' => 'TWINT', 'description' => 'Payez avec votre smartphone' ],
			'de' => [ 'title' => 'TWINT', 'description' => 'Bezahlen Sie mit Ihrem Smartphone' ],
			'it' => [ 'title' => 'TWINT', 'description' => 'Paga con il tuo smartphone' ],
			'en' => [ 'title' => 'TWINT', 'description' => 'Pay with your smartphone' ],
		];
	}

	public static function register() : void {
		add_action( 'admin_menu', [ __CLASS__, 'add_submenu' ], 12 );
		add_action( 'admin_init', [ __CLASS__, 'maybe_handle_post' ] );
		add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_assets' ] );
	}

	/**
	 * Load pay4all-for-twint's wizard.css on this page so the reformatted
	 * « Statut de la commande » section (t4a-wizard-card / t4a-field-row)
	 * inherits the same visual style as the wizard's Commande tab. The
	 * asset is guarded by T4A_PLUGIN_URL — a constant only defined when
	 * pay4all-for-twint is active, which is a hard prerequisite for the
	 * pay4all-pro TWINT integration anyway.
	 */
	public static function enqueue_assets( string $hook ) : void {
		if ( ! defined( 'T4A_PLUGIN_URL' ) || ! defined( 'T4A_PLUGIN_VERSION' ) ) { return; }
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || strpos( (string) $screen->id, self::SLUG ) === false ) { return; }
		wp_enqueue_style(
			't4a-twint-wizard',
			T4A_PLUGIN_URL . 'assets/admin/css/wizard.css',
			[],
			T4A_PLUGIN_VERSION
		);
	}

	public static function add_submenu() : void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) { return; }

		add_submenu_page(
			'woocommerce',
			__( 'Configurer TWINT', 'pay4all-pro' ),
			__( 'Configurer TWINT', 'pay4all-pro' ),
			'manage_woocommerce',
			self::SLUG,
			[ __CLASS__, 'render' ]
		);
	}

	/**
	 * True once TWINT credentials + certificate have been submitted through
	 * the pay4all-for-twint wizard. Used to grey-out the WC-specific config
	 * until the basics are in place.
	 */
	private static function is_twint_enrolled() : bool {
		return get_option( 't4a_twint_enrolled' ) === 'yes';
	}

	// ---------------------------------------------------------------------
	// POST handler
	// ---------------------------------------------------------------------

	public static function maybe_handle_post() : void {
		if ( ! isset( $_POST[ 'pay4all_twint_woo_action' ] ) ) { return; }
		if ( ! current_user_can( 'manage_woocommerce' ) ) { return; }

		$action = sanitize_key( wp_unslash( (string) $_POST[ 'pay4all_twint_woo_action' ] ) );
		$nonce  = isset( $_POST[ '_pay4all_twint_woo_nonce' ] )
			? sanitize_text_field( wp_unslash( (string) $_POST[ '_pay4all_twint_woo_nonce' ] ) )
			: '';
		if ( ! wp_verify_nonce( $nonce, 'pay4all_twint_woo_' . $action ) ) {
			wp_die( esc_html__( 'Jeton de sécurité invalide, merci de réessayer.', 'pay4all-pro' ), 403 );
		}

		// Sections 2 and 3 stay dormant until TWINT is enrolled — accepting a
		// save from a spoofed request would corrupt the WC gateway settings
		// before the merchant has finished the wizard.
		if ( in_array( $action, [ 'save_texts', 'save_statuses', 'toggle_gateway' ], true )
			&& ! self::is_twint_enrolled() ) {
			self::flash( __( 'Configurez d\'abord vos identifiants TWINT dans le menu « Pay4All TWINT ».', 'pay4all-pro' ), 'error' );
			wp_safe_redirect( add_query_arg( [ 'page' => self::SLUG ], admin_url( 'admin.php' ) ) );
			exit;
		}

		switch ( $action ) {
			case 'save_texts':
				self::save_texts();
				self::flash( __( 'Textes enregistrés et gateway TWINT activé sur le checkout.', 'pay4all-pro' ) );
				break;
			case 'save_statuses':
				self::save_statuses();
				self::flash( __( 'Statuts de commande enregistrés.', 'pay4all-pro' ) );
				break;
			case 'toggle_gateway':
				self::toggle_gateway();
				break;
		}

		wp_safe_redirect( add_query_arg( [ 'page' => self::SLUG ], admin_url( 'admin.php' ) ) );
		exit;
	}

	private static function save_texts() : void {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Called only from maybe_handle_post() which wp_verify_nonce()'s the pay4all_twint_woo_save_texts action upstream ; static analyzers don't follow the dispatch chain.
		foreach ( self::langs() as $code ) {
			foreach ( [ 'title', 'description' ] as $field ) {
				$key = 't4a_twint_' . $field . '_' . $code;
				if ( ! isset( $_POST[ $key ] ) ) { continue; }
				update_option( $key, sanitize_text_field( wp_unslash( (string) $_POST[ $key ] ) ) );
			}
		}
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		$gateway_settings = get_option( 'woocommerce_t4a_twint_settings', [] );
		if ( ! is_array( $gateway_settings ) ) { $gateway_settings = []; }
		$gateway_settings[ 'enabled' ] = 'yes';

		$current = self::current_lang();
		$gateway_settings[ 'title' ]       = get_option( 't4a_twint_title_' . $current, 'TWINT' );
		$gateway_settings[ 'description' ] = get_option( 't4a_twint_description_' . $current, '' );
		update_option( 'woocommerce_t4a_twint_settings', $gateway_settings );
	}

	private static function save_statuses() : void {
		$allowed_paid      = [ 'on-hold', 'processing', 'completed' ];
		$allowed_failed    = [ 'pending', 'failed' ];
		$allowed_cancelled = [ 'pending', 'cancelled' ];

		self::save_select( 't4a_twint_settings_order_status_non_virtual', $allowed_paid, 'processing' );
		self::save_select( 't4a_twint_settings_order_status_virtual',     $allowed_paid, 'completed' );
		self::save_select( 't4a_twint_settings_deferred_order_status',    $allowed_paid, 'on-hold' );
		self::save_select( 't4a_twint_settings_order_status_failed',      $allowed_failed, 'pending' );
		self::save_select( 't4a_twint_settings_cancelled_order_status',   $allowed_cancelled, 'cancelled' );
	}

	private static function save_select( string $key, array $allowed, string $fallback ) : void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Called only from save_statuses() → maybe_handle_post() which verified the pay4all_twint_woo_save_statuses nonce ; static analyzers don't follow the dispatch chain.
		$raw = isset( $_POST[ $key ] ) ? sanitize_key( wp_unslash( (string) $_POST[ $key ] ) ) : $fallback;
		update_option( $key, in_array( $raw, $allowed, true ) ? $raw : $fallback );
	}

	private static function toggle_gateway() : void {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Called only from maybe_handle_post() which verified the pay4all_twint_woo_toggle_gateway nonce upstream.
		$gateway_settings = get_option( 'woocommerce_t4a_twint_settings', [] );
		if ( ! is_array( $gateway_settings ) ) { $gateway_settings = []; }
		$new = isset( $_POST[ 't4a_gateway_enabled' ] ) ? 'yes' : 'no';
		$gateway_settings[ 'enabled' ] = $new;
		update_option( 'woocommerce_t4a_twint_settings', $gateway_settings );

		// Currency scoping (« Devise » checkbox) lives in the same form as
		// the activation toggle now — save both together so the merchant
		// sees a single « Mettre à jour l'état » action for the two related
		// gateway-visibility settings.
		update_option( 't4a_twint_settings_chf_only', isset( $_POST[ 't4a_twint_settings_chf_only' ] ) ? 'yes' : 'no' );
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		self::flash( $new === 'yes'
			? __( 'TWINT activé sur le checkout WooCommerce.', 'pay4all-pro' )
			: __( 'TWINT désactivé sur le checkout WooCommerce.', 'pay4all-pro' )
		);
	}

	// ---------------------------------------------------------------------
	// Rendering
	// ---------------------------------------------------------------------

	public static function render() : void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) { return; }

		$flash         = self::consume_flash();
		$flash_type    = self::consume_flash_type();
		$is_enrolled   = self::is_twint_enrolled();
		$wizard_url    = admin_url( 'admin.php?page=pay4all-settings' );
		$disabled_attr = $is_enrolled ? '' : ' disabled';
		$section_style = $is_enrolled ? '' : 'opacity:.45;pointer-events:none;';

		$statuses_paid = [
			'on-hold'    => __( 'En attente', 'pay4all-pro' ),
			'processing' => __( 'En cours', 'pay4all-pro' ),
			'completed'  => __( 'Terminée', 'pay4all-pro' ),
		];

		$opts = [
			'status_non_virtual' => get_option( 't4a_twint_settings_order_status_non_virtual', 'processing' ),
			'status_virtual'     => get_option( 't4a_twint_settings_order_status_virtual', 'completed' ),
			'status_deferred'    => get_option( 't4a_twint_settings_deferred_order_status', 'on-hold' ),
			'status_failed'      => get_option( 't4a_twint_settings_order_status_failed', 'pending' ),
			'status_cancelled'   => get_option( 't4a_twint_settings_cancelled_order_status', 'cancelled' ),
			'chf_only'           => get_option( 't4a_twint_settings_chf_only', 'no' ),
		];

		$gateway_settings = get_option( 'woocommerce_t4a_twint_settings', [] );
		$gateway_enabled  = is_array( $gateway_settings ) && ( $gateway_settings[ 'enabled' ] ?? 'no' ) === 'yes';
		$current_lang     = self::current_lang();
		$defaults         = self::defaults();
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Configurer TWINT', 'pay4all-pro' ); ?></h1>

			<?php if ( $flash ) : ?>
				<div class="notice notice-<?php echo esc_attr( $flash_type ); ?> is-dismissible"><p><?php echo esc_html( $flash ); ?></p></div>
			<?php endif; ?>

			<p style="max-width:820px;">
				<?php esc_html_e( 'Configurez ici les textes affichés au checkout et le statut appliqué automatiquement aux commandes payées par TWINT. Les identifiants TWINT (Store UUID, certificat) restent gérés depuis le menu « Pay4All TWINT ».', 'pay4all-pro' ); ?>
			</p>

			<!-- Section 1 : Activation de TWINT -->
			<h2 class="title"><?php esc_html_e( 'Activation de TWINT', 'pay4all-pro' ); ?></h2>

			<?php if ( ! $is_enrolled ) : ?>
				<div class="notice notice-warning inline" style="max-width:820px;margin:8px 0 16px;">
					<p style="margin:8px 0;">
						<strong><?php esc_html_e( 'TWINT n\'est pas encore configuré.', 'pay4all-pro' ); ?></strong><br>
						<?php esc_html_e( 'Renseignez le Store UUID, le certificat et le cash-register ID depuis le menu « Pay4All TWINT » pour activer les sections ci-dessous.', 'pay4all-pro' ); ?>
					</p>
					<p style="margin:8px 0 12px;">
						<a href="<?php echo esc_url( $wizard_url ); ?>" class="button button-primary">
							<?php esc_html_e( 'Ouvrir le configurateur TWINT', 'pay4all-pro' ); ?>
						</a>
					</p>
				</div>
			<?php endif; ?>

			<form method="post" style="margin:0 0 24px;">
				<?php wp_nonce_field( 'pay4all_twint_woo_toggle_gateway', '_pay4all_twint_woo_nonce' ); ?>
				<input type="hidden" name="pay4all_twint_woo_action" value="toggle_gateway" />
				<div style="background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:14px 18px;margin-bottom:12px;max-width:820px;">
					<label style="display:flex;align-items:center;gap:8px;">
						<input type="checkbox" name="t4a_gateway_enabled" value="yes" <?php checked( $gateway_enabled ); ?><?php echo esc_attr( $disabled_attr ); ?> />
						<?php esc_html_e( 'Activer TWINT comme moyen de paiement WooCommerce', 'pay4all-pro' ); ?>
					</label>
					<label style="display:flex;align-items:center;gap:8px;margin-top:6px;">
						<input type="checkbox" name="t4a_twint_settings_chf_only" value="yes" <?php checked( $opts[ 'chf_only' ], 'yes' ); ?><?php echo esc_attr( $disabled_attr ); ?> />
						<?php esc_html_e( 'Afficher TWINT uniquement lorsque la devise du magasin est CHF', 'pay4all-pro' ); ?>
					</label>
				</div>
				<p class="submit" style="padding:0;margin:0;">
					<button type="submit" class="button"<?php echo esc_attr( $disabled_attr ); ?>><?php esc_html_e( 'Mettre à jour l\'état', 'pay4all-pro' ); ?></button>
				</p>
			</form>

			<!-- Section 2 : Textes du moyen de paiement (par langue) -->
			<div style="<?php echo esc_attr( $section_style ); ?>">
				<h2 class="title"><?php esc_html_e( 'Textes du moyen de paiement (par langue)', 'pay4all-pro' ); ?></h2>
				<p class="description" style="max-width:820px;margin-bottom:12px;">
					<?php esc_html_e( 'Titre et description affichés au checkout WooCommerce. La bonne langue est sélectionnée automatiquement selon la langue active de la page (compatible WPML et Polylang).', 'pay4all-pro' ); ?>
				</p>
				<form method="post">
					<?php wp_nonce_field( 'pay4all_twint_woo_save_texts', '_pay4all_twint_woo_nonce' ); ?>
					<input type="hidden" name="pay4all_twint_woo_action" value="save_texts" />

					<?php foreach ( self::lang_labels() as $code => $label ) :
						$title       = get_option( 't4a_twint_title_' . $code, $defaults[ $code ][ 'title' ] );
						$description = get_option( 't4a_twint_description_' . $code, $defaults[ $code ][ 'description' ] );
						$open        = $code === $current_lang ? ' open' : '';
					?>
						<details<?php echo esc_attr( $open ); ?> style="background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:14px 18px;margin-bottom:10px;max-width:820px;">
							<summary style="cursor:pointer;font-weight:600;">
								<?php echo esc_html( $label ); ?>
								<code style="font-weight:normal;color:#646970;font-size:11px;margin-left:6px;"><?php echo esc_html( $code ); ?></code>
								<?php if ( $code === $current_lang ) : ?>
									<span style="background:#dcdcde;color:#1d2327;font-size:10px;padding:1px 8px;border-radius:10px;margin-left:6px;text-transform:uppercase;letter-spacing:.03em;"><?php esc_html_e( 'langue active', 'pay4all-pro' ); ?></span>
								<?php endif; ?>
							</summary>
							<table class="form-table" role="presentation">
								<tr>
									<th scope="row"><label for="t4a_twint_title_<?php echo esc_attr( $code ); ?>"><?php esc_html_e( 'Titre', 'pay4all-pro' ); ?></label></th>
									<td>
										<input type="text" class="regular-text" id="t4a_twint_title_<?php echo esc_attr( $code ); ?>" name="t4a_twint_title_<?php echo esc_attr( $code ); ?>" value="<?php echo esc_attr( $title ); ?>"<?php echo esc_attr( $disabled_attr ); ?> />
										<p class="description"><?php esc_html_e( 'Affiché comme nom du moyen de paiement.', 'pay4all-pro' ); ?></p>
									</td>
								</tr>
								<tr>
									<th scope="row"><label for="t4a_twint_description_<?php echo esc_attr( $code ); ?>"><?php esc_html_e( 'Description', 'pay4all-pro' ); ?></label></th>
									<td>
										<input type="text" class="regular-text" id="t4a_twint_description_<?php echo esc_attr( $code ); ?>" name="t4a_twint_description_<?php echo esc_attr( $code ); ?>" value="<?php echo esc_attr( $description ); ?>"<?php echo esc_attr( $disabled_attr ); ?> />
										<p class="description"><?php esc_html_e( 'Phrase courte affichée sous le titre au checkout.', 'pay4all-pro' ); ?></p>
									</td>
								</tr>
							</table>
						</details>
					<?php endforeach; ?>

					<p class="submit">
						<button type="submit" class="button button-primary"<?php echo esc_attr( $disabled_attr ); ?>><?php esc_html_e( 'Enregistrer les textes', 'pay4all-pro' ); ?></button>
					</p>
				</form>
			</div>

			<!-- Section 3 : Statut de la commande après paiement -->
			<div style="<?php echo esc_attr( $section_style ); ?>">
				<h2 class="title"><?php esc_html_e( 'Statut de la commande après paiement', 'pay4all-pro' ); ?></h2>
				<form method="post" class="t4a-wizard-form">
					<?php wp_nonce_field( 'pay4all_twint_woo_save_statuses', '_pay4all_twint_woo_nonce' ); ?>
					<input type="hidden" name="pay4all_twint_woo_action" value="save_statuses" />

					<section class="t4a-wizard-card">
						<p class="t4a-card-intro">
							<?php esc_html_e( 'Définit à quel statut passe la commande dès que le paiement TWINT est confirmé, selon le type de produit et l\'issue de la transaction.', 'pay4all-pro' ); ?>
						</p>

						<div class="t4a-field-row">
							<label for="t4a_status_non_virtual"><?php esc_html_e( 'Commande contenant au moins un produit physique', 'pay4all-pro' ); ?></label>
							<select id="t4a_status_non_virtual" name="t4a_twint_settings_order_status_non_virtual"<?php echo esc_attr( $disabled_attr ); ?>>
								<?php foreach ( $statuses_paid as $val => $lbl ) : ?>
									<option value="<?php echo esc_attr( $val ); ?>" <?php selected( $opts[ 'status_non_virtual' ], $val ); ?>><?php echo esc_html( $lbl ); ?></option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'Recommandé : « En cours » (le produit doit être expédié).', 'pay4all-pro' ); ?></p>
						</div>

						<div class="t4a-field-row">
							<label for="t4a_status_virtual"><?php esc_html_e( 'Commande contenant uniquement des produits virtuels / téléchargeable', 'pay4all-pro' ); ?></label>
							<select id="t4a_status_virtual" name="t4a_twint_settings_order_status_virtual"<?php echo esc_attr( $disabled_attr ); ?>>
								<?php foreach ( $statuses_paid as $val => $lbl ) : ?>
									<option value="<?php echo esc_attr( $val ); ?>" <?php selected( $opts[ 'status_virtual' ], $val ); ?>><?php echo esc_html( $lbl ); ?></option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'Recommandé : « Terminée » (rien à expédier, le client accède immédiatement au produit).', 'pay4all-pro' ); ?></p>
						</div>

						<div class="t4a-field-row">
							<label for="t4a_status_deferred"><?php esc_html_e( 'Paiement différé - en attente de confirmation', 'pay4all-pro' ); ?></label>
							<select id="t4a_status_deferred" name="t4a_twint_settings_deferred_order_status"<?php echo esc_attr( $disabled_attr ); ?>>
								<?php foreach ( $statuses_paid as $val => $lbl ) : ?>
									<option value="<?php echo esc_attr( $val ); ?>" <?php selected( $opts[ 'status_deferred' ], $val ); ?>><?php echo esc_html( $lbl ); ?></option>
								<?php endforeach; ?>
							</select>
						</div>

						<div class="t4a-field-row">
							<label for="t4a_status_failed"><?php esc_html_e( 'Paiement échoué', 'pay4all-pro' ); ?></label>
							<select id="t4a_status_failed" name="t4a_twint_settings_order_status_failed"<?php echo esc_attr( $disabled_attr ); ?>>
								<option value="pending" <?php selected( $opts[ 'status_failed' ], 'pending' ); ?>><?php esc_html_e( 'En attente de paiement', 'pay4all-pro' ); ?></option>
								<option value="failed" <?php selected( $opts[ 'status_failed' ], 'failed' ); ?>><?php esc_html_e( 'Échouée', 'pay4all-pro' ); ?></option>
							</select>
						</div>

						<div class="t4a-field-row">
							<label for="t4a_status_cancelled"><?php esc_html_e( 'Paiement annulé', 'pay4all-pro' ); ?></label>
							<select id="t4a_status_cancelled" name="t4a_twint_settings_cancelled_order_status"<?php echo esc_attr( $disabled_attr ); ?>>
								<option value="pending" <?php selected( $opts[ 'status_cancelled' ], 'pending' ); ?>><?php esc_html_e( 'En attente de paiement', 'pay4all-pro' ); ?></option>
								<option value="cancelled" <?php selected( $opts[ 'status_cancelled' ], 'cancelled' ); ?>><?php esc_html_e( 'Annulée', 'pay4all-pro' ); ?></option>
							</select>
						</div>
					</section>

					<p class="submit">
						<button type="submit" class="button button-primary"<?php echo esc_attr( $disabled_attr ); ?>><?php esc_html_e( 'Enregistrer les statuts', 'pay4all-pro' ); ?></button>
					</p>
				</form>
			</div>
		</div>
		<?php
	}

	// ---------------------------------------------------------------------
	// Helpers
	// ---------------------------------------------------------------------

	private static function current_lang() : string {
		if ( class_exists( '\\Twnt4All\\Backend\\ConfigPage' ) ) {
			return \Twnt4All\Backend\ConfigPage::current_supported_lang();
		}
		$locale = function_exists( 'determine_locale' ) ? determine_locale() : get_locale();
		$code   = strtolower( substr( (string) $locale, 0, 2 ) );
		return in_array( $code, self::langs(), true ) ? $code : 'fr';
	}

	private static function flash( string $message, string $type = 'success' ) : void {
		set_transient( 'pay4all_twint_woo_flash', $message, 30 );
		set_transient( 'pay4all_twint_woo_flash_type', $type, 30 );
	}

	private static function consume_flash() : string {
		$m = get_transient( 'pay4all_twint_woo_flash' );
		if ( $m ) { delete_transient( 'pay4all_twint_woo_flash' ); }
		return is_string( $m ) ? $m : '';
	}

	private static function consume_flash_type() : string {
		$t = get_transient( 'pay4all_twint_woo_flash_type' );
		if ( $t ) { delete_transient( 'pay4all_twint_woo_flash_type' ); }
		return in_array( $t, [ 'success', 'error', 'warning', 'info' ], true ) ? $t : 'success';
	}
}
