<?php
/**
 * Warranty Selector Template
 *
 * @package WarrantyCart
 * @version 1.0.0
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables are local scope and don't need prefixing

$main_warranties = $args['main_warranties'] ?? array();
$services        = $args['services'] ?? array();
$layout          = $args['layout'] ?? 'grid';

/**
 * Filter warranty selector arguments
 *
 * @param array $args Template arguments.
 */
$args = \apply_filters( 'warranty_cart_selector_args', $args );

/*
 * Tags allowed in a price.
 *
 * The four prices below were run through `wp_kses_post()`, which does not allow
 * `<bdi>` — the element WooCommerce wraps every amount in so a price and its
 * currency symbol keep their order inside right-to-left text. It was stripped
 * from every price the selector renders, so an Arabic or Hebrew store showed
 * them reversed.
 */

/*
 * A note where the price shown is not the price that will be charged.
 *
 * A percentage warranty has no product to take a percentage of on this page, so
 * it falls back to the fixed price the shop set. Showing only that number would
 * quote a customer £29 for cover that will cost £200 against the television
 * they actually buy.
 */
if ( ! function_exists( 'warranty_cart_price_note' ) ) {
	/**
	 * Print the pricing rule beneath a price, when there is one to explain.
	 *
	 * @param WC_Product $warranty_product The warranty product.
	 *
	 * @return void
	 */
	function warranty_cart_price_note( $warranty_product ) {
		$note = \WarrantyCart\Core\Pricing::describe( $warranty_product );

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

		printf( '<small class="product-price__note">%s</small>', \esc_html( $note ) );
	}
}

if ( ! function_exists( 'warranty_cart_plan_image' ) ) {
	/**
	 * A plan's thumbnail, or nothing.
	 *
	 * Written once and used by both layouts. The grid had its own copy of this
	 * and the list had none at all, so a shop that gave its plans pictures saw
	 * them in one layout and not the other.
	 *
	 * `woocommerce_gallery_thumbnail` rather than `woocommerce_thumbnail`: the
	 * latter is the catalogue size, several hundred pixels square, and it was
	 * being set to `width: 100%` — so a square image filled the card's whole
	 * width and pushed the plan's name, price and terms below the fold of its
	 * own card. This is a thumbnail beside a name, and asking for the smaller
	 * file is the difference between a 12KB request and a 200KB one per plan.
	 *
	 * Returns '' when there is no image, so nothing reserves space for one —
	 * most shops sell cover without pictures.
	 *
	 * @param WC_Product $warranty_product The warranty product.
	 *
	 * @return string Markup, or ''.
	 */
	function warranty_cart_plan_image( $warranty_product ) {
		if ( ! $warranty_product instanceof WC_Product || ! $warranty_product->get_image_id() ) {
			return '';
		}

		$image = \wp_get_attachment_image(
			$warranty_product->get_image_id(),
			'woocommerce_gallery_thumbnail',
			false,
			array(
				'class'   => 'product-image',
				// Decorative: the plan's name is right beside it, and a screen
				// reader repeating it as alt text is noise.
				'alt'     => '',
				'loading' => 'lazy',
			)
		);

		return $image ? '<div class="product-media">' . $image . '</div>' : '';
	}
}

$warranty_price_tags = array(
	'span' => array(
		'class'     => true,
		'translate' => true,
	),
	'bdi'  => array(),
	'del'  => array(),
	'ins'  => array(),
);
?>

<div id="warranty-selector" class="warranty-selector warranty-layout-<?php echo \esc_attr( $layout ); ?>">
	<?php
	/**
	 * Action before warranty selector content
	 *
	 * @param array $main_warranties Main warranty products.
	 * @param array $services Additional services.
	 * @param string $layout Layout type.
	 */
	\do_action( 'warranty_cart_before_selector_content', $main_warranties, $services, $layout );
	?>

	<?php
	/*
	 * Where the selector talks to the customer.
	 *
	 * The script announced every failure through `wc_add_notice()` on
	 * `window` -- but that is a PHP function, so the branch was never taken
	 * and every message, including "Please select a main warranty", went to
	 * the browser console. Pressing the button with nothing selected appeared
	 * to do nothing at all.
	 *
	 * `role="status"` rather than `role="alert"`: the region exists on first
	 * paint, and an alert region that is present but empty is announced by
	 * some screen readers as soon as anything is written to it *and* on load.
	 */
	?>
	<div class="warranty-notice" id="warranty-notice" role="status" aria-live="polite" hidden></div>

	<?php if ( 'grid' === $layout ) : ?>
		<div class="warranty-grid">
			<?php if ( ! empty( $main_warranties ) ) : ?>
				<div class="warranty-section warranty-main-section">
					<h3 class="section-title" id="warranty-main-title"><?php \esc_html_e( 'Select Main Warranty', 'warranty-cart' ); ?></h3>
					<div class="products-grid" role="radiogroup" aria-labelledby="warranty-main-title">
						<?php
						foreach ( $main_warranties as $product ) :
							?>
							<div class="product-card warranty-card" data-product-id="<?php echo \esc_attr( $product->get_id() ); ?>" data-price="<?php echo \esc_attr( $product->get_price() ); ?>">
								<div class="product-main">
									<?php
									/*
									 * The plan's own image, beside its name.
									 *
									 * A warranty is an abstract thing and a
									 * picture is how a shop makes one feel
									 * concrete — a shield, a badge, a photo of an
									 * engineer. Left out, every plan on the page
									 * looks identical except for its price, which
									 * is the one axis a customer should not be
									 * choosing on alone.
									 *
									 * A thumbnail beside the name, not a banner
									 * above it. It was `woocommerce_thumbnail` at
									 * `width: 100%`, so a square image filled the
									 * card's whole width — on a three-column grid
									 * that is a picture some 300px tall carrying
									 * a plan whose name, price and terms then sat
									 * below the fold of the card. A plan is a line
									 * on a menu, not a product hero.
									 */
									echo \wp_kses_post( warranty_cart_plan_image( $product ) );
									?>

									<div class="product-body">
										<div class="product-header">
											<h4><?php echo \esc_html( $product->get_name() ); ?></h4>
											<span class="product-price"><?php echo \wp_kses( \wc_price( $product->get_price() ), $warranty_price_tags ); ?><?php warranty_cart_price_note( $product ); ?></span>
										</div>
										<div class="product-description">
											<?php echo \wp_kses_post( \wp_trim_words( $product->get_short_description() ? $product->get_short_description() : $product->get_description(), 20 ) ); ?>
										</div>
									</div>
								</div>
								<label class="product-selector">
									<input type="radio" name="main_warranty" value="<?php echo \esc_attr( $product->get_id() ); ?>">
									<span class="checkmark"></span>
									<?php \esc_html_e( 'Select this warranty', 'warranty-cart' ); ?>
								</label>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $services ) ) : ?>
				<div class="warranty-section warranty-services-section">
					<h3 class="section-title"><?php \esc_html_e( 'Add Associated Services', 'warranty-cart' ); ?></h3>
					<div class="products-grid">
						<?php
						foreach ( $services as $product ) :
							?>
							<div class="product-card service-card" data-product-id="<?php echo \esc_attr( $product->get_id() ); ?>" data-price="<?php echo \esc_attr( $product->get_price() ); ?>">
								<div class="product-main">
									<?php echo \wp_kses_post( warranty_cart_plan_image( $product ) ); ?>

									<div class="product-body">
										<div class="product-header">
											<h4><?php echo \esc_html( $product->get_name() ); ?></h4>
											<span class="product-price"><?php echo \wp_kses( '+ ' . \wc_price( $product->get_price() ), $warranty_price_tags ); ?></span>
										</div>
										<div class="product-description">
											<?php echo \wp_kses_post( \wp_trim_words( $product->get_short_description() ? $product->get_short_description() : $product->get_description(), 15 ) ); ?>
										</div>
									</div>
								</div>
								<label class="product-selector">
									<input type="checkbox" name="services[]" value="<?php echo \esc_attr( $product->get_id() ); ?>">
									<span class="checkmark"></span>
									<?php \esc_html_e( 'Add this service', 'warranty-cart' ); ?>
								</label>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>
		</div>
	<?php else : // List layout ?>
		<div class="warranty-list">
			<?php if ( ! empty( $main_warranties ) ) : ?>
				<div class="warranty-section warranty-main-section">
					<h3 class="section-title" id="warranty-main-title"><?php \esc_html_e( 'Select Main Warranty', 'warranty-cart' ); ?></h3>
					<div class="products-list" role="radiogroup" aria-labelledby="warranty-main-title">
						<?php
						foreach ( $main_warranties as $product ) :
							?>
							<div class="product-item warranty-item" data-product-id="<?php echo \esc_attr( $product->get_id() ); ?>" data-price="<?php echo \esc_attr( $product->get_price() ); ?>">
								<?php echo \wp_kses_post( warranty_cart_plan_image( $product ) ); ?>
								<div class="product-info">
									<h4><?php echo \esc_html( $product->get_name() ); ?></h4>
									<div class="product-description">
										<?php echo \wp_kses_post( \wp_trim_words( $product->get_short_description() ? $product->get_short_description() : $product->get_description(), 30 ) ); ?>
									</div>
								</div>
								<div class="product-price"><?php echo \wp_kses( \wc_price( $product->get_price() ), $warranty_price_tags ); ?><?php warranty_cart_price_note( $product ); ?></div>
								<label class="product-selector">
									<input type="radio" name="main_warranty" value="<?php echo \esc_attr( $product->get_id() ); ?>">
									<span class="checkmark"></span>
									<span class="screen-reader-text">
										<?php
										/* translators: %s: warranty product name. */
										printf( \esc_html__( 'Select %s', 'warranty-cart' ), \esc_html( $product->get_name() ) );
										?>
									</span>
								</label>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $services ) ) : ?>
				<div class="warranty-section warranty-services-section">
					<h3 class="section-title"><?php \esc_html_e( 'Add Associated Services', 'warranty-cart' ); ?></h3>
					<div class="products-list">
						<?php
						foreach ( $services as $product ) :
							?>
							<div class="product-item service-item" data-product-id="<?php echo \esc_attr( $product->get_id() ); ?>" data-price="<?php echo \esc_attr( $product->get_price() ); ?>">
								<?php echo \wp_kses_post( warranty_cart_plan_image( $product ) ); ?>
								<div class="product-info">
									<h4><?php echo \esc_html( $product->get_name() ); ?></h4>
									<div class="product-description">
										<?php echo \wp_kses_post( \wp_trim_words( $product->get_short_description() ? $product->get_short_description() : $product->get_description(), 25 ) ); ?>
									</div>
								</div>
								<div class="product-price"><?php echo \wp_kses( '+ ' . \wc_price( $product->get_price() ), $warranty_price_tags ); ?></div>
								<label class="product-selector">
									<input type="checkbox" name="services[]" value="<?php echo \esc_attr( $product->get_id() ); ?>">
									<span class="checkmark"></span>
									<span class="screen-reader-text">
										<?php
										/* translators: %s: service product name. */
										printf( \esc_html__( 'Add %s', 'warranty-cart' ), \esc_html( $product->get_name() ) );
										?>
									</span>
								</label>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>
		</div>
	<?php endif; ?>

	<div class="warranty-summary">
		<div class="total-price">
			<span class="total-label"><?php \esc_html_e( 'Total:', 'warranty-cart' ); ?></span>
			<span class="total-amount"><?php echo \wp_kses_post( \wc_price( 0 ) ); ?></span>
		</div>
		<div class="selected-items" style="display: none;">
			<h4><?php \esc_html_e( 'Selected Items:', 'warranty-cart' ); ?></h4>
			<ul id="selected-items-list"></ul>
		</div>
		<button id="add-to-cart-btn" class="button alt warranty-add-to-cart" disabled>
			<?php \esc_html_e( 'Add to Cart & Checkout', 'warranty-cart' ); ?>
		</button>
	</div>

	<?php
	/**
	 * Action after warranty selector content
	 *
	 * @param array $main_warranties Main warranty products.
	 * @param array $services Additional services.
	 * @param string $layout Layout type.
	 */
	\do_action( 'warranty_cart_after_selector_content', $main_warranties, $services, $layout );
	?>
</div>
<?php // phpcs:enable ?>