<?php
/**
 * Shared helpers for Advanced settings tabs (debug logging, destructive confirmations).
 *
 * @package Rsmspark_Suite
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Advanced_Settings
 */
final class Rsmspark_Advanced_Settings {

	/**
	 * Read a plugin advanced settings array from the options table.
	 *
	 * @param string               $option_key Option name.
	 * @param array<string, mixed> $defaults   Default values.
	 * @return array<string, mixed>
	 */
	public static function get( $option_key, array $defaults = array() ) {
		$stored = get_option( $option_key, array() );

		return wp_parse_args( is_array( $stored ) ? $stored : array(), $defaults );
	}

	/**
	 * Persist advanced settings.
	 *
	 * @param string               $option_key Option name.
	 * @param array<string, mixed> $settings   Settings to save.
	 * @return void
	 */
	public static function save( $option_key, array $settings ) {
		update_option( $option_key, $settings, false );
	}

	/**
	 * Whether debug mode is enabled for an option key.
	 *
	 * @param string $option_key Option name.
	 * @return bool
	 */
	public static function is_debug( $option_key ) {
		$settings = self::get( $option_key );

		return ! empty( $settings['debug_mode'] );
	}

	/**
	 * Write a debug line when WP_DEBUG is on and plugin debug mode is enabled.
	 *
	 * @param string               $source  Plugin slug or label.
	 * @param string               $message Log message.
	 * @param array<string, mixed> $context Optional context.
	 * @param string               $option_key Advanced settings option key.
	 * @return void
	 */
	public static function log( $source, $message, array $context = array(), $option_key = '' ) {
		if ( '' !== $option_key && ! self::is_debug( $option_key ) ) {
			return;
		}

		if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
			return;
		}

		$line = '[RSM ' . $source . '] ' . $message;
		if ( ! empty( $context ) ) {
			$line .= ' ' . wp_json_encode( $context, JSON_UNESCAPED_SLASHES );
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		error_log( $line );
	}

	/**
	 * Verify the admin typed the expected confirmation phrase.
	 *
	 * @param string $field_name POST field name.
	 * @param string $phrase     Required phrase (e.g. RESET).
	 * @return bool
	 */
	public static function confirmation_ok( $field_name, $phrase ) {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified in caller via check_ajax_referer/check_admin_referer.
		if ( ! isset( $_POST[ $field_name ] ) ) {
			return false;
		}

		$typed = sanitize_text_field( wp_unslash( (string) $_POST[ $field_name ] ) );
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		return $phrase === $typed;
	}

	/**
	 * Render a typed confirmation field for destructive actions.
	 *
	 * @param string $field_id    Input id/name.
	 * @param string $phrase      Phrase the user must type.
	 * @param string $description Optional help text.
	 * @return void
	 */
	public static function render_confirmation_input( $field_id, $phrase, $description = '' ) {
		?>
		<p>
			<label for="<?php echo esc_attr( $field_id ); ?>">
				<?php
				printf(
					/* translators: %s: confirmation word the user must type */
					esc_html__( 'Type %s to confirm', 'rsm-content-widgets' ),
					'<code>' . esc_html( $phrase ) . '</code>'
				);
				?>
			</label><br />
			<input type="text" class="regular-text code" name="<?php echo esc_attr( $field_id ); ?>" id="<?php echo esc_attr( $field_id ); ?>" autocomplete="off" />
		</p>
		<?php if ( '' !== $description ) : ?>
			<p class="description"><?php echo esc_html( $description ); ?></p>
		<?php endif; ?>
		<?php
	}

	/**
	 * Open a danger-zone fieldset.
	 *
	 * @param string $title Section title.
	 * @return void
	 */
	public static function render_danger_zone_open( $title = '' ) {
		if ( '' === $title ) {
			$title = __( 'Danger zone', 'rsm-content-widgets' );
		}
		?>
		<h2 class="rsm-settings-section-title rsm-advanced-danger-title"><?php echo esc_html( $title ); ?></h2>
		<?php
		rsmspark_suite_render_admin_notice(
			__( 'These actions are destructive and cannot be undone.', 'rsm-content-widgets' ),
			array( 'logo' => false )
		);
		?>
		<?php
	}

	/**
	 * @param string $text Message.
	 * @return void
	 */
	private static function render_notice( $text ) {
		rsmspark_suite_render_admin_notice( (string) $text );
	}

	/**
	 * Render common Advanced-tab admin notices from query args.
	 *
	 * @param array<string, string> $messages Optional overrides keyed by adv_err|updated|purged|reset|cache_cleared.
	 * @return void
	 */
	public static function render_admin_notices( array $messages = array() ) {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin notice flag; no state change.
		$adv_err        = isset( $_GET['adv_err'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['adv_err'] ) ) : '';
		$updated        = isset( $_GET['updated'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['updated'] ) ) : '';
		$settings_saved = isset( $_GET['settings-updated'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['settings-updated'] ) ) : '';
		$purged         = isset( $_GET['purged'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['purged'] ) ) : '';
		$reset          = isset( $_GET['reset'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['reset'] ) ) : '';
		$cache_cleared  = isset( $_GET['cache_cleared'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['cache_cleared'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		if ( 'confirm' === $adv_err ) {
			$text = $messages['adv_err'] ?? __( 'Confirmation phrase did not match. No changes were made.', 'rsm-content-widgets' );
			self::render_notice( $text );
		}

		if ( '' !== $updated || '' !== $settings_saved ) {
			$text = $messages['updated'] ?? __( 'Settings saved.', 'rsm-content-widgets' );
			self::render_notice( $text );
		}

		if ( '' !== $purged ) {
			$count = absint( $purged );
			$text  = $messages['purged'] ?? sprintf(
				/* translators: %d: number of deleted records */
				__( 'Deleted %d record(s).', 'rsm-content-widgets' ),
				$count
			);
			self::render_notice( $text );
		}

		if ( '' !== $reset ) {
			$text = $messages['reset'] ?? __( 'Settings were reset. License fields were preserved.', 'rsm-content-widgets' );
			self::render_notice( $text );
		}

		if ( '' !== $cache_cleared ) {
			$text = $messages['cache_cleared'] ?? __( 'Cache cleared.', 'rsm-content-widgets' );
			self::render_notice( $text );
		}
	}
}
