<?php

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

if ( ! class_exists( 'AIEO_Trust_Badges_Block' ) ) :

class AIEO_Trust_Badges_Block {

	const BLOCK_NAME = 'aieo/trust-badges';
	const ICON_SLUGS = array( 'shipping', 'payment', 'returns', 'quality' );

	public function __construct() {
		add_action( 'init', array( $this, 'register_block' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
	}

	
	public static function default_items() {
		return array(
			array( 'icon' => 'shipping', 'iconUrl' => '', 'title' => 'Free shipping',  'subtitle' => 'On orders over 40€' ),
			array( 'icon' => 'payment',  'iconUrl' => '', 'title' => 'Secure payment', 'subtitle' => 'Visa, mastercard, paypal' ),
			array( 'icon' => 'returns',  'iconUrl' => '', 'title' => 'Returns',        'subtitle' => 'Within 15 days' ),
			array( 'icon' => 'quality',  'iconUrl' => '', 'title' => 'Top quality',    'subtitle' => 'Hand-picked products our experts trust' ),
		);
	}

	
	public static function icon_svg( $slug ) {
		static $cache = array();
		$slug = sanitize_key( (string) $slug );
		if ( isset( $cache[ $slug ] ) ) { return $cache[ $slug ]; }
		if ( ! in_array( $slug, self::ICON_SLUGS, true ) ) { return $cache[ $slug ] = ''; }
		
		$path = dirname( __DIR__ ) . '/assets/icons/trust-' . $slug . '.svg';
		return $cache[ $slug ] = is_readable( $path ) ? (string) file_get_contents( $path ) : '';
	}

	public function enqueue_block_editor_assets() {
		$h = 'aieo-trust-badges-editor';
		if ( wp_script_is( $h, 'registered' ) ) { wp_enqueue_script( $h ); }
	}

	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) { return; }
		if ( class_exists( 'WP_Block_Type_Registry' ) && WP_Block_Type_Registry::get_instance()->is_registered( self::BLOCK_NAME ) ) { return; }

		$handle = 'aieo-trust-badges-editor';
		$rel    = 'assets/js/aieo-trust-badges-editor.js';
		$path   = defined( 'AIEO_DIR' ) ? AIEO_DIR . $rel : dirname( __DIR__ ) . '/' . $rel;
		$url    = plugins_url( $rel, dirname( __DIR__ ) . '/ai-eshop-optimizer.php' );
		if ( defined( 'AIEO_FILE' ) ) { $url = plugins_url( $rel, AIEO_FILE ); }
		$ver    = file_exists( $path ) ? filemtime( $path ) : ( defined( 'AIEO_VERSION' ) ? AIEO_VERSION : false );

		if ( file_exists( $path ) ) {
			wp_register_script( $handle, $url, array( 'wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-i18n' ), $ver, true );
			
			$icons = array();
			foreach ( self::ICON_SLUGS as $s ) { $icons[ $s ] = self::icon_svg( $s ); }
			wp_localize_script( $handle, 'aieoTrustBadgesConfig', array(
				'slugs'        => self::ICON_SLUGS,
				'icons'        => $icons,
				'defaultItems' => self::default_items(),
			) );
		}

		register_block_type( self::BLOCK_NAME, array(
			'api_version'     => 3,
			'title'           => __( 'AIEO Trust Badges', 'ai-eshop-optimizer' ),
			'category'        => 'theme',
			'icon'            => 'awards',
			'description'     => __( 'A trust strip of icon + title + subtitle columns (shipping, payment, returns, quality…).', 'ai-eshop-optimizer' ),
			'keywords'        => array( 'trust', 'badges', 'features', 'usp', 'shipping', 'aieo' ),
			'attributes'      => array(
				'items'        => array( 'type' => 'array',   'default' => self::default_items() ),
				'align'        => array( 'type' => 'string',  'default' => '' ),
				'gap'          => array( 'type' => 'string',  'default' => '24px' ),
				'divider'      => array( 'type' => 'boolean', 'default' => true ),
				'dividerColor' => array( 'type' => 'string',  'default' => '#000000' ),
				'dividerWidth' => array( 'type' => 'string',  'default' => '1px' ),
			),
			'supports'        => array(
				'align'   => array( 'wide', 'full' ),
				'spacing' => array( 'margin' => true, 'padding' => true ),
			),
			'editor_script'   => $handle,
			'render_callback' => array( $this, 'render_block' ),
		) );
	}

	public function render_block( $attrs = array() ) {
		$items = ( isset( $attrs['items'] ) && is_array( $attrs['items'] ) && $attrs['items'] ) ? $attrs['items'] : self::default_items();

		$tiles = '';
		foreach ( $items as $it ) {
			if ( ! is_array( $it ) ) { continue; }
			$title    = isset( $it['title'] ) ? (string) $it['title'] : '';
			$subtitle = isset( $it['subtitle'] ) ? (string) $it['subtitle'] : '';
			if ( '' === $title && '' === $subtitle ) { continue; }

			$icon_url  = isset( $it['iconUrl'] ) ? trim( (string) $it['iconUrl'] ) : '';
			$icon_slug = isset( $it['icon'] ) ? sanitize_key( (string) $it['icon'] ) : '';
			if ( '' !== $icon_url ) {
				$icon_inner = '<img src="' . esc_url( $icon_url ) . '" alt="" width="48" height="48" loading="lazy" />';
			} else {
				$icon_inner = self::icon_svg( $icon_slug );
			}
			$icon_html = $icon_inner
				? '<span class="roosterx-trust-tile__icon" aria-hidden="true" style="width:48px;height:48px;">' . $icon_inner . '</span>'
				: '<span class="roosterx-trust-tile__icon roosterx-trust-tile__icon--missing" aria-hidden="true" style="width:48px;height:48px;"></span>';

			$body = '';
			if ( '' !== $title )    { $body .= '<strong class="roosterx-trust-tile__title">' . esc_html( $title ) . '</strong>'; }
			if ( '' !== $subtitle ) { $body .= '<span class="roosterx-trust-tile__subtitle">' . esc_html( $subtitle ) . '</span>'; }

			$tiles .= '<div class="wp-block-column"><div class="roosterx-trust-tile aieo-trust-tile" data-roosterx="trust-tile">'
				. $icon_html . '<div class="roosterx-trust-tile__body">' . $body . '</div></div></div>';
		}

		if ( '' === $tiles ) { return ''; }

		$align = isset( $attrs['align'] ) ? sanitize_html_class( (string) $attrs['align'] ) : '';
		$align_cls = ( 'full' === $align ) ? ' alignfull' : ( ( 'wide' === $align ) ? ' alignwide' : '' );
		$gap = isset( $attrs['gap'] ) ? self::sanitize_len( (string) $attrs['gap'] ) : '24px';

		
		
		
		
		$divider   = ! isset( $attrs['divider'] ) || ! empty( $attrs['divider'] );
		$div_color = isset( $attrs['dividerColor'] ) ? ( sanitize_hex_color( (string) $attrs['dividerColor'] ) ?: '#000000' ) : '#000000';
		$div_width = isset( $attrs['dividerWidth'] ) ? self::sanitize_len( (string) $attrs['dividerWidth'] ) : '1px';

		
		
		
		
		
		
		
		static $css_done = false;
		$css = '';
		if ( ! $css_done ) {
			$css_done = true;
			$css = '<style id="aieo-trust-badges-css">'
				. '.aieo-trust-strip{margin-left:auto;margin-right:auto;width:100%;box-sizing:border-box}'
				. '.aieo-trust-strip:not(.alignwide):not(.alignfull){max-width:var(--wp--style--global--content-size,1100px)}'
				. '.aieo-trust-strip.alignwide{max-width:var(--wp--style--global--wide-size,1350px)}'
				. '.aieo-trust-strip.alignfull{max-width:none}'
				. '.aieo-trust-strip .aieo-trust-cols{display:flex;flex-wrap:nowrap;align-items:flex-start}'
				. '.aieo-trust-strip .aieo-trust-cols>.wp-block-column{flex:1 1 0;min-width:0;margin:0}'
				. '.aieo-trust-strip[data-divider="1"] .aieo-trust-cols{align-items:stretch}'
				. '.aieo-trust-strip[data-divider="1"] .aieo-trust-cols>.wp-block-column{position:relative}'
				. '.aieo-trust-strip[data-divider="1"] .aieo-trust-cols>.wp-block-column:not(:first-child)::before{content:"";position:absolute;top:0;bottom:0;left:calc(var(--aieo-tb-gap,24px) / -2);width:var(--aieo-tb-divider-w,1px);background:var(--aieo-tb-divider-c,#000000)}'
				. '@media(max-width:781px){.aieo-trust-strip .aieo-trust-cols{flex-wrap:wrap;flex-direction:column}.aieo-trust-strip .aieo-trust-cols>.wp-block-column{flex:1 1 100%}.aieo-trust-strip[data-divider="1"] .aieo-trust-cols>.wp-block-column:not(:first-child)::before{display:none}}'
				. '</style>';
		}

		
		$wrap_style = 'padding-top:var(--wp--preset--spacing--6);padding-bottom:var(--wp--preset--spacing--6)';
		if ( $divider ) {
			$wrap_style .= ';--aieo-tb-gap:' . $gap . ';--aieo-tb-divider-c:' . $div_color . ';--aieo-tb-divider-w:' . $div_width;
		}

		return $css . '<div class="wp-block-group aieo-trust-strip ff-trust-strip' . esc_attr( $align_cls ) . '"'
			. ' data-divider="' . ( $divider ? '1' : '0' ) . '"'
			. ' style="' . esc_attr( $wrap_style ) . '">'
			. '<div class="wp-block-columns aieo-trust-cols' . esc_attr( $align_cls ) . '" style="gap:' . esc_attr( $gap ) . '">' . $tiles . '</div></div>';
	}

	
	private static function sanitize_len( $v ) {
		$v = trim( (string) $v );
		return preg_match( '/^[0-9]{1,4}(\.[0-9]{1,2})?(px|rem|em|%|vw)?$/', $v ) ? $v : '24px';
	}
}

new AIEO_Trust_Badges_Block();

endif;
