<?php
/**
 * RSM Footer widget — shortcode, block, classic widget, SiteOrigin.
 *
 * Shortcode: [rsmspark_footer]
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Widget_Footer
 */
class Rsmspark_Content_Widgets_Widget_Footer {

	const REGISTRY_ID = 'footer';

	/**
	 * @return void
	 */
	public static function register() {
		self::ensure_dependencies();

		require_once RSMSPARK_CONTENT_WIDGETS_PATH . 'includes/class-rsmspark-content-widgets-footer-json.php';
		Rsmspark_Content_Widgets_Footer_Json::init();

		Rsmspark_Content_Widgets_Shortcodes::add(
			Rsmspark_Content_Widgets_Registry::shortcode_tag( self::REGISTRY_ID ),
			array( __CLASS__, 'shortcode' ),
			self::REGISTRY_ID
		);

		$demo = Rsmspark_Content_Widgets_Footer_Config::demo_instance();

		Rsmspark_Content_Widgets_Blocks::add(
			'footer',
			array(
				'api_version'     => 3,
				'title'           => __( 'RSM Footer', 'rsm-content-widgets' ),
				'description'     => __( 'Multi-column footer with brand, social icons, and link columns.', 'rsm-content-widgets' ),
				'category'        => Rsmspark_Content_Widgets_Blocks::BLOCK_CATEGORY,
				'icon'            => 'align-wide',
				'keywords'        => array( 'footer', 'links', 'social', 'rsm', 'openrsm' ),
				'supports'        => array( 'html' => false ),
				'uses_context'    => array( 'widgetAreaId' ),
				'attributes'      => self::block_attributes(),
				'render_callback' => array( __CLASS__, 'render_block' ),
			)
		);

		add_action( 'widgets_init', array( __CLASS__, 'register_wp_widget' ) );
	}

	/**
	 * @return void
	 */
	public static function ensure_dependencies() {
		require_once RSMSPARK_CONTENT_WIDGETS_PATH . 'includes/class-rsmspark-content-widgets-footer-config.php';
		require_once RSMSPARK_CONTENT_WIDGETS_PATH . 'includes/widgets/class-rsmspark-content-widgets-wp-widget-footer.php';
		Rsmspark_Content_Widgets_Footer_Visibility::init();
	}

	/**
	 * @return array<string, array<string, mixed>>
	 */
	public static function block_attributes() {
		$demo = Rsmspark_Content_Widgets_Footer_Config::demo_instance();

		return array(
			'brand'              => array( 'type' => 'object', 'default' => $demo['brand'] ),
			'social'             => array( 'type' => 'array', 'default' => $demo['social'] ),
			'columns'            => array( 'type' => 'array', 'default' => $demo['columns'] ),
			'copyright'          => array( 'type' => 'string', 'default' => $demo['copyright'] ),
			'region'             => array( 'type' => 'string', 'default' => $demo['region'] ),
			'show_on'            => array(
				'type'    => 'array',
				'default' => $demo['show_on'],
				'items'   => array( 'type' => 'string' ),
			),
			'hide_on'            => array(
				'type'    => 'array',
				'default' => $demo['hide_on'],
				'items'   => array( 'type' => 'string' ),
			),
			'show_on_post_types' => array(
				'type'    => 'array',
				'default' => $demo['show_on_post_types'],
				'items'   => array( 'type' => 'string' ),
			),
			'hide_on_post_types' => array(
				'type'    => 'array',
				'default' => $demo['hide_on_post_types'],
				'items'   => array( 'type' => 'string' ),
			),
			'design'             => array( 'type' => 'object', 'default' => $demo['design'] ),
		);
	}

	/**
	 * @return void
	 */
	public static function register_wp_widget() {
		register_widget( 'Rsmspark_Content_Widgets_WP_Widget_Footer' );
	}

	/**
	 * @param array<string, mixed>|string $atts Attributes.
	 * @param string                      $content Inner content.
	 * @return string
	 */
	public static function shortcode( $atts, $content = '' ) {
		unset( $content );
		$atts = is_array( $atts ) ? $atts : array();

		if ( ! empty( $atts['config'] ) ) {
			$instance = Rsmspark_Content_Widgets_Footer_Config::sanitize_instance( $atts['config'] );
		} else {
			$instance = Rsmspark_Content_Widgets_Footer_Config::sanitize_instance( $atts );
		}

		return self::render( $instance );
	}

	/**
	 * @param array<string, mixed> $attributes Block attributes.
	 * @param string               $content    Inner blocks (unused).
	 * @param WP_Block|null        $block      Parsed block instance.
	 * @return string
	 */
	public static function render_block( $attributes, $content = '', $block = null ) {
		unset( $content );
		$attributes = self::merge_block_attributes( $attributes, $block );
		$sidebar_id = self::sidebar_id_from_block( $block );

		return self::render( is_array( $attributes ) ? $attributes : array(), $sidebar_id );
	}

	/**
	 * Merge attributes from WP_Block (parsed block JSON is authoritative).
	 *
	 * @param mixed         $attributes Render callback attributes.
	 * @param WP_Block|null $block      Block instance.
	 * @return array<string, mixed>
	 */
	public static function merge_block_attributes( $attributes, $block = null ) {
		$merged = is_array( $attributes ) ? $attributes : array();

		if ( $block instanceof WP_Block ) {
			if ( ! empty( $block->parsed_block['attrs'] ) && is_array( $block->parsed_block['attrs'] ) ) {
				$merged = array_merge( $merged, $block->parsed_block['attrs'] );
			}
			if ( ! empty( $block->attributes ) && is_array( $block->attributes ) ) {
				$merged = array_merge( $merged, $block->attributes );
			}
		}

		return $merged;
	}

	/**
	 * Resolve widget area id for multi-footer suppression in sidebars.
	 *
	 * @param WP_Block|null $block Block instance.
	 * @return string
	 */
	private static function sidebar_id_from_block( $block ) {
		if ( $block instanceof WP_Block && ! empty( $block->context['widgetAreaId'] ) ) {
			return sanitize_key( (string) $block->context['widgetAreaId'] );
		}

		return Rsmspark_Content_Widgets_Footer_Visibility::get_current_sidebar_id();
	}

	/**
	 * @param array<string, mixed> $instance Widget instance.
	 * @return array<string, mixed>
	 */
	public static function prepare_from_instance( array $instance ) {
		return Rsmspark_Content_Widgets_Footer_Config::from_siteorigin_instance( $instance );
	}

	/**
	 * @param array<string, mixed> $instance Sanitized instance.
	 * @param string               $sidebar_id Optional widget area id.
	 * @return string
	 */
	public static function render( array $instance, $sidebar_id = '' ) {
		if ( ! Rsmspark_Content_Widgets_Render::should_render( self::REGISTRY_ID ) ) {
			return '';
		}

		$instance = Rsmspark_Content_Widgets_Footer_Config::sanitize_instance( $instance );
		if ( ! Rsmspark_Content_Widgets_Footer_Visibility::instance_is_visible( $instance, $sidebar_id ) ) {
			return '';
		}

		$vars = Rsmspark_Content_Widgets_Footer_Config::prepare_view_model( $instance );
		if ( ! $vars['has_brand'] && ! $vars['has_columns'] && ! $vars['has_copyright'] ) {
			return '';
		}

		return Rsmspark_Content_Widgets_Render::render_template( self::REGISTRY_ID, 'footer.php', $vars );
	}

	/**
	 * @param string $icon Icon classes.
	 * @return string
	 */
	public static function social_icon_html( $icon ) {
		$icon = trim( sanitize_text_field( (string) $icon ) );
		if ( '' === $icon ) {
			$icon = 'fa-solid fa-link';
		}

		if ( preg_match( '/\bfa[srb]?\b|fontawesome/i', $icon ) ) {
			return sprintf( '<i class="%s" aria-hidden="true"></i>', esc_attr( $icon ) );
		}

		if ( preg_match( '/^dashicons-/', $icon ) ) {
			$icon = 'dashicons ' . $icon;
		} elseif ( ! preg_match( '/^dashicons\s/', $icon ) ) {
			$icon = 'dashicons dashicons-' . ltrim( $icon, '-' );
		}

		return sprintf( '<span class="%s" aria-hidden="true"></span>', esc_attr( $icon ) );
	}
}
