<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
 * Dynamic render for bw/library-search.
 *
 * A plain GET form whose action is an EXTERNAL catalogue URL (EBSCO Research by
 * default). On submit the browser navigates to <action>?<param>=<typed query>,
 * URL-encoding the value for free — no JavaScript involved, works without JS and
 * is keyboard/Enter accessible by construction.
 *
 * If the configured action URL already carries its own query string (e.g.
 * ".../results?profile=foo"), those pairs are preserved as hidden inputs and the
 * form action is reduced to the path, so the GET form doesn't drop them.
 *
 * @var array $attributes
 */

$action_raw = isset( $attributes['actionUrl'] ) ? trim( (string) $attributes['actionUrl'] ) : '';
$param      = isset( $attributes['paramName'] ) ? trim( (string) $attributes['paramName'] ) : 'q';
if ( '' === $param ) { $param = 'q'; }

$placeholder = isset( $attributes['placeholder'] ) ? (string) $attributes['placeholder'] : '';
$button      = isset( $attributes['buttonText'] ) ? (string) $attributes['buttonText'] : '';
if ( '' === trim( $button ) ) { $button = __( 'Search', 'kadence-child' ); }
$new_tab  = ! empty( $attributes['newTab'] );
$full     = ! isset( $attributes['fullWidth'] ) || ! empty( $attributes['fullWidth'] );

$accent = isset( $attributes['accentColor'] ) ? sanitize_hex_color( $attributes['accentColor'] ) : '';
if ( ! $accent ) { $accent = '#cc0000'; }

// Heading + link labels come from inline RichText, so they're stored as
// entity-encoded HTML (e.g. "&amp;"). Render them through wp_kses with a tiny
// inline allow-list (never esc_html — that would double-encode the entities).
$inline_allowed = array(
	'strong' => array(), 'b' => array(),
	'em'     => array(), 'i' => array(),
	'br'     => array(),
);
$has_text = static function ( $s ) {
	return '' !== trim( wp_strip_all_tags( (string) $s ) );
};

// Secondary links shown under the box (Advanced Search / Browse Databases).
// Each is optional: a link only renders if it has both a label and a valid
// http(s) URL. The whole row is gated by showLinks.
$show_links = ! isset( $attributes['showLinks'] ) || ! empty( $attributes['showLinks'] );
$site_host  = wp_parse_url( home_url(), PHP_URL_HOST );
$links      = array();
if ( $show_links && ! empty( $attributes['links'] ) && is_array( $attributes['links'] ) ) {
	foreach ( $attributes['links'] as $item ) {
		if ( ! is_array( $item ) ) {
			continue;
		}
		$ltext = (string) ( $item['label'] ?? '' );
		// Allow http(s) AND site-relative links (e.g. /library/databases).
		$lurl  = esc_url_raw( trim( (string) ( $item['url'] ?? '' ) ), array( 'http', 'https' ) );
		if ( ! $has_text( $ltext ) || '' === $lurl ) {
			continue;
		}
		// A link opens in a new tab only when it's external (absolute, different
		// host) and "open in new tab" is on. Internal/relative links stay put.
		$lhost    = wp_parse_url( $lurl, PHP_URL_HOST );
		$external = $lhost && $lhost !== $site_host;
		$links[]  = array(
			'label'  => $ltext,
			'url'    => $lurl,
			'target' => ( $new_tab && $external ) ? ' target="_blank" rel="noopener"' : '',
		);
	}
}

// Only allow http(s) external destinations; bail out cleanly otherwise so the
// block never renders a form that posts somewhere unexpected.
$action = esc_url_raw( $action_raw, array( 'http', 'https' ) );
if ( '' === $action ) {
	if ( current_user_can( 'edit_posts' ) ) {
		return '<p class="bw-ls__notice">' . esc_html__( 'Library Search: set a valid destination URL in the block sidebar.', 'kadence-child' ) . '</p>';
	}
	return '';
}

// Split any pre-existing query string off the action into hidden inputs so a GET
// form (which replaces the query string) doesn't lose them.
$hidden  = array();
$qpos    = strpos( $action, '?' );
if ( false !== $qpos ) {
	$query  = substr( $action, $qpos + 1 );
	$action = substr( $action, 0, $qpos );
	parse_str( $query, $existing );
	if ( is_array( $existing ) ) {
		foreach ( $existing as $k => $v ) {
			if ( $k === $param || is_array( $v ) ) { continue; }
			$hidden[ (string) $k ] = (string) $v;
		}
	}
}

$uid = wp_unique_id( 'bw-ls-' );

$wrapper = get_block_wrapper_attributes(
	array(
		'class' => 'bw-ls' . ( $full ? ' bw-ls--full' : '' ),
		'style' => '--bw-ls-accent:' . esc_attr( $accent ) . ';',
	)
);

$target = $new_tab ? ' target="_blank" rel="noopener"' : '';

ob_start();
?>
<div <?php echo $wrapper; // phpcs:ignore WordPress.Security.EscapeOutput ?>>
	<form class="bw-ls__form" role="search" method="get" action="<?php echo esc_url( $action ); ?>"<?php echo $target; // phpcs:ignore WordPress.Security.EscapeOutput ?>>
		<?php // The visible heading is added manually above the block; keep an
		// accessible name on the input for screen readers. ?>
		<label class="screen-reader-text" for="<?php echo esc_attr( $uid ); ?>"><?php echo esc_html( $button ); ?></label>
		<div class="bw-ls__row">
			<input
				type="search"
				id="<?php echo esc_attr( $uid ); ?>"
				class="bw-ls__input"
				name="<?php echo esc_attr( $param ); ?>"
				placeholder="<?php echo esc_attr( $placeholder ); ?>"
				autocomplete="off"
			/>
			<?php foreach ( $hidden as $hk => $hv ) : ?>
				<input type="hidden" name="<?php echo esc_attr( $hk ); ?>" value="<?php echo esc_attr( $hv ); ?>" />
			<?php endforeach; ?>
			<button type="submit" class="bw-ls__button"><?php echo esc_html( $button ); ?></button>
		</div>
	</form>
	<?php if ( ! empty( $links ) ) : ?>
		<div class="bw-ls__links">
			<?php foreach ( $links as $lk ) : ?>
				<a class="bw-ls__link" href="<?php echo esc_url( $lk['url'] ); ?>"<?php echo $lk['target']; // phpcs:ignore WordPress.Security.EscapeOutput ?>><?php echo wp_kses( $lk['label'], $inline_allowed ); // phpcs:ignore WordPress.Security.EscapeOutput ?></a>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>
</div>
<?php
echo ob_get_clean(); // phpcs:ignore WordPress.Security.EscapeOutput
