<?php

namespace SugarCalendarBookings\Antispam\Captcha\Settings;

use SugarCalendarBookings\Antispam\Captcha\Turnstile;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Helpers\Helpers;
use SugarCalendarBookings\Support\Helpers\UI;

/**
 * Cloudflare Turnstile settings.
 *
 * @since 1.5.0
 */
final class TurnstileSettings extends AbstractCaptchaSettings {

	/**
	 * Category key matching `Turnstile::CATEGORY`.
	 *
	 * @since 1.5.0
	 *
	 * @return string
	 */
	public function get_key(): string {

		return 'turnstile';
	}

	/**
	 * Default flat method-key written when Turnstile is freshly selected.
	 *
	 * @since 1.5.0
	 *
	 * @return string
	 */
	public function default_method_key(): string {

		return 'turnstile';
	}

	/**
	 * Card metadata for the methods-selection grid.
	 *
	 * @since 1.5.0
	 *
	 * @return array
	 */
	public function get_card(): array {

		return [
			'title'       => esc_html__( 'Turnstile', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			'icon'        => SCBOOKINGS_PLUGIN_URL . 'assets/images/icons/settings-captcha-cloudflare.svg',
			'description' => '<p>' . esc_html__( 'Cloudflare Turnstile is a free, CAPTCHA-like service for preventing form spam while protecting data privacy. It offers a user-friendly experience by confirming visitors are real humans without requiring them to solve puzzles or math questions.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) . '</p>'
				. '<p>' . wp_kses(
					sprintf(
						/* translators: %1$s - link to the SCB anti-spam documentation. */
						__( 'For more details on how Turnstile works, as well as a step by step setup guide, please check out our <a href="%1$s" target="_blank" rel="noopener">documentation</a>.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						esc_url(
							Helpers::get_utm_url(
								'https://sugarcalendar.com/docs/bookings/how-to-set-up-cloudflare-turnstile/',
								[
									'content' => 'documentation',
									'medium'  => 'plugin-settings-antispam',
								]
							)
						)
					),
					self::allowed_link_html()
				) . '</p>',
		];
	}

	/**
	 * Render the Turnstile panel HTML.
	 *
	 * Output is byte-identical to the markup previously emitted by
	 * `AntispamSettingsTab::get_turnstile_fields()`.
	 *
	 * @since 1.5.0
	 *
	 * @param string $stored_method Currently saved flat method-key.
	 *
	 * @return string
	 */
	public function render_panel( string $stored_method ): string { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found

		// Turnstile has a single method-key — the active sub-method check
		// the reCAPTCHA panel needs doesn't apply here.
		$options = Plugin::get( Options::class );

		ob_start();

		UI::text_input(
			[
				'type'        => 'text',
				'id'          => 'antispam_turnstile_site_key',
				'name'        => [ 'antispam', 'turnstile', 'site_key' ],
				'value'       => $options->get( 'antispam.turnstile.site_key' ),
				'label'       => esc_html__( 'Site Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Enter your Cloudflare Turnstile site key.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		$stored_secret     = (string) $options->get( Turnstile::SECRET_OPTION_KEY );
		$resolved_secret   = Turnstile::filter_secret_key( $stored_secret );
		$secret_overridden = self::is_secret_overridden( $resolved_secret, $stored_secret );

		UI::text_input(
			[
				'type'        => 'text',
				'id'          => 'antispam_turnstile_secret_key',
				'name'        => [ 'antispam', 'turnstile', 'secret_key' ],
				'value'       => $secret_overridden ? $resolved_secret : $stored_secret,
				'label'       => esc_html__( 'Secret Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'disabled'    => $secret_overridden,
				'description' => $secret_overridden
					? esc_html__( 'Defined via filter. Edit the filter callback in code to change this value.', 'sugar-calendar-bookings-scheduling-appointments-lite' )
					: esc_html__( 'Enter your Cloudflare Turnstile secret key.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		self::render_radio_group(
			'turnstile.theme',
			esc_html__( 'Type', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			[
				'auto'  => esc_html__( 'Auto', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'light' => esc_html__( 'Light', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'dark'  => esc_html__( 'Dark', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			],
			esc_html__( 'Select the visual theme of the Turnstile widget.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			$options->get( 'antispam.turnstile.theme' ) ?: 'auto'
		);

		$fail_message = (string) $options->get( 'antispam.turnstile.fail_message' );
		$verifier     = new Turnstile();

		UI::text_input(
			[
				'type'        => 'text',
				'id'          => 'antispam_turnstile_fail_message',
				'name'        => [ 'antispam', 'turnstile', 'fail_message' ],
				'value'       => $fail_message !== '' ? $fail_message : $verifier->get_fail_message_default(),
				'label'       => esc_html__( 'Fail Message', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Displays to users who fail the verification process.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		return ob_get_clean();
	}

	/**
	 * Validation rules for the Turnstile panel's posted fields.
	 *
	 * @since 1.5.0
	 *
	 * @return array<string, string>
	 */
	public function get_validation_rules(): array {

		return [
			'antispam.turnstile.site_key'     => 'string',
			'antispam.turnstile.secret_key'   => 'string',
			'antispam.turnstile.theme'        => 'string|in:auto,light,dark',
			'antispam.turnstile.fail_message' => 'string',
		];
	}

	/**
	 * Sanitize the Turnstile slice of the submitted antispam payload.
	 *
	 * Strips `antispam.turnstile.secret_key` when the resolved secret is
	 * filter-overridden.
	 *
	 * @since 1.5.0
	 *
	 * @param array $antispam Submitted `antispam` array slice.
	 *
	 * @return array Mutated array slice.
	 */
	public function sanitize_post_data( array $antispam ): array {

		$options       = Plugin::get( Options::class );
		$stored_secret = (string) $options->get( Turnstile::SECRET_OPTION_KEY );

		if ( self::is_secret_overridden( Turnstile::filter_secret_key( $stored_secret ), $stored_secret ) ) {
			unset( $antispam['turnstile']['secret_key'] );
		}

		return $antispam;
	}

	/**
	 * Localized JS data block contributed under
	 * `sugar_calendar_bookings_admin.antispam.turnstile`.
	 *
	 * @since 1.5.0
	 *
	 * @return array
	 */
	public function get_admin_script_data(): array {

		$options = Plugin::get( Options::class );

		return [
			'site_key' => $options->get( 'antispam.turnstile.site_key' ),
			'theme'    => $options->get( 'antispam.turnstile.theme' ) ?: 'auto',
		];
	}

	/**
	 * User-facing description shown under the preview widget when Turnstile
	 * is active and keys are complete.
	 *
	 * @since 1.5.0
	 *
	 * @return string
	 */
	public function get_preview_description(): string {

		return esc_html__( 'This Turnstile widget is generated using your site and secret keys. If an error is displayed or the preview is not showing, please double-check your keys.', 'sugar-calendar-bookings-scheduling-appointments-lite' );
	}
}
