<?php
/**
 * Storzen Module — Invoice / PDF (Pro)
 *
 * Generates branded HTML invoices for WooCommerce orders.
 *
 * Implementation note on PDF:
 *   v1 generates print-optimized HTML invoices that customers download as
 *   PDF via their browser's native print → save-as-PDF dialog (Ctrl+P).
 *   This avoids bundling a 3MB+ vendor library (dompdf/mpdf) which would
 *   bloat the plugin and create security maintenance burden. True
 *   server-side PDF generation + email attachment is on the roadmap for
 *   a future "Storzen Invoice PDF" companion plugin.
 *
 *   The `attach_to_email` setting therefore attaches the HTML invoice
 *   (renderable in any modern email client) rather than a PDF binary.
 *
 * Numbering:
 *   Sequential per year. Persisted as option `storzen_invoice_seq_{year}`.
 *   Each order gets a stable number stored as `_storzen_invoice_number` meta
 *   on first generation; never re-assigned afterwards.
 *
 * Access:
 *   Invoice URL: ?storzen_invoice=ORDER_ID&key=ORDER_KEY
 *   Admin can access via order edit screen's "Storzen Invoice" link.
 *
 * @package storzen
 * @since   1.6.1
 */

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

if ( ! class_exists( 'Storzen_Module_Invoice' ) ) {

	class Storzen_Module_Invoice {

		const META_NUMBER     = '_storzen_invoice_number';
		const META_GEN_AT     = '_storzen_invoice_generated_at';
		const OPTION_SEQ_FMT  = 'storzen_invoice_seq_%d'; // %d = year
		const QUERY_PARAM     = 'storzen_invoice';

		/** @var array|null */
		private $settings = null;

		public function __construct() {
			if ( ! function_exists( 'WC' ) ) {
				return;
			}

			// Frontend invoice viewer (rendered via query param).
			// Module loads at init priority 15 — 'init' has already fired, so
			// call directly. Also hook template_redirect as a belt-and-suspenders
			// fallback for requests where init priority 15 runs in time.
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public invoice link authorized by the order key (checked in maybe_render_invoice), not a nonce.
			if ( isset( $_GET[ self::QUERY_PARAM ] ) ) {
				$this->maybe_render_invoice();
			}
			add_action( 'template_redirect', array( $this, 'maybe_render_invoice' ), 1 );

			// Auto-generate invoice number when order hits target status.
			$s = $this->get_settings();
			if ( 'manual' !== $s['generate_on'] ) {
				if ( 'processing' === $s['generate_on'] ) {
					add_action( 'woocommerce_order_status_processing', array( $this, 'on_status_change' ), 10, 2 );
				} elseif ( 'completed' === $s['generate_on'] ) {
					add_action( 'woocommerce_order_status_completed',  array( $this, 'on_status_change' ), 10, 2 );
				} elseif ( 'paid' === $s['generate_on'] ) {
					add_action( 'woocommerce_order_status_processing', array( $this, 'on_status_change' ), 10, 2 );
					add_action( 'woocommerce_order_status_completed',  array( $this, 'on_status_change' ), 10, 2 );
				}
			}

			// Email attachment (HTML).
			if ( $s['attach_to_email'] ) {
				add_filter( 'woocommerce_email_attachments', array( $this, 'attach_to_email' ), 10, 3 );
			}

			// Customer download link in "My Account → Orders" — for past orders too.
			if ( $s['allow_download'] ) {
				add_filter( 'woocommerce_my_account_my_orders_actions', array( $this, 'add_my_account_action' ), 10, 2 );
				// On the single order view page (My Account → Order Details).
				add_action( 'woocommerce_order_details_after_order_table', array( $this, 'render_download_button' ), 10, 1 );
			}

			// Admin: link on the order edit screen.
			if ( is_admin() ) {
				add_action( 'woocommerce_admin_order_data_after_order_details', array( $this, 'admin_order_invoice_link' ) );
			}
		}

		// ─────────────────────────────────────────────────────────────────
		// Settings
		// ─────────────────────────────────────────────────────────────────

		private function get_settings() {
			if ( null !== $this->settings ) return $this->settings;

			$valid_gen = array( 'processing', 'completed', 'paid', 'manual' );
			$gen = (string) storzen_module_setting( 'invoice', 'generate_on' );
			if ( ! in_array( $gen, $valid_gen, true ) ) $gen = 'completed';

			$valid_paper = array( 'A4', 'Letter', 'Legal' );
			$paper = (string) storzen_module_setting( 'invoice', 'paper_size' );
			if ( ! in_array( $paper, $valid_paper, true ) ) $paper = 'A4';

			$prefix     = rtrim( (string) storzen_module_setting( 'invoice', 'invoice_number_prefix' ), '-' );
			$company    = (string) storzen_module_setting( 'invoice', 'company_name' );
			$details    = (string) storzen_module_setting( 'invoice', 'company_details' );
			$logo       = (string) storzen_module_setting( 'invoice', 'logo_url' );
			$accent     = sanitize_hex_color( (string) storzen_module_setting( 'invoice', 'accent_color' ) );
			$footer     = (string) storzen_module_setting( 'invoice', 'footer_text' );

			$this->settings = array(
				'generate_on'           => $gen,
				'paper_size'            => $paper,
				'invoice_number_prefix' => $prefix !== '' ? $prefix : 'INV',
				'company_name'          => $company !== '' ? $company : get_bloginfo( 'name' ),
				'company_details'       => $details,
				'logo_url'              => esc_url_raw( $logo ),
				'accent_color'          => $accent ?: '#FF3636',
				'footer_text'           => $footer !== '' ? $footer : __( 'Thank you for your business!', 'storzen' ),
				'include_tax_breakdown' => (bool) storzen_module_setting( 'invoice', 'include_tax_breakdown' ),
				'attach_to_email'       => (bool) storzen_module_setting( 'invoice', 'attach_to_email' ),
				'allow_download'        => (bool) storzen_module_setting( 'invoice', 'allow_download' ),
			);
			return $this->settings;
		}

		// ─────────────────────────────────────────────────────────────────
		// Numbering
		// ─────────────────────────────────────────────────────────────────

		/**
		 * Assign an invoice number to the order, if it doesn't have one yet.
		 * Idempotent — repeated calls return the existing number.
		 *
		 * @param WC_Order $order
		 * @return string The invoice number.
		 */
		private function ensure_invoice_number( $order ) {
			if ( ! $order instanceof WC_Order ) {
				return '';
			}

			$existing = $order->get_meta( self::META_NUMBER, true );
			if ( $existing ) {
				return $existing;
			}

			$s     = $this->get_settings();
			$year  = (int) gmdate( 'Y' );
			$opt   = sprintf( self::OPTION_SEQ_FMT, $year );
			$seq   = (int) get_option( $opt, 0 ) + 1;
			update_option( $opt, $seq, false );

			$number = sprintf( '%s-%d-%05d', $s['invoice_number_prefix'], $year, $seq );
			$order->update_meta_data( self::META_NUMBER, $number );
			$order->update_meta_data( self::META_GEN_AT, current_time( 'mysql', true ) );
			$order->save_meta_data();

			return $number;
		}

		/**
		 * Triggered when WC moves an order into our configured status.
		 *
		 * @param int      $order_id
		 * @param WC_Order $order
		 */
		public function on_status_change( $order_id, $order = null ) {
			$order = $order ?: wc_get_order( $order_id );
			if ( $order ) {
				$this->ensure_invoice_number( $order );
				do_action( 'storzen_invoice_generated', $order, $this );
			}
		}

		// ─────────────────────────────────────────────────────────────────
		// Frontend viewer
		// ─────────────────────────────────────────────────────────────────

		/**
		 * If the page request includes `?storzen_invoice=ID&key=KEY`,
		 * render the invoice HTML and exit.
		 */
		public function maybe_render_invoice() {
			// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public invoice link authorized by the order key (see can_view_invoice), not a nonce.
			if ( ! isset( $_GET[ self::QUERY_PARAM ] ) ) {
				return;
			}

			$order_id = absint( wp_unslash( $_GET[ self::QUERY_PARAM ] ) );
			$key      = isset( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : '';
			// phpcs:enable WordPress.Security.NonceVerification.Recommended
			$order    = wc_get_order( $order_id );

			if ( ! $order || ! $this->can_view_invoice( $order, $key ) ) {
				wp_die( esc_html__( 'You do not have permission to view this invoice.', 'storzen' ), 403 );
			}

			$this->ensure_invoice_number( $order );

			// Stream the invoice HTML and stop normal WP page rendering.
			nocache_headers();
			header( 'Content-Type: text/html; charset=utf-8' );
			echo $this->render_invoice_html( $order ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML built from sanitized data
			exit;
		}

		/**
		 * Permission check: order key matches (for guests + customers), or
		 * current user can manage shop orders.
		 */
		private function can_view_invoice( $order, $key ) {
			if ( current_user_can( 'edit_shop_orders' ) ) {
				return true;
			}
			if ( $key && hash_equals( $order->get_order_key(), $key ) ) {
				return true;
			}
			// Customer logged in + owns the order.
			$cid = $order->get_customer_id();
			if ( $cid && is_user_logged_in() && (int) $cid === get_current_user_id() ) {
				return true;
			}
			return false;
		}

		/**
		 * Generate the secure invoice URL for an order.
		 *
		 * @param WC_Order $order
		 * @return string
		 */
		public function get_invoice_url( $order ) {
			return add_query_arg( array(
				self::QUERY_PARAM => $order->get_id(),
				'key'             => $order->get_order_key(),
			), home_url( '/' ) );
		}

		// ─────────────────────────────────────────────────────────────────
		// Customer-facing download links
		// ─────────────────────────────────────────────────────────────────

		/**
		 * Add a "Download Invoice" action button to "My Account → Orders" list.
		 */
		public function add_my_account_action( $actions, $order ) {
			if ( ! $order instanceof WC_Order ) {
				return $actions;
			}
			$actions['storzen_invoice'] = array(
				'url'  => $this->get_invoice_url( $order ),
				'name' => __( 'Invoice', 'storzen' ),
			);
			return $actions;
		}

		/**
		 * On the single order view page in My Account.
		 */
		public function render_download_button( $order ) {
			?>
			<p class="storzen-invoice-download-cta">
				<a class="button" href="<?php echo esc_url( $this->get_invoice_url( $order ) ); ?>" target="_blank" rel="noopener">
					<?php esc_html_e( 'Download Invoice', 'storzen' ); ?>
				</a>
			</p>
			<?php
		}

		/**
		 * Admin order edit screen — link to view the invoice.
		 */
		public function admin_order_invoice_link( $order ) {
			if ( ! $order instanceof WC_Order ) return;
			$number = $order->get_meta( self::META_NUMBER, true );
			?>
			<p class="form-field form-field-wide" style="background:#f3f4f6;padding:10px;border-radius:4px;margin-top:12px">
				<strong><?php esc_html_e( 'Storzen Invoice:', 'storzen' ); ?></strong>
				<?php if ( $number ) : ?>
					<code><?php echo esc_html( $number ); ?></code>
				<?php else : ?>
					<em><?php esc_html_e( 'Not yet generated', 'storzen' ); ?></em>
				<?php endif; ?>
				<br>
				<a class="button button-secondary" href="<?php echo esc_url( $this->get_invoice_url( $order ) ); ?>" target="_blank" rel="noopener" style="margin-top:6px">
					<?php esc_html_e( 'View / Print Invoice', 'storzen' ); ?>
				</a>
			</p>
			<?php
		}

		// ─────────────────────────────────────────────────────────────────
		// Email attachment
		// ─────────────────────────────────────────────────────────────────

		/**
		 * Attach an HTML invoice file to outgoing customer emails.
		 *
		 * @param string[] $attachments
		 * @param string   $email_id
		 * @param mixed    $object
		 * @return string[]
		 */
		public function attach_to_email( $attachments, $email_id, $object ) {
			// Customer-facing emails only — skip admin notifications.
			$customer_emails = array(
				'customer_processing_order',
				'customer_completed_order',
				'customer_invoice',
				'customer_on_hold_order',
			);
			if ( ! in_array( $email_id, $customer_emails, true ) ) {
				return $attachments;
			}
			if ( ! $object instanceof WC_Order ) {
				return $attachments;
			}

			$this->ensure_invoice_number( $object );

			// Write HTML file into uploads/storzen-invoices/.
			$dir = wp_upload_dir();
			$folder = trailingslashit( $dir['basedir'] ) . 'storzen-invoices';
			if ( ! file_exists( $folder ) ) {
				wp_mkdir_p( $folder );
				// Add an index.html to prevent directory listing.
				@file_put_contents( $folder . '/index.html', '' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors,WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			}

			$filename = $folder . '/invoice-' . $object->get_meta( self::META_NUMBER ) . '.html';
			$html     = $this->render_invoice_html( $object );

			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			if ( false !== @file_put_contents( $filename, $html ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors
				$attachments[] = $filename;
			}

			return $attachments;
		}

		// ─────────────────────────────────────────────────────────────────
		// Invoice HTML rendering
		// ─────────────────────────────────────────────────────────────────

		/**
		 * Build the full invoice HTML document for an order.
		 *
		 * @param WC_Order $order
		 * @return string
		 */
		public function render_invoice_html( $order ) {
			$s        = $this->get_settings();
			$number   = $this->ensure_invoice_number( $order );
			$accent   = esc_attr( $s['accent_color'] );
			$paper    = $s['paper_size'];

			$paper_css = array(
				'A4'     => '@page { size: A4; margin: 18mm; }',
				'Letter' => '@page { size: Letter; margin: 0.75in; }',
				'Legal'  => '@page { size: Legal; margin: 0.75in; }',
			);
			$paper_rule = $paper_css[ $paper ] ?? $paper_css['A4'];

			$billing  = $order->get_address( 'billing' );
			$shipping = $order->get_address( 'shipping' );
			$has_shipping = ! empty( array_filter( $shipping ) ) && $shipping !== $billing;

			$date     = wc_format_datetime( $order->get_date_created() );
			$status   = wc_get_order_status_name( $order->get_status() );
			$site_url = home_url( '/' );

			ob_start();
			?><!DOCTYPE html>
<html lang="<?php echo esc_attr( get_bloginfo( 'language' ) ); ?>">
<head>
<meta charset="utf-8">
<title><?php
	/* translators: %s invoice number */
	printf( esc_html__( 'Invoice %s', 'storzen' ), esc_html( $number ) );
?></title>
<style>
<?php echo $paper_rule; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS ?>
* { box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; color: #1f2937; line-height: 1.5; margin: 0; padding: 24px; font-size: 13px; }
.inv-wrap { max-width: 800px; margin: 0 auto; }

.inv-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; padding-bottom: 20px; border-bottom: 3px solid <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; }
.inv-brand h1 { margin: 0 0 4px; font-size: 22px; color: <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; font-weight: 700; }
.inv-brand .company-details { font-size: 12px; color: #6b7280; white-space: pre-line; }
.inv-brand img.logo { max-height: 60px; margin-bottom: 8px; }

.inv-meta { text-align: right; }
.inv-meta h2 { margin: 0 0 6px; font-size: 28px; font-weight: 700; letter-spacing: 1px; color: <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; }
.inv-meta dl { margin: 0; font-size: 12px; }
.inv-meta dt { display: inline-block; min-width: 90px; color: #6b7280; }
.inv-meta dd { display: inline-block; margin: 0 0 2px; font-weight: 500; }

.inv-parties { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 24px 0; }
.inv-party { background: #f9fafb; border-radius: 6px; padding: 12px 14px; }
.inv-party h3 { margin: 0 0 6px; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: #6b7280; }
.inv-party p { margin: 0; font-size: 13px; line-height: 1.5; }

.inv-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
.inv-table th { background: <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; color: #fff; padding: 10px 12px; text-align: left; font-size: 12px; font-weight: 600; }
.inv-table th.num { text-align: right; }
.inv-table td { padding: 10px 12px; border-bottom: 1px solid #e5e7eb; font-size: 13px; vertical-align: top; }
.inv-table td.num { text-align: right; }
.inv-table tbody tr:last-child td { border-bottom: 0; }

.inv-totals { margin-top: 20px; display: flex; justify-content: flex-end; }
.inv-totals table { width: 100%; max-width: 340px; }
.inv-totals td { padding: 6px 10px; font-size: 13px; }
.inv-totals td.label { color: #6b7280; }
.inv-totals td.value { text-align: right; font-weight: 500; }
.inv-totals tr.grand-total { border-top: 2px solid <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; }
.inv-totals tr.grand-total td { padding-top: 10px; font-size: 16px; font-weight: 700; color: <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; }

.inv-footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #e5e7eb; font-size: 11px; color: #9ca3af; text-align: center; white-space: pre-line; }

.inv-print-btn { position: fixed; top: 20px; right: 20px; background: <?php echo $accent; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; color: #fff; border: 0; padding: 10px 18px; font-size: 13px; font-weight: 600; border-radius: 6px; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,.12); }
.inv-print-hint { position: fixed; top: 60px; right: 20px; background: #fff; padding: 8px 12px; border-radius: 4px; box-shadow: 0 2px 6px rgba(0,0,0,.08); font-size: 11px; color: #6b7280; max-width: 200px; }

@media print {
	body { padding: 0; }
	.inv-print-btn, .inv-print-hint { display: none; }
}
</style>
</head>
<body>
<button class="inv-print-btn" onclick="window.print()"><?php esc_html_e( 'Print / Save as PDF', 'storzen' ); ?></button>
<p class="inv-print-hint"><?php esc_html_e( 'Use your browser\'s "Save as PDF" option in the print dialog.', 'storzen' ); ?></p>

<div class="inv-wrap">

	<header class="inv-header">
		<div class="inv-brand">
			<?php if ( $s['logo_url'] ) : ?>
				<img class="logo" src="<?php echo esc_url( $s['logo_url'] ); ?>" alt="">
			<?php endif; ?>
			<h1><?php echo esc_html( $s['company_name'] ); ?></h1>
			<?php if ( $s['company_details'] ) : ?>
				<div class="company-details"><?php echo esc_html( $s['company_details'] ); ?></div>
			<?php endif; ?>
		</div>
		<div class="inv-meta">
			<h2><?php esc_html_e( 'INVOICE', 'storzen' ); ?></h2>
			<dl>
				<dt><?php esc_html_e( 'Number:', 'storzen' ); ?></dt><dd><?php echo esc_html( $number ); ?></dd><br>
				<dt><?php esc_html_e( 'Order #:', 'storzen' ); ?></dt><dd><?php echo esc_html( $order->get_order_number() ); ?></dd><br>
				<dt><?php esc_html_e( 'Date:', 'storzen' ); ?></dt><dd><?php echo esc_html( $date ); ?></dd><br>
				<dt><?php esc_html_e( 'Status:', 'storzen' ); ?></dt><dd><?php echo esc_html( $status ); ?></dd>
			</dl>
		</div>
	</header>

	<section class="inv-parties">
		<div class="inv-party">
			<h3><?php esc_html_e( 'Billed To', 'storzen' ); ?></h3>
			<p>
				<strong><?php echo esc_html( trim( $billing['first_name'] . ' ' . $billing['last_name'] ) ); ?></strong><br>
				<?php
				$lines = array_filter( array(
					$billing['company'] ?? '',
					$billing['address_1'] ?? '',
					$billing['address_2'] ?? '',
					trim( ( $billing['city'] ?? '' ) . ' ' . ( $billing['postcode'] ?? '' ) ),
					$billing['country'] ?? '',
					$billing['email'] ?? '',
					$billing['phone'] ?? '',
				) );
				echo esc_html( implode( "\n", $lines ) );
				?>
			</p>
		</div>
		<?php if ( $has_shipping ) : ?>
			<div class="inv-party">
				<h3><?php esc_html_e( 'Shipped To', 'storzen' ); ?></h3>
				<p>
					<strong><?php echo esc_html( trim( $shipping['first_name'] . ' ' . $shipping['last_name'] ) ); ?></strong><br>
					<?php
					$lines = array_filter( array(
						$shipping['company'] ?? '',
						$shipping['address_1'] ?? '',
						$shipping['address_2'] ?? '',
						trim( ( $shipping['city'] ?? '' ) . ' ' . ( $shipping['postcode'] ?? '' ) ),
						$shipping['country'] ?? '',
					) );
					echo esc_html( implode( "\n", $lines ) );
					?>
				</p>
			</div>
		<?php else : ?>
			<div class="inv-party">
				<h3><?php esc_html_e( 'Payment Method', 'storzen' ); ?></h3>
				<p><?php echo esc_html( $order->get_payment_method_title() ); ?></p>
			</div>
		<?php endif; ?>
	</section>

	<table class="inv-table">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Item', 'storzen' ); ?></th>
				<th class="num"><?php esc_html_e( 'Qty', 'storzen' ); ?></th>
				<th class="num"><?php esc_html_e( 'Price', 'storzen' ); ?></th>
				<th class="num"><?php esc_html_e( 'Total', 'storzen' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ( $order->get_items() as $item ) :
				/** @var WC_Order_Item_Product $item */
				$qty = $item->get_quantity();
				$line_total = $item->get_total();
				$unit = $qty > 0 ? $line_total / $qty : $line_total;
				?>
				<tr>
					<td>
						<strong><?php echo esc_html( $item->get_name() ); ?></strong>
						<?php
						$meta = wc_display_item_meta( $item, array( 'echo' => false ) );
						if ( $meta ) {
							echo '<div style="font-size:11px;color:#6b7280;margin-top:4px">' . wp_kses_post( $meta ) . '</div>';
						}
						?>
					</td>
					<td class="num"><?php echo esc_html( (string) $qty ); ?></td>
					<td class="num"><?php echo wp_kses_post( wc_price( $unit, array( 'currency' => $order->get_currency() ) ) ); ?></td>
					<td class="num"><?php echo wp_kses_post( wc_price( $line_total, array( 'currency' => $order->get_currency() ) ) ); ?></td>
				</tr>
			<?php endforeach; ?>
		</tbody>
	</table>

	<section class="inv-totals">
		<table>
			<tr>
				<td class="label"><?php esc_html_e( 'Subtotal', 'storzen' ); ?></td>
				<td class="value"><?php echo wp_kses_post( wc_price( $order->get_subtotal(), array( 'currency' => $order->get_currency() ) ) ); ?></td>
			</tr>
			<?php
			$shipping_total = (float) $order->get_shipping_total();
			if ( $shipping_total > 0 ) : ?>
				<tr>
					<td class="label"><?php esc_html_e( 'Shipping', 'storzen' ); ?></td>
					<td class="value"><?php echo wp_kses_post( wc_price( $shipping_total, array( 'currency' => $order->get_currency() ) ) ); ?></td>
				</tr>
			<?php endif; ?>

			<?php
			$discount_total = (float) $order->get_discount_total();
			if ( $discount_total > 0 ) : ?>
				<tr>
					<td class="label"><?php esc_html_e( 'Discount', 'storzen' ); ?></td>
					<td class="value">-<?php echo wp_kses_post( wc_price( $discount_total, array( 'currency' => $order->get_currency() ) ) ); ?></td>
				</tr>
			<?php endif; ?>

			<?php
			$tax_total = (float) $order->get_total_tax();
			if ( $tax_total > 0 ) :
				if ( $s['include_tax_breakdown'] ) {
					foreach ( $order->get_tax_totals() as $tax ) {
						?>
						<tr>
							<td class="label"><?php echo esc_html( $tax->label ); ?></td>
							<td class="value"><?php echo wp_kses_post( wc_price( $tax->amount, array( 'currency' => $order->get_currency() ) ) ); ?></td>
						</tr>
						<?php
					}
				} else {
					?>
					<tr>
						<td class="label"><?php esc_html_e( 'Tax', 'storzen' ); ?></td>
						<td class="value"><?php echo wp_kses_post( wc_price( $tax_total, array( 'currency' => $order->get_currency() ) ) ); ?></td>
					</tr>
					<?php
				}
			endif; ?>

			<tr class="grand-total">
				<td class="label"><?php esc_html_e( 'Total', 'storzen' ); ?></td>
				<td class="value"><?php echo wp_kses_post( wc_price( $order->get_total(), array( 'currency' => $order->get_currency() ) ) ); ?></td>
			</tr>
		</table>
	</section>

	<footer class="inv-footer">
		<?php echo esc_html( $s['footer_text'] ); ?>
		<br><br>
		<small><?php echo esc_url( $site_url ); ?></small>
	</footer>

</div>
</body>
</html>
<?php
			return ob_get_clean();
		}

	} // end class

} // end class_exists
