<?php
/**
 * My Account — Warranties
 *
 * @package WarrantyCart
 * @version 2.1.0
 */

use WarrantyCart\Core\Renewals;
use WarrantyCart\Frontend\MyAccount;

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

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

$warranties       = $args['warranties'] ?? array();
$claims           = $args['claims'] ?? array();
$claim_messages   = $args['claim_messages'] ?? array();
$claims_enabled   = $args['claims_enabled'] ?? false;
$statuses         = $args['statuses'] ?? array();
$renewals_enabled = $args['renewals_enabled'] ?? false;
$renewal_counts   = $args['renewal_counts'] ?? array();
$page             = (int) ( $args['page'] ?? 1 );
$pages            = (int) ( $args['pages'] ?? 0 );
$endpoint         = $args['endpoint'] ?? 'warranties';

/**
 * Before the warranties tab.
 *
 * The counterpart to `woocommerce_before_account_orders`. The tab had no hooks
 * at all, so a theme or a plugin could add nothing to it without replacing the
 * whole template.
 *
 * @param bool $has_warranties Whether the customer has any.
 */
\do_action( 'warranty_cart_before_account_warranties', ! empty( $warranties ) );

if ( empty( $warranties ) ) :
	?>
	<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
		<?php
		/*
		 * A way out of the empty state.
		 *
		 * WooCommerce's own empty Orders tab offers "Browse products", because
		 * a message with nothing to act on leaves the customer on a dead end.
		 * This said "You have no warranties yet." and stopped there.
		 */
		if ( \wc_get_page_permalink( 'shop' ) ) :
			?>
			<a class="woocommerce-Button button" href="<?php echo \esc_url( \wc_get_page_permalink( 'shop' ) ); ?>">
				<?php \esc_html_e( 'Browse products', 'warranty-cart' ); ?>
			</a>
			<?php
		endif;

		\esc_html_e( 'No warranties yet. Cover you buy will appear here.', 'warranty-cart' );
		?>
	</div>
	<?php
	/**
	 * After the warranties tab.
	 *
	 * @param bool $has_warranties Whether the customer has any.
	 */
	\do_action( 'warranty_cart_after_account_warranties', false );

	return;
endif;
?>

<div class="warranty-cart-account" id="warranty-cart-account">

	<?php /* Where the claim form reports success or failure. */ ?>
	<div class="warranty-notice" id="warranty-claim-notice" role="status" aria-live="polite" hidden></div>

	<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive warranty-cart-warranties">
		<thead>
			<?php
			/*
			 * `scope="col"`, which WooCommerce's own orders table sets and this
			 * did not. Without it a screen reader cannot associate a cell with
			 * its heading, and every row is read as a bare list of values.
			 */
			?>
			<tr>
				<th scope="col" class="warranty-cart-warranties__header-name"><span class="nobr"><?php \esc_html_e( 'Warranty', 'warranty-cart' ); ?></span></th>
				<th scope="col" class="warranty-cart-warranties__header-order"><span class="nobr"><?php \esc_html_e( 'Order', 'warranty-cart' ); ?></span></th>
				<th scope="col" class="warranty-cart-warranties__header-purchased"><span class="nobr"><?php \esc_html_e( 'Purchased', 'warranty-cart' ); ?></span></th>
				<th scope="col" class="warranty-cart-warranties__header-expires"><span class="nobr"><?php \esc_html_e( 'Expires', 'warranty-cart' ); ?></span></th>
				<th scope="col" class="warranty-cart-warranties__header-status"><span class="nobr"><?php \esc_html_e( 'Status', 'warranty-cart' ); ?></span></th>
				<?php if ( $claims_enabled ) : ?>
					<th scope="col" class="warranty-cart-warranties__header-claim"><span class="nobr"><?php \esc_html_e( 'Claim', 'warranty-cart' ); ?></span></th>
				<?php endif; ?>
				<?php if ( $renewals_enabled ) : ?>
					<th scope="col" class="warranty-cart-warranties__header-renew"><span class="nobr"><?php \esc_html_e( 'Renew', 'warranty-cart' ); ?></span></th>
				<?php endif; ?>
			</tr>
		</thead>
		<tbody>
			<?php
			foreach ( $warranties as $warranty ) :
				$product = \wc_get_product( (int) $warranty->product_id );

				/*
				 * A product can be deleted long after its warranty was sold. The
				 * row still describes a commitment the shop has made, so it is
				 * shown with the name unavailable rather than skipped.
				 */
				$name = $product ? $product->get_name() : \__( 'Warranty', 'warranty-cart' );

				$order     = \wc_get_order( (int) $warranty->order_id );
				$order_url = $order ? $order->get_view_order_url() : '';
				$is_active = 'active' === (string) $warranty->status;

				/*
				 * Whether the Renew button is offered for this row.
				 *
				 * Asked of the same code the endpoint asks, rather than
				 * re-deriving the window here — a button the server is going to
				 * refuse is worse than no button, and two copies of a date
				 * comparison drift apart.
				 */
				$can_renew = $renewals_enabled
					&& true === Renewals::can_renew( $warranty, \get_current_user_id() );
				?>
				<?php
				/*
				 * The status on the row, the way WooCommerce puts it on its
				 * orders table. A theme cannot tint an expired warranty's row
				 * without something to select on, and there was nothing.
				 */
				?>
				<tr class="warranty-cart-warranties__row warranty-cart-warranties__row--status-<?php echo \esc_attr( (string) $warranty->status ); ?>">
					<?php
					/*
					 * A `th scope="row"`, not a `td`. This is the cell that names
					 * the row, and marking it up as a heading is what lets a
					 * screen reader announce "Essential Protection, Expires,
					 * 14 August 2027" rather than reading six unlabelled values.
					 *
					 * The name is the link, the way an order number is on the
					 * Orders tab. A separate View column would be a fifth control
					 * on a row that already has Claim and Renew.
					 */
					?>
					<th scope="row" class="warranty-cart-warranties__cell-name" data-title="<?php \esc_attr_e( 'Warranty', 'warranty-cart' ); ?>">
						<?php
						$warranty_url = \wc_get_endpoint_url( MyAccount::ENDPOINT, (string) $warranty->id, \wc_get_page_permalink( 'myaccount' ) );

						$warranty_label = sprintf(
							/* translators: %s: the warranty's name. */
							\__( 'View %s', 'warranty-cart' ),
							$name
						);
						?>
						<a href="<?php echo \esc_url( $warranty_url ); ?>" aria-label="<?php echo \esc_attr( $warranty_label ); ?>">
							<?php echo \esc_html( $name ); ?>
						</a>
					</th>
					<td class="warranty-cart-warranties__cell-order" data-title="<?php \esc_attr_e( 'Order', 'warranty-cart' ); ?>">
						<?php
						// Cover issued by hand has no order; "#0" would name one
						// that does not exist. See the note in
						// my-account-warranty.php.
						?>
						<?php if ( ! (int) $warranty->order_id ) : ?>
							<?php \esc_html_e( 'Issued directly', 'warranty-cart' ); ?>
						<?php elseif ( $order_url ) : ?>
							<a href="<?php echo \esc_url( $order_url ); ?>">
								<?php echo \esc_html( sprintf( '#%d', (int) $warranty->order_id ) ); ?>
							</a>
						<?php else : ?>
							<?php echo \esc_html( sprintf( '#%d', (int) $warranty->order_id ) ); ?>
						<?php endif; ?>
					</td>
					<td class="warranty-cart-warranties__cell-purchased" data-title="<?php \esc_attr_e( 'Purchased', 'warranty-cart' ); ?>">
						<?php
						/*
						 * A <time datetime>, as WooCommerce's orders table uses.
						 * The visible text is formatted to the site's setting;
						 * the attribute is machine-readable, which is what a
						 * reader-mode, a browser extension or a scraper wants.
						 */
						$purchased_at = strtotime( (string) $warranty->purchase_date );
						?>
						<time datetime="<?php echo \esc_attr( \gmdate( 'c', (int) $purchased_at ) ); ?>">
							<?php echo \esc_html( \wp_date( \get_option( 'date_format' ), (int) $purchased_at ) ); ?>
						</time>
					</td>
					<td class="warranty-cart-warranties__cell-expires" data-title="<?php \esc_attr_e( 'Expires', 'warranty-cart' ); ?>">
						<?php $expires_at = strtotime( (string) $warranty->expiration_date ); ?>
						<time datetime="<?php echo \esc_attr( \gmdate( 'c', (int) $expires_at ) ); ?>">
							<?php echo \esc_html( \wp_date( \get_option( 'date_format' ), (int) $expires_at ) ); ?>
						</time>

						<?php
						/*
						 * A count, and a way to go and read it.
						 *
						 * The history itself used to open in a disclosure right
						 * here, which put a nested list inside a table cell on a
						 * screen that is already a table, and gave the row a
						 * variable height depending on how often somebody had
						 * renewed. The row says there is something to read; the
						 * warranty's own page is where it is read.
						 */
						$renewed = (int) ( $renewal_counts[ (int) $warranty->id ] ?? 0 );

						if ( $renewed > 0 ) :
							?>
							<span class="warranty-renewed-note">
								<?php
								echo \esc_html(
									sprintf(
										/* translators: %d: how many times this warranty has been renewed. */
										\_n( 'Renewed %d time', 'Renewed %d times', $renewed, 'warranty-cart' ),
										$renewed
									)
								);
								?>
							</span>
						<?php endif; ?>
					</td>
					<td class="warranty-cart-warranties__cell-status" data-title="<?php \esc_attr_e( 'Status', 'warranty-cart' ); ?>">
						<?php
						$warranty_statuses = array(
							'active'    => \__( 'Active', 'warranty-cart' ),
							'expired'   => \__( 'Expired', 'warranty-cart' ),
							'cancelled' => \__( 'Cancelled', 'warranty-cart' ),
							'pending'   => \__( 'Pending', 'warranty-cart' ),
						);

						$status = (string) $warranty->status;

						/*
						 * A word, even for a status nobody labelled.
						 *
						 * The fallback printed the raw slug, so an unlabelled
						 * status appeared in lower case beside properly
						 * capitalised ones — visible to the customer, and the
						 * sort of detail that reads as a half-finished plugin.
						 */
						echo \esc_html(
							$warranty_statuses[ $status ] ?? ucfirst( str_replace( '_', ' ', $status ) )
						);
						?>
					</td>
					<?php if ( $claims_enabled ) : ?>
						<td class="warranty-cart-warranties__cell-claim" data-title="<?php \esc_attr_e( 'Claim', 'warranty-cart' ); ?>">
							<?php
							/*
							 * Only an active warranty can be claimed against, and
							 * the server enforces that too. Showing a button that
							 * is going to be refused is worse than showing none.
							 */
							if ( $is_active ) :
								?>
								<button
									type="button"
									class="button warranty-claim-open"
									data-warranty="<?php echo \esc_attr( (string) $warranty->id ); ?>"
									data-name="<?php echo \esc_attr( $name ); ?>"
								>
									<?php \esc_html_e( 'File a claim', 'warranty-cart' ); ?>
								</button>
							<?php else : ?>
								<span class="warranty-claim-unavailable">&mdash;</span>
							<?php endif; ?>
						</td>
					<?php endif; ?>
					<?php if ( $renewals_enabled ) : ?>
						<td class="warranty-cart-warranties__cell-renew" data-title="<?php \esc_attr_e( 'Renew', 'warranty-cart' ); ?>">
							<?php if ( $can_renew ) : ?>
								<button
									type="button"
									class="button warranty-renew"
									data-warranty="<?php echo \esc_attr( (string) $warranty->id ); ?>"
								>
									<?php \esc_html_e( 'Renew', 'warranty-cart' ); ?>
								</button>
							<?php else : ?>
								<span class="warranty-renew-unavailable">&mdash;</span>
							<?php endif; ?>
						</td>
					<?php endif; ?>
				</tr>
			<?php endforeach; ?>
		</tbody>
	</table>

	<?php
	/*
	 * The same pager WooCommerce puts under its orders table, down to the class
	 * names, so a theme that has styled one has styled both. Previous/Next
	 * without numbers is WooCommerce's own choice here.
	 */
	if ( $pages > 1 ) :
		$account_url = \wc_get_page_permalink( 'myaccount' );
		?>
		<div class="woocommerce-pagination woocommerce-pagination--without-numbers woocommerce-Pagination">
			<?php if ( $page > 1 ) : ?>
				<a
					class="woocommerce-button woocommerce-button--previous woocommerce-Button woocommerce-Button--previous button"
					href="<?php echo \esc_url( \wc_get_endpoint_url( $endpoint, (string) ( $page - 1 ), $account_url ) ); ?>"
				>
					<?php \esc_html_e( 'Previous', 'warranty-cart' ); ?>
				</a>
			<?php endif; ?>

			<?php if ( $page < $pages ) : ?>
				<a
					class="woocommerce-button woocommerce-button--next woocommerce-Button woocommerce-Button--next button"
					href="<?php echo \esc_url( \wc_get_endpoint_url( $endpoint, (string) ( $page + 1 ), $account_url ) ); ?>"
				>
					<?php \esc_html_e( 'Next', 'warranty-cart' ); ?>
				</a>
			<?php endif; ?>
		</div>
	<?php endif; ?>

	<?php if ( $claims_enabled ) : ?>

		<?php
		/*
		 * The form lives in a partial: the single warranty page opens the same
		 * one, and two copies would mean two sets of field IDs for one handler.
		 */
		\wc_get_template(
			'frontend/my-account-claim-form.php',
			array(),
			'warranty-cart',
			WARRANTY_CART_PATH . 'templates/'
		);
		?>

		<h3 class="warranty-claims-title"><?php \esc_html_e( 'Your claims', 'warranty-cart' ); ?></h3>

		<?php if ( empty( $claims ) ) : ?>
			<p class="warranty-claims-empty">
				<?php \esc_html_e( 'You have not filed any claims.', 'warranty-cart' ); ?>
			</p>
		<?php else : ?>
			<table class="woocommerce-orders-table shop_table shop_table_responsive warranty-cart-claims" id="warranty-claims-table">
				<thead>
					<tr>
						<th><span class="nobr"><?php \esc_html_e( 'Claim', 'warranty-cart' ); ?></span></th>
						<th><span class="nobr"><?php \esc_html_e( 'Summary', 'warranty-cart' ); ?></span></th>
						<th><span class="nobr"><?php \esc_html_e( 'Filed', 'warranty-cart' ); ?></span></th>
						<th><span class="nobr"><?php \esc_html_e( 'Status', 'warranty-cart' ); ?></span></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $claims as $claim ) : ?>
						<tr>
							<td class="warranty-cart-warranties__cell-claim" data-title="<?php \esc_attr_e( 'Claim', 'warranty-cart' ); ?>">
								<?php echo \esc_html( sprintf( '#%d', (int) $claim->id ) ); ?>
							</td>
							<td data-title="<?php \esc_attr_e( 'Summary', 'warranty-cart' ); ?>">
								<?php echo \esc_html( (string) $claim->subject ); ?>

								<?php if ( ! empty( $claim->resolution ) ) : ?>
									<span class="warranty-claim-resolution">
										<?php echo \esc_html( (string) $claim->resolution ); ?>
									</span>
								<?php endif; ?>

								<?php
								/*
								 * What the shop has said since.
								 *
								 * Beneath the summary rather than in a column of
								 * its own: most claims have none of these, and
								 * an empty column on every row to accommodate
								 * the one that does is worse than nothing.
								 */
								$claim_thread = $claim_messages[ (int) $claim->id ] ?? array();
								?>
								<?php if ( ! empty( $claim_thread ) ) : ?>
									<ul class="warranty-claim-messages">
										<?php foreach ( $claim_thread as $claim_message ) : ?>
											<li class="warranty-claim-message">
												<span class="warranty-claim-message__meta">
													<?php
													printf(
														/* translators: 1: who wrote it, 2: the date. */
														\esc_html__( '%1$s · %2$s', 'warranty-cart' ),
														\esc_html( (string) $claim_message->author_name ),
														\esc_html(
															\wp_date(
																\get_option( 'date_format' ),
																strtotime( (string) $claim_message->created_at )
															)
														)
													);
													?>
												</span>
												<span class="warranty-claim-message__body">
													<?php echo \nl2br( \esc_html( (string) $claim_message->body ) ); ?>
												</span>
											</li>
										<?php endforeach; ?>
									</ul>
								<?php endif; ?>
							</td>
							<td class="warranty-cart-claims__cell-filed" data-title="<?php \esc_attr_e( 'Filed', 'warranty-cart' ); ?>">
								<?php echo \esc_html( \wp_date( \get_option( 'date_format' ), strtotime( (string) $claim->created_at ) ) ); ?>
							</td>
							<td class="warranty-cart-warranties__cell-status" data-title="<?php \esc_attr_e( 'Status', 'warranty-cart' ); ?>">
								<span class="warranty-claim-status warranty-claim-status--<?php echo \esc_attr( (string) $claim->status ); ?>">
									<?php
									echo \esc_html(
										$statuses[ (string) $claim->status ]
											?? ucfirst( str_replace( '_', ' ', (string) $claim->status ) )
									);
									?>
								</span>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>

	<?php endif; ?>
</div>

<?php
/**
 * After the warranties tab.
 *
 * @param bool $has_warranties Whether the customer has any.
 */
\do_action( 'warranty_cart_after_account_warranties', true );

