<?php
/**
 * Back to Top button customizer: outputs dynamic CSS via admin-ajax and enqueues it on frontend.
 *
 * @package FoodOrd
 */

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

/**
 * Class responsible for enqueuing and outputting dynamic CSS for Back to Top button.
 */
class Foodord_Back_To_Top_Customizer {
	/**
	 * Bootstrap.
	 */
	public function init() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_dynamic_css' ), 20 );
		add_filter( 'body_class', array( $this, 'filter_body_class' ) );
		// One-time migration to update old default colors to new defaults if user hasn't customized.
		add_action( 'init', array( $this, 'maybe_migrate_old_defaults' ) );
	}

	/**
	 * Adds contextual body class when current page contains FoodOrd products shortcode or block.
	 *
	 * @param array $classes Body classes.
	 * @return array
	 */
	public function filter_body_class( $classes ) {
		if ( $this->is_foodord_products_context() ) {
			$classes[] = 'foodord-products-context';
		}
		return $classes;
	}

	/**
	 * Detect if current request is rendering a page that contains the FoodOrd products
	 * shortcode or block.
	 *
	 * @return bool
	 */
	private function is_foodord_products_context() {
		if ( is_admin() ) {
			return false;
		}
		if ( is_singular() ) {
			$post = get_post();
			if ( $post ) {
				// Shortcode detection.
				if ( function_exists( 'has_shortcode' ) && has_shortcode( $post->post_content, 'foodord_products' ) ) {
					return true;
				}
				// Block detection.
				if ( function_exists( 'has_block' ) && has_block( 'foodord/products', $post ) ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Enqueue dynamic CSS inline after theme's back-to-top stylesheet.
	 */
	public function enqueue_dynamic_css() {
		$bg    = sanitize_hex_color( get_option( 'foodord_back_to_top_bg', '#ffffff' ) );
		$hover = sanitize_hex_color( get_option( 'foodord_back_to_top_hover', '#f5f5f5' ) );
		$icon  = sanitize_hex_color( get_option( 'foodord_back_to_top_icon', '#ea004b' ) );

		$bg    = $bg ? $bg : '#ffffff';
		$hover = $hover ? $hover : '#f5f5f5';
		$icon  = $icon ? $icon : '#ea004b';

		$declarations = array(
			'--btt-color'       => $bg,
			'--btt-hover-color' => $hover,
			'--btt-icon-color'  => $icon,
		);

		$rules = array();
		foreach ( $declarations as $variable => $value ) {
			if ( '' !== $value ) {
				$rules[] = $variable . ': ' . $value . ';';
			}
		}

		if ( $rules ) {
			$css      = ':root{ ' . implode( ' ', $rules ) . ' }';
			$css_safe = $this->sanitize_inline_css( $css );
			if ( '' === $css_safe ) {
				return;
			}
			wp_enqueue_style( 'foodord-back-to-top' );
			wp_add_inline_style( 'foodord-back-to-top', $css_safe );
		}
	}

	/**
	 * Sanitize inline CSS output for wp_add_inline_style().
	 *
	 * @param string $css Raw CSS.
	 */
	private function sanitize_inline_css( string $css ): string {
		$css = wp_strip_all_tags( $css );
		$css = str_replace( array( "\0", '<', '>' ), '', $css );
		return trim( $css );
	}

	/**
	 * Migrate default color values forward when users have not customized them.
	 */
	public function maybe_migrate_old_defaults() {
		$this->maybe_run_back_to_top_migration_v1();
		$this->maybe_run_back_to_top_migration_v2();
	}

	/**
	 * Initial migration: Legacy magenta defaults → neutral palette.
	 */
	private function maybe_run_back_to_top_migration_v1() {
		if ( get_option( 'foodord_back_to_top_defaults_migrated_v1' ) ) {
			return;
		}

		$bg    = get_option( 'foodord_back_to_top_bg', '' );
		$hover = get_option( 'foodord_back_to_top_hover', '' );
		$icon  = get_option( 'foodord_back_to_top_icon', '' );

		$old_bg    = '#ea004b';
		$old_hover = '#b92a61';
		$old_icon  = '#ffffff';

		$new_bg    = '#f7f7f7';
		$new_hover = '#f5f5f5';
		$new_icon  = '#ea004b';

		if ( '' === $bg || $bg === $old_bg ) {
			$sanitized = function_exists( 'sanitize_hex_color' ) ? sanitize_hex_color( $new_bg ) : $new_bg;
			if ( $sanitized ) {
				update_option( 'foodord_back_to_top_bg', $sanitized );
			}
		}
		if ( '' === $hover || $hover === $old_hover ) {
			$sanitized = function_exists( 'sanitize_hex_color' ) ? sanitize_hex_color( $new_hover ) : $new_hover;
			if ( $sanitized ) {
				update_option( 'foodord_back_to_top_hover', $sanitized );
			}
		}
		if ( '' === $icon || $icon === $old_icon ) {
			$sanitized = function_exists( 'sanitize_hex_color' ) ? sanitize_hex_color( $new_icon ) : $new_icon;
			if ( $sanitized ) {
				update_option( 'foodord_back_to_top_icon', $sanitized );
			}
		}

		update_option( 'foodord_back_to_top_defaults_migrated_v1', '1' );
	}

	/**
	 * Second migration: Neutral gray default → white background if untouched.
	 */
	private function maybe_run_back_to_top_migration_v2() {
		if ( get_option( 'foodord_back_to_top_defaults_migrated_v2' ) ) {
			return;
		}

		$bg                = get_option( 'foodord_back_to_top_bg', '' );
		$previous_default  = '#f7f7f7';
		$new_default_bg    = '#ffffff';
		$bg_lower          = is_string( $bg ) ? strtolower( $bg ) : '';
		$previous_computed = strtolower( $previous_default );

		if ( '' === $bg_lower || $bg_lower === $previous_computed ) {
			$sanitized = function_exists( 'sanitize_hex_color' ) ? sanitize_hex_color( $new_default_bg ) : $new_default_bg;
			if ( $sanitized ) {
				update_option( 'foodord_back_to_top_bg', $sanitized );
			}
		}

		update_option( 'foodord_back_to_top_defaults_migrated_v2', '1' );
	}
}
