<?php
/**
 * File Path: includes/helpers/class-mbs-buy-link-row-renderer.php
 *
 * Shared Buy Link Row Renderer — renders a single buy link row for both the
 * global buy link repeater and the per-format buy link repeater.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Buy_Link_Row_Renderer { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Render a single buy link row.
	 *
	 * Used by MBS_Metabox_Buy_Links::render_row() (global) and
	 * MBS_Metabox_Format_Repeater_Render::render_row_buy_links() (per-format).
	 *
	 * @param object|null $link              Row data, or null for a hidden template row.
	 * @param array       $field_names       Associative array keyed by:
	 *                                       id, retailer_key, icon_id, label, url, embed.
	 * @param bool        $is_pro            Whether PRO tier is active.
	 * @param bool        $is_pub            Whether PUB tier is active.
	 * @param bool        $show_sort_controls Emit drag handle + arrow fallback spans. Default true.
	 * @return void
	 */
	public static function render_row(
		?object $link,
		array $field_names,
		bool $is_pro = false,
		bool $is_pub = false,
		bool $show_sort_controls = true
	): void {
		$retailers_url = MBS_ASSETS_URL . 'images/retailers/';
		$is_template   = ( null === $link );
		$disabled      = $is_template ? ' disabled="disabled"' : '';

		// Pre-compute all row values so no null-dereference occurs in HTML section.
		$retailer_key   = $is_template ? '' : sanitize_key( $link->retailer_key ?? '' );
		$icon_att_id    = $is_template ? 0 : (int) ( $link->icon_attachment_id ?? 0 );
		$saved_id       = $is_template ? '' : ( $link->id ?? '' );
		$saved_icon_id  = $is_template ? '' : ( $link->icon_attachment_id ?: '' );
		$saved_label    = $is_template ? '' : sanitize_text_field( $link->link_label ?? '' );
		$saved_url      = $is_template ? '' : ( $link->url ?? '' );
		$saved_embed    = $is_template ? '' : ( $link->embed ?? '' );

		// Icon resolution chain: attachment ID > retailer key > site icon (A4-003).
		if ( $icon_att_id > 0 ) {
			$img_src = wp_get_attachment_image_url( $icon_att_id, array( 24, 24 ) ) ?: ''; // R5-exempt: buy-link row admin context
		} elseif ( $retailer_key ) {
			$img_src = MBS_Link_Icon_Helper::resolve_icon_src( $retailer_key, $retailers_url );
		} else {
			$img_src = MBS_Link_Icon_Helper::get_site_icon_url( 32 );
		}

		$label_placeholder = MBS_Link_Icon_Helper::get_label( $retailer_key );

		?>
		<div class="mbs-buy-link-row" style="display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px;">
		<?php

		if ( $show_sort_controls ) :
			if ( $is_pro ) : ?>
		<span class="mbs-drag-handle dashicons dashicons-menu"
		      title="<?php esc_attr_e( 'Drag to reorder', 'my-book-showroom' ); ?>"
		      aria-hidden="true"></span>
			<?php endif; ?>
		<span class="mbs-buy-link-fallback">
			<button type="button" class="button-link mbs-reorder-move-up"
			        aria-label="<?php esc_attr_e( 'Move up', 'my-book-showroom' ); ?>"
			        title="<?php esc_attr_e( 'Move up', 'my-book-showroom' ); ?>">
				<span class="dashicons dashicons-arrow-up-alt2" aria-hidden="true"></span>
			</button>
			<button type="button" class="button-link mbs-reorder-move-down"
			        aria-label="<?php esc_attr_e( 'Move down', 'my-book-showroom' ); ?>"
			        title="<?php esc_attr_e( 'Move down', 'my-book-showroom' ); ?>">
				<span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
			</button>
		</span>
		<?php
		endif;

		// Hidden ID.
		?>
		<input type="hidden"
		       name="<?php echo esc_attr( $field_names['id'] ); ?>"
		       value="<?php echo esc_attr( $saved_id ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>

		<!-- Hidden retailer key — JS reads/writes this to track detected key. -->
		<input type="hidden"
		       name="<?php echo esc_attr( $field_names['retailer_key'] ); ?>"
		       class="mbs-buy-link-retailer-key"
		       value="<?php echo esc_attr( $retailer_key ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>

		<!-- Hidden icon attachment ID — JS icon-picker updates this. -->
		<input type="hidden"
		       name="<?php echo esc_attr( $field_names['icon_id'] ); ?>"
		       class="mbs-buy-link-icon-id"
		       value="<?php echo esc_attr( $saved_icon_id ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>

		<input type="text"
		       name="<?php echo esc_attr( $field_names['label'] ); ?>"
		       class="mbs-buy-link-label"
		       value="<?php echo esc_attr( $saved_label ); ?>"
		       placeholder="<?php echo esc_attr( $label_placeholder ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>

		<input type="url"
		       name="<?php echo esc_attr( $field_names['url'] ); ?>"
		       class="mbs-buy-link-url"
		       value="<?php echo esc_url( $saved_url ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>

		<div class="mbs-buy-link-icon-wrap">
			<?php if ( $img_src ) : ?>
				<img class="mbs-buy-link-icon-preview"
				     src="<?php echo esc_url( $img_src ); ?>"
				     alt="" width="24" height="24">
			<?php else : ?>
				<span class="mbs-buy-link-icon-placeholder"></span>
			<?php endif; ?>
			<?php if ( ( $is_pro || $is_pub ) && ( ! $retailer_key || '' === $img_src ) ) : // Show picker when no key (custom link) OR key exists but no icon asset found ?>
				<button type="button"
				        class="button button-small mbs-change-icon-btn"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>
					<?php esc_html_e( 'Change Icon', 'my-book-showroom' ); ?>
				</button>
			<?php elseif ( ! $is_pro && ! $is_pub ) : ?>
				<!-- MBS: custom icon upload requires PRO license -->
			<?php endif; ?>
		</div>

		<?php if ( $is_template || 'shopify-buy' === $retailer_key ) : ?>
		<textarea name="<?php echo esc_attr( $field_names['embed'] ); ?>"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>><?php echo esc_textarea( $saved_embed ); ?></textarea>
		<?php else : ?>
		<input type="hidden"
		       name="<?php echo esc_attr( $field_names['embed'] ); ?>"
		       value=""<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>
		<?php endif; ?>

		<button type="button" class="button mbs-remove-buy-link-row"<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $disabled is a pre-constructed HTML attribute, contains no user input ?>>
			<?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
		</button>

		</div><!-- /.mbs-buy-link-row -->
		<?php
	}
}
