<?php
/**
 * Warranty Certificate PDF Template
 *
 * A customer keeps this to prove what is covered and until when, and hands it
 * over when something breaks. The previous version stated neither: it listed
 * every line on the order — including the physical goods — under a heading
 * reading "Warranty Products", gave no term, no expiry date, no coverage terms
 * and no certificate number, and signed off as "Warranty Cart Plugin" rather
 * than as the shop the customer bought from.
 *
 * Laid out with tables and inline widths rather than flexbox or grid: Dompdf
 * renders neither, and a layout relying on them collapses into a single column
 * in the file the customer actually receives.
 *
 * @package WarrantyCart
 * @version 2.0.0
 */

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

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

$order = $args['order'] ?? null;

if ( ! $order instanceof WC_Order ) {
	return;
}

/**
 * Filter PDF certificate arguments
 *
 * @param array    $args  Template arguments.
 * @param WC_Order $order Order object.
 */
$args = \apply_filters( 'warranty_cart_pdf_certificate_args', $args, $order );

$records = warranty_cart()->repository->records_for_order( $order->get_id() );

/*
 * Fall back to the order's warranty lines.
 *
 * Records are written when an order completes, and an administrator can ask
 * for a certificate before that. A document without expiry dates is worth
 * more than one listing nothing at all.
 */
if ( empty( $records ) ) {
	$warranty_items = warranty_cart()->repository->get_order_warranty_items( $order );

	foreach ( $warranty_items['items'] as $item ) {
		$product = $item['product'] ?? null;

		$records[] = (object) array(
			'id'               => 0,
			'product_name'     => $item['product_name'],
			'product_sku'      => $product instanceof WC_Product ? $product->get_sku() : '',
			'covers'           => '',
			'covers_sku'       => '',
			'warranty_type'    => \WarrantyCart\Core\Repository::product_type( $product ),
			'duration'         => \WarrantyCart\Core\Repository::product_duration( $product ),
			'duration_unit'    => \WarrantyCart\Core\Repository::product_duration_unit( $product ),
			'purchase_date'    => '',
			'expiration_date'  => '',
			'coverage_details' => $product instanceof WC_Product
				? (string) $product->get_meta( '_warranty_cart_coverage_details', true )
				: '',
		);
	}
}

if ( empty( $records ) ) {
	return;
}

$date_format = \get_option( 'date_format' );
$created     = $order->get_date_created();

/*
 * The shop's name, not the plugin's.
 *
 * The footer read "Warranty Cart Plugin", which tells the customer nothing and
 * puts a piece of the shop's toolchain on a document they may hand to a
 * retailer or an insurer.
 */
$store_name  = \wp_specialchars_decode( \get_bloginfo( 'name' ), ENT_QUOTES );
$store_email = \get_option( 'woocommerce_email_from_address', \get_option( 'admin_email' ) );

/*
 * A number the shop and the customer can both quote.
 *
 * Derived from the order rather than generated, so it is stable across
 * regenerations — a number that changed each time the file was downloaded
 * would be useless for exactly the conversation it exists to support.
 */
$certificate_no = sprintf( 'WC-%s', $order->get_order_number() );

$accent = \apply_filters( 'warranty_cart_pdf_accent_colour', '#1d4ed8', $order );

/**
 * Human-readable term, e.g. "2 years".
 *
 * @param object $record A warranty record.
 *
 * @return string
 */
$term_label = static function ( $record ): string {
	$duration = (int) $record->duration;

	if ( $duration < 1 ) {
		return '';
	}

	switch ( $record->duration_unit ) {
		case 'days':
			/* translators: %d: number of days. */
			return sprintf( \_n( '%d day', '%d days', $duration, 'warranty-cart' ), $duration );
		case 'months':
			/* translators: %d: number of months. */
			return sprintf( \_n( '%d month', '%d months', $duration, 'warranty-cart' ), $duration );
		default:
			/* translators: %d: number of years. */
			return sprintf( \_n( '%d year', '%d years', $duration, 'warranty-cart' ), $duration );
	}
};
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title><?php \esc_html_e( 'Warranty Certificate', 'warranty-cart' ); ?></title>
	<style>
		@page { margin: 0; }

		body {
			font-family: DejaVu Sans, Arial, sans-serif;
			margin: 0;
			color: #1f2937;
			font-size: 11pt;
			line-height: 1.5;
		}

		.sheet { padding: 34px 44px 44px; }

		/*
		 * A table, not a flex row: Dompdf ignores flexbox, and the two halves
		 * have to sit side by side on every renderer this file might meet.
		 */
		.masthead { width: 100%; border-collapse: collapse; margin-bottom: 24px; }
		.masthead td { vertical-align: top; padding: 0; border: 0; }

		.store-name { font-size: 17pt; font-weight: bold; margin: 0; color: #111827; }
		.store-meta { font-size: 9pt; color: #6b7280; margin: 3px 0 0; }

		.doc-title {
			text-align: right;
			font-size: 9pt;
			letter-spacing: 1.4px;
			text-transform: uppercase;
			color: <?php echo \esc_html( $accent ); ?>;
			font-weight: bold;
			margin: 0;
		}
		.doc-number { text-align: right; font-size: 9pt; color: #6b7280; margin: 4px 0 0; }

		.rule { height: 3px; background: <?php echo \esc_html( $accent ); ?>; margin: 0 0 24px; }

		/* One block per warranty, kept whole across a page break. */
		.cover { page-break-inside: avoid; margin-bottom: 22px; }

		.cover-head {
			background: #f8fafc;
			border: 1px solid #e5e7eb;
			border-bottom: 0;
			padding: 12px 16px;
		}
		.cover-name { font-size: 13pt; font-weight: bold; margin: 0; color: #111827; }
		.cover-kind {
			font-size: 8.5pt;
			color: #6b7280;
			margin: 2px 0 0;
			text-transform: uppercase;
			letter-spacing: 0.6px;
		}

		.facts { width: 100%; border-collapse: collapse; }
		.facts th, .facts td {
			border: 1px solid #e5e7eb;
			padding: 9px 16px;
			text-align: left;
			font-size: 10pt;
			vertical-align: top;
		}
		.facts th { width: 32%; font-weight: normal; color: #6b7280; }
		.facts td { color: #111827; }

		/*
		 * The expiry is the single fact somebody opens this document to find,
		 * so it is the one row set apart from the rest of the table.
		 */
		.expiry td { font-weight: bold; font-size: 11.5pt; }

		.terms { padding: 12px 16px; border: 1px solid #e5e7eb; border-top: 0; }
		.terms-title {
			font-size: 8.5pt;
			text-transform: uppercase;
			letter-spacing: 0.6px;
			color: #6b7280;
			margin: 0 0 6px;
		}
		.terms ul { margin: 0; padding-left: 16px; }
		.terms li { font-size: 10pt; margin-bottom: 3px; }

		/*
		 * Kept whole. The proof-of-purchase block split across a page break on
		 * any order with two warranties on it, leaving the order number on one
		 * page and the customer it belongs to on the next.
		 */
		.keep-together { page-break-inside: avoid; }

		.order-panel { width: 100%; border-collapse: collapse; }
		.order-panel th, .order-panel td {
			border: 1px solid #e5e7eb;
			padding: 8px 16px;
			font-size: 9.5pt;
			text-align: left;
			vertical-align: top;
		}
		.order-panel th { background: #f8fafc; font-weight: normal; color: #6b7280; width: 32%; }

		.section-title {
			font-size: 9pt;
			text-transform: uppercase;
			letter-spacing: 1px;
			color: #6b7280;
			margin: 24px 0 8px;
			font-weight: bold;
		}

		.claiming { font-size: 9.5pt; color: #374151; margin: 0; }
		.muted { color: #6b7280; font-size: 9pt; }

		.footer {
			margin-top: 26px;
			padding-top: 12px;
			border-top: 1px solid #e5e7eb;
			font-size: 8.5pt;
			color: #9ca3af;
		}
	</style>
</head>
<body>
<div class="sheet">
	<?php
	/**
	 * Action before PDF certificate header
	 *
	 * @param WC_Order $order Order object.
	 */
	\do_action( 'warranty_cart_pdf_certificate_before_header', $order );
	?>

	<table class="masthead">
		<tr>
			<td>
				<p class="store-name"><?php echo \esc_html( $store_name ); ?></p>
				<?php if ( $store_email ) : ?>
					<p class="store-meta"><?php echo \esc_html( $store_email ); ?></p>
				<?php endif; ?>
			</td>
			<td>
				<p class="doc-title"><?php \esc_html_e( 'Warranty Certificate', 'warranty-cart' ); ?></p>
				<p class="doc-number"><?php echo \esc_html( $certificate_no ); ?></p>
			</td>
		</tr>
	</table>

	<div class="rule"></div>

	<?php
	/**
	 * Action after PDF certificate header
	 *
	 * @param WC_Order $order Order object.
	 */
	\do_action( 'warranty_cart_pdf_certificate_after_header', $order );
	?>

	<?php foreach ( $records as $record ) : ?>
		<?php
		$term     = $term_label( $record );
		$is_main  = 'main_warranty' === $record->warranty_type;
		$lines    = preg_split( '/\r\n|\r|\n/', (string) $record->coverage_details );
		$coverage = array_filter( array_map( 'trim', is_array( $lines ) ? $lines : array() ) );
		?>
		<div class="cover">
			<div class="cover-head">
				<p class="cover-name"><?php echo \esc_html( $record->product_name ); ?></p>
				<p class="cover-kind">
					<?php
					echo \esc_html(
						$is_main
							? __( 'Warranty cover', 'warranty-cart' )
							: __( 'Additional service', 'warranty-cart' )
					);
					?>
				</p>
			</div>

			<table class="facts">
				<?php if ( ! empty( $record->covers ) ) : ?>
					<tr>
						<th><?php \esc_html_e( 'Covers', 'warranty-cart' ); ?></th>
						<td>
							<?php echo \esc_html( $record->covers ); ?>
							<?php if ( ! empty( $record->covers_sku ) ) : ?>
								<br><span class="muted"><?php echo \esc_html( $record->covers_sku ); ?></span>
							<?php endif; ?>
						</td>
					</tr>
				<?php endif; ?>

				<?php if ( $term ) : ?>
					<tr>
						<th><?php \esc_html_e( 'Term', 'warranty-cart' ); ?></th>
						<td><?php echo \esc_html( $term ); ?></td>
					</tr>
				<?php endif; ?>

				<?php if ( ! empty( $record->purchase_date ) ) : ?>
					<tr>
						<th><?php \esc_html_e( 'Cover begins', 'warranty-cart' ); ?></th>
						<td><?php echo \esc_html( \wp_date( $date_format, (int) strtotime( $record->purchase_date ) ) ); ?></td>
					</tr>
				<?php endif; ?>

				<?php if ( ! empty( $record->expiration_date ) ) : ?>
					<tr class="expiry">
						<th><?php \esc_html_e( 'Cover ends', 'warranty-cart' ); ?></th>
						<td><?php echo \esc_html( \wp_date( $date_format, (int) strtotime( $record->expiration_date ) ) ); ?></td>
					</tr>
				<?php endif; ?>

				<?php if ( ! empty( $record->id ) ) : ?>
					<tr>
						<th><?php \esc_html_e( 'Reference', 'warranty-cart' ); ?></th>
						<td><?php echo \esc_html( $certificate_no . '-' . $record->id ); ?></td>
					</tr>
				<?php endif; ?>
			</table>

			<?php if ( ! empty( $coverage ) ) : ?>
				<div class="terms">
					<p class="terms-title"><?php \esc_html_e( 'What this covers', 'warranty-cart' ); ?></p>
					<ul>
						<?php foreach ( $coverage as $line ) : ?>
							<li><?php echo \esc_html( $line ); ?></li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>
		</div>
	<?php endforeach; ?>

	<div class="keep-together">
	<p class="section-title"><?php \esc_html_e( 'Proof of purchase', 'warranty-cart' ); ?></p>

	<table class="order-panel">
		<tr>
			<th><?php \esc_html_e( 'Order', 'warranty-cart' ); ?></th>
			<td><?php echo \esc_html( $order->get_order_number() ); ?></td>
		</tr>
		<tr>
			<th><?php \esc_html_e( 'Purchased', 'warranty-cart' ); ?></th>
			<td>
				<?php
				/*
				 * A saved order always has a creation date, but a null here is a
				 * fatal in a customer-facing document, so it is not assumed.
				 */
				echo \esc_html( $created ? \wp_date( $date_format, $created->getTimestamp() ) : '—' );
				?>
			</td>
		</tr>
		<tr>
			<th><?php \esc_html_e( 'Customer', 'warranty-cart' ); ?></th>
			<td>
				<?php echo \esc_html( $order->get_formatted_billing_full_name() ); ?>
				<?php if ( $order->get_billing_email() ) : ?>
					<br><span class="muted"><?php echo \esc_html( $order->get_billing_email() ); ?></span>
				<?php endif; ?>
			</td>
		</tr>
	</table>
	</div>

	<div class="keep-together">
	<p class="section-title"><?php \esc_html_e( 'Making a claim', 'warranty-cart' ); ?></p>

	<p class="claiming">
		<?php
		echo \esc_html(
			$store_email
				? sprintf(
					/* translators: %s: the shop's email address. */
					__( 'Contact %s quoting the certificate number above, and describe the fault. Keep this document for the length of the cover — it is your proof of purchase and of what was covered.', 'warranty-cart' ),
					$store_email
				)
				: __( 'Contact the shop quoting the certificate number above, and describe the fault. Keep this document for the length of the cover — it is your proof of purchase and of what was covered.', 'warranty-cart' )
		);
		?>
	</p>
	</div>

	<?php
	/**
	 * Action before the certificate footer.
	 *
	 * @param WC_Order $order Order object.
	 */
	\do_action( 'warranty_cart_pdf_certificate_before_footer', $order );
	?>

	<div class="footer">
		<?php
		echo \esc_html(
			sprintf(
				/* translators: 1: the shop's name, 2: the date the file was produced. */
				__( 'Issued by %1$s on %2$s.', 'warranty-cart' ),
				$store_name,
				\wp_date( $date_format )
			)
		);
		?>
	</div>
</div>
</body>
</html>
<?php
// phpcs:enable
