<?php
/**
 * BW Dev — Separator block. Server-side render.
 *
 * @var array    $attributes
 * @var string   $content
 * @var WP_Block $block
 */

defined( 'ABSPATH' ) || exit;

$align        = isset( $attributes['align'] ) ? strtolower( (string) $attributes['align'] ) : 'center';
$symbol_type  = isset( $attributes['symbolType'] ) ? (string) $attributes['symbolType'] : 'predefined';
$symbol       = isset( $attributes['symbol'] ) ? (string) $attributes['symbol'] : '✦';
$svg_id       = isset( $attributes['svgId'] ) ? (int) $attributes['svgId'] : 0;
$svg_url_attr = isset( $attributes['svgUrl'] ) ? trim( (string) $attributes['svgUrl'] ) : '';
$color        = isset( $attributes['color'] ) ? trim( (string) $attributes['color'] ) : '';

if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
	$align = 'center';
}

$allowed_symbols = array( '✦', '✧', '◆', '◇', '★', '☆', '•', '◉', '❖', '✿', '❀', '⬥', '⬦' );
if ( ! in_array( $symbol, $allowed_symbols, true ) ) {
	$symbol = '✦';
}

$color_clean = sanitize_hex_color( $color );

// Resolve SVG URL: prefer the persisted URL (saved at edit time); re-resolve
// from the attachment ID if missing (covers attachments that moved).
$svg_url = '';
if ( 'svg' === $symbol_type ) {
	if ( '' !== $svg_url_attr ) {
		$svg_url = $svg_url_attr;
	} elseif ( $svg_id > 0 ) {
		$resolved = wp_get_attachment_url( $svg_id );
		if ( is_string( $resolved ) ) {
			$svg_url = $resolved;
		}
	}
	// Confirm it's actually an SVG; if not, fall back to the predefined glyph.
	if ( '' !== $svg_url ) {
		$path = wp_parse_url( $svg_url, PHP_URL_PATH );
		if ( ! is_string( $path ) || 'svg' !== strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ) ) {
			$svg_url = '';
		}
	}
}

$wrapper_classes = 'bw-dev-separator bw-dev-separator--' . $align;
$wrapper_style   = $color_clean ? 'color:' . esc_attr( $color_clean ) . ';' : '';
$wrapper_attrs   = get_block_wrapper_attributes(
	array_filter(
		array(
			'class' => $wrapper_classes,
			'style' => $wrapper_style,
		)
	)
);

if ( 'svg' === $symbol_type && '' !== $svg_url ) {
	$symbol_html = sprintf(
		'<span class="bw-dev-separator__symbol bw-dev-separator__symbol--svg" style="--bw-dev-sep-svg: url(%s);"></span>',
		esc_url( $svg_url )
	);
} else {
	$symbol_html = '<span class="bw-dev-separator__symbol">' . esc_html( $symbol ) . '</span>';
}

printf(
	'<div %1$s><div class="bw-dev-separator__inner"><span class="bw-dev-separator__line"></span>%2$s<span class="bw-dev-separator__line"></span></div></div>',
	wp_kses_data( $wrapper_attrs ),
	$symbol_html // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already-escaped HTML built above.
);
