<?php
/**
 * My Account — one warranty, in full.
 *
 * The customer's counterpart to the admin's warranty record page, and the same
 * shape as WooCommerce's own `view-order`: the thing itself at the top, its
 * details beneath, then its history.
 *
 * This exists because the list could not hold it. Coverage terms, the item the
 * cover was bought for, every renewal and every claim do not fit in a table row
 * — the previous attempt folded the renewal history into a disclosure inside
 * the Expires cell, which put a nested list inside a table cell on a screen
 * that is already a table.
 *
 * @package WarrantyCart
 * @version 2.1.0
 */

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

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

$warranty         = $args['warranty'] ?? null;
$renewals         = $args['renewals'] ?? array();
$serials_enabled  = $args['serials_enabled'] ?? true;
$claims           = $args['claims'] ?? array();
$claims_enabled   = $args['claims_enabled'] ?? false;
$statuses         = $args['statuses'] ?? array();
$renewals_enabled = $args['renewals_enabled'] ?? false;
$can_renew        = $args['can_renew'] ?? false;
$list_url         = $args['list_url'] ?? '';

if ( ! $warranty ) {
	return;
}

$date_format = \get_option( 'date_format' );

$product = \wc_get_product( (int) $warranty->product_id );
$covered = ! empty( $warranty->covered_product_id ) ? \wc_get_product( (int) $warranty->covered_product_id ) : null;

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

$status        = (string) $warranty->status;
$status_labels = array(
	'active'    => \__( 'Active', 'warranty-cart' ),
	'expired'   => \__( 'Expired', 'warranty-cart' ),
	'cancelled' => \__( 'Cancelled', 'warranty-cart' ),
	'pending'   => \__( 'Pending', 'warranty-cart' ),
	'refunded'  => \__( 'Refunded', 'warranty-cart' ),
);
$status_label  = $status_labels[ $status ] ?? $status;

$coverage_lines = preg_split( '/\r\n|\r|\n/', (string) ( $warranty->coverage_details ?? '' ) );
$coverage_lines = array_filter( array_map( 'trim', is_array( $coverage_lines ) ? $coverage_lines : array() ) );

$term_unit  = (string) $warranty->duration_unit;
$term_count = (int) $warranty->duration;

/*
 * Tags allowed in a price. `wc_price()` wraps every amount in `<bdi>` so a
 * price and its currency symbol keep their order inside right-to-left text, and
 * `wp_kses_post()` strips it. See templates/frontend/product-warranty-offer.php.
 */
$warranty_price_tags = array(
	'span' => array(
		'class'     => true,
		'translate' => true,
	),
	'bdi'  => array(),
	'del'  => array(),
	'ins'  => array(),
);
?>

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

	<?php /* Where the claim form and the Renew button report back. */ ?>
	<div class="warranty-notice" id="warranty-claim-notice" role="status" aria-live="polite" hidden></div>

	<?php if ( $list_url ) : ?>
		<p class="warranty-single__back">
			<a href="<?php echo \esc_url( $list_url ); ?>">
				<?php \esc_html_e( '← All warranties', 'warranty-cart' ); ?>
			</a>
		</p>
	<?php endif; ?>

	<header class="warranty-single__head">
		<h2 class="warranty-single__title"><?php echo \esc_html( $name ); ?></h2>

		<span class="warranty-single__status warranty-single__status--<?php echo \esc_attr( $status ); ?>">
			<?php echo \esc_html( $status_label ); ?>
		</span>
	</header>

	<?php if ( $renewals_enabled && $can_renew ) : ?>
		<p class="warranty-single__actions">
			<button
				type="button"
				class="button warranty-renew"
				data-warranty="<?php echo \esc_attr( (string) $warranty->id ); ?>"
			>
				<?php \esc_html_e( 'Renew this warranty', 'warranty-cart' ); ?>
			</button>
		</p>
	<?php endif; ?>

	<h3 class="warranty-single__section"><?php \esc_html_e( 'Cover', 'warranty-cart' ); ?></h3>

	<table class="woocommerce-table shop_table warranty-single__facts">
		<tbody>
			<?php if ( $covered ) : ?>
				<tr>
					<th><?php \esc_html_e( 'Covers', 'warranty-cart' ); ?></th>
					<td><?php echo \esc_html( $covered->get_name() ); ?></td>
				</tr>
			<?php endif; ?>

			<tr>
				<th><?php \esc_html_e( 'Type', 'warranty-cart' ); ?></th>
				<td>
					<?php
					echo \esc_html(
						'main_warranty' === (string) $warranty->warranty_type
							? \__( 'Warranty cover', 'warranty-cart' )
							: \__( 'Additional service', 'warranty-cart' )
					);
					?>
				</td>
			</tr>

			<?php if ( $term_count > 0 ) : ?>
				<tr>
					<th><?php \esc_html_e( 'Term', 'warranty-cart' ); ?></th>
					<td>
						<?php
						if ( 'days' === $term_unit ) {
							/* translators: %d: number of days. */
							$term_text = sprintf( \_n( '%d day', '%d days', $term_count, 'warranty-cart' ), $term_count );
						} elseif ( 'months' === $term_unit ) {
							/* translators: %d: number of months. */
							$term_text = sprintf( \_n( '%d month', '%d months', $term_count, 'warranty-cart' ), $term_count );
						} else {
							/* translators: %d: number of years. */
							$term_text = sprintf( \_n( '%d year', '%d years', $term_count, 'warranty-cart' ), $term_count );
						}

						echo \esc_html( $term_text );
						?>
					</td>
				</tr>
			<?php endif; ?>

			<tr>
				<th><?php \esc_html_e( 'Cover begins', 'warranty-cart' ); ?></th>
				<td><?php echo \esc_html( \wp_date( $date_format, strtotime( (string) $warranty->purchase_date ) ) ); ?></td>
			</tr>

			<tr class="warranty-single__expiry">
				<th><?php \esc_html_e( 'Cover ends', 'warranty-cart' ); ?></th>
				<td><?php echo \esc_html( \wp_date( $date_format, strtotime( (string) $warranty->expiration_date ) ) ); ?></td>
			</tr>
		</tbody>
	</table>

	<?php if ( ! empty( $coverage_lines ) ) : ?>
		<h3 class="warranty-single__section"><?php \esc_html_e( 'What this covers', 'warranty-cart' ); ?></h3>

		<ul class="warranty-single__coverage">
			<?php foreach ( $coverage_lines as $line ) : ?>
				<li><?php echo \esc_html( $line ); ?></li>
			<?php endforeach; ?>
		</ul>
	<?php endif; ?>

	<h3 class="warranty-single__section"><?php \esc_html_e( 'Purchase', 'warranty-cart' ); ?></h3>

	<table class="woocommerce-table shop_table warranty-single__facts">
		<tbody>
			<tr>
				<th><?php \esc_html_e( 'Order', 'warranty-cart' ); ?></th>
				<td>
					<?php
					/*
					 * A warranty can have no order behind it.
					 *
					 * Cover issued by hand — a phone order, goodwill, a record
					 * brought across from another system — carries order_id 0.
					 * Printing that as "#0" tells the customer their policy
					 * belongs to an order that does not exist, which is both
					 * wrong and alarming.
					 */
					?>
					<?php if ( ! (int) $warranty->order_id ) : ?>
						<?php \esc_html_e( 'Issued directly', 'warranty-cart' ); ?>
					<?php elseif ( $order ) : ?>
						<a href="<?php echo \esc_url( $order->get_view_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>
			</tr>

			<tr>
				<th><?php \esc_html_e( 'Paid', 'warranty-cart' ); ?></th>
				<td>
					<?php
					echo \wp_kses(
						\wc_price(
							(float) $warranty->purchase_price,
							array( 'currency' => (string) $warranty->currency )
						),
						$warranty_price_tags
					);
					?>
				</td>
			</tr>

			<?php if ( ! empty( $warranty->payment_method ) ) : ?>
				<tr>
					<th><?php \esc_html_e( 'Paid with', 'warranty-cart' ); ?></th>
					<td>
						<?php
						/*
						 * The gateway's own title where it is still installed, so
						 * this reads "Credit card" rather than "ppcp-gateway".
						 */
						$gateways = \WC()->payment_gateways() ? \WC()->payment_gateways()->payment_gateways() : array();
						$gateway  = $gateways[ (string) $warranty->payment_method ] ?? null;

						echo \esc_html( $gateway ? $gateway->get_title() : (string) $warranty->payment_method );
						?>
					</td>
				</tr>
			<?php endif; ?>
		</tbody>
	</table>

	<?php
	/*
	 * The number on the back of the thing.
	 *
	 * Asked for after the purchase rather than during it, because at checkout
	 * the customer does not have the item yet — the serial is on a plate they
	 * can only read once it has arrived. Editable rather than write-once: the
	 * first attempt is usually a phone camera and a badly lit label.
	 */
	?>
	<?php if ( $serials_enabled ) : ?>

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

	<form class="warranty-serial" id="warranty-serial-form" data-warranty="<?php echo \esc_attr( (string) $warranty->id ); ?>">
		<p class="form-row">
			<label for="warranty-serial">
				<?php \esc_html_e( 'Serial number', 'warranty-cart' ); ?>
			</label>
			<input
				type="text"
				id="warranty-serial"
				name="serial"
				value="<?php echo \esc_attr( (string) ( $warranty->serial_number ?? '' ) ); ?>"
				maxlength="100"
				autocomplete="off"
				spellcheck="false"
			>
			<span class="warranty-serial__hint">
				<?php \esc_html_e( 'Printed on the item or its plate. Recording it means we can find this cover from the item itself.', 'warranty-cart' ); ?>
			</span>
		</p>

		<p class="form-row">
			<button type="submit" class="button" id="warranty-serial-submit">
				<?php \esc_html_e( 'Save serial number', 'warranty-cart' ); ?>
			</button>
		</p>

		<div class="warranty-serial__notice" role="status" aria-live="polite" hidden></div>
	</form>

	<?php endif; ?>

	<?php if ( ! empty( $renewals ) ) : ?>
		<h3 class="warranty-single__section"><?php \esc_html_e( 'Renewal history', 'warranty-cart' ); ?></h3>

		<?php
		/*
		 * A list, not a count.
		 *
		 * The tab could only say how many times a warranty had been renewed,
		 * which leaves the obvious question — a customer looking at an expiry
		 * date later than the term they remember buying wants to know when it
		 * moved, by how much, and what each extension cost.
		 */
		?>
		<ol class="warranty-single__history">
			<?php foreach ( $renewals as $renewal ) : ?>
				<li class="warranty-single__renewal">
					<span class="warranty-single__renewal-dates">
						<?php
						echo \esc_html(
							$renewal->previous_expiration
								? sprintf(
									/* translators: 1: previous expiry date, 2: new expiry date. */
									\__( 'Extended from %1$s to %2$s', 'warranty-cart' ),
									\wp_date( $date_format, strtotime( (string) $renewal->previous_expiration ) ),
									\wp_date( $date_format, strtotime( (string) $renewal->new_expiration ) )
								)
								: sprintf(
									/* translators: %s: new expiry date. */
									\__( 'Extended to %s', 'warranty-cart' ),
									\wp_date( $date_format, strtotime( (string) $renewal->new_expiration ) )
								)
						);
						?>
					</span>

					<span class="warranty-single__renewal-meta">
						<?php
						echo \esc_html( \wp_date( $date_format, strtotime( (string) $renewal->created_at ) ) );

						if ( null !== $renewal->amount && '' !== $renewal->amount ) {
							echo ' · ';
							echo \wp_kses(
								\wc_price(
									(float) $renewal->amount,
									array( 'currency' => (string) ( $renewal->currency ? $renewal->currency : $warranty->currency ) )
								),
								$warranty_price_tags
							);
						} elseif ( 'admin' === $renewal->source ) {
							/*
							 * A renewal the shop made on the customer's behalf takes
							 * no payment and creates no order. Saying so beats a
							 * blank space, which reads as a figure that failed to
							 * load.
							 */
							echo ' · ';
							echo \esc_html__( 'no charge', 'warranty-cart' );
						}
						?>
					</span>
				</li>
			<?php endforeach; ?>
		</ol>
	<?php endif; ?>

	<?php if ( $claims_enabled ) : ?>
		<h3 class="warranty-single__section"><?php \esc_html_e( 'Claims', 'warranty-cart' ); ?></h3>

		<?php if ( empty( $claims ) ) : ?>
			<p class="warranty-single__empty">
				<?php \esc_html_e( 'You have not filed a claim against this warranty.', 'warranty-cart' ); ?>
			</p>
		<?php else : ?>
			<ol class="warranty-single__history">
				<?php foreach ( $claims as $claim ) : ?>
					<li class="warranty-single__claim">
						<span class="warranty-single__claim-subject">
							<?php echo \esc_html( (string) $claim->subject ); ?>
						</span>

						<span class="warranty-single__renewal-meta">
							<?php
							echo \esc_html( \wp_date( $date_format, strtotime( (string) $claim->created_at ) ) );
							echo ' · ';
							echo \esc_html( $statuses[ (string) $claim->status ] ?? (string) $claim->status );
							?>
						</span>

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

		<?php if ( 'active' === $status ) : ?>
			<p class="warranty-single__actions">
				<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>
			</p>
		<?php endif; ?>
	<?php endif; ?>

	<?php
	/*
	 * The claim form the list tab carries, so the button above works here too.
	 * It is the same markup and the same handler — the frontend bundle binds by
	 * class, not by page.
	 */
	if ( $claims_enabled ) {
		\wc_get_template(
			'frontend/my-account-claim-form.php',
			array(),
			'warranty-cart',
			WARRANTY_CART_PATH . 'templates/'
		);
	}
	?>
</div>
<?php
// phpcs:enable
