<?php
/**
 * Invoice Download Button Template
 *
 * @var int    $order_id     Order ID (required)
 * @var string $context      Context (orders-table, order-edit, my-account)
 * @var string $type         Button type ('icon', 'text', 'both') - default: 'icon'
 * @var string $text         Button text - default: 'Download invoice'
 * @var string $size         Button size ('small', 'medium', 'large') - default: 'medium'
 * @var array  $classes      Additional CSS classes
 * @var bool   $disabled     Whether button is disabled
 * @var string $tooltip       Tooltip text - default: 'Download invoice'
 * @var string $download_url   Optional full download URL (filtered); when set, script uses it instead of building from base + order_id.
 * @var string $wrap_modifier  BEM suffix for .PDFDraft-Invoice-Wrap--{x} (visual layout); defaults to $context. Use e.g. view-order to match admin styling while keeping data-context for REST.
 * @var bool   $show_delete_invoice When true and invoice exists, show admin delete control (order edit).
 * @var string $delete_url          REST URL for DELETE invoice (admin).
 */
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Template variables are file scope only (passed via renderTemplate); not registered WordPress globals.

$order_id            = $order_id ?? 0;
$download_url        = $download_url ?? '';
$context             = $context ?? 'default';
$wrap_modifier       = isset( $wrap_modifier ) && is_string( $wrap_modifier ) && '' !== $wrap_modifier
	? $wrap_modifier
	: $context;
$type                = $type ?? 'icon'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$text                = $text ?? __( 'Download invoice', 'pdfdraft-pdf-invoices-for-woocommerce' );
$classes             = $classes ?? array();
$disabled            = $disabled ?? false;
$tooltip             = $tooltip ?? __( 'Download invoice', 'pdfdraft-pdf-invoices-for-woocommerce' );
$show_delete_invoice = ! empty( $show_delete_invoice );
$delete_url          = isset( $delete_url ) && is_string( $delete_url ) ? $delete_url : '';

// Check if invoice has already been generated.
$invoice_filename = '';
if ( $order_id ) {
	$order_obj_meta = wc_get_order( $order_id );
	if ( $order_obj_meta instanceof \WC_Order ) {
		$is_generated = $order_obj_meta->get_meta( 'pdfdraft_is_invoice_generated' );
		if ( $is_generated === 'true' || $is_generated === true ) {
			$invoice_filename = $order_obj_meta->get_meta( 'pdfdraft_invoice_path' );
		}
	}
}

$has_invoice = $invoice_filename !== '';

$button_classes = array(
	'PDFDraft-Invoice-Download-Button',
	'PDFDraft-Button-' . $context,
	'PDFDraft-Button-' . $type,
);

if ( 'orders-table' === $context ) {
	$button_classes[] = 'help_tip';
}

if ( $disabled ) {
	$button_classes[] = 'disabled';
}

$button_classes = array_merge( $button_classes, $classes );
$css_classes    = implode( ' ', $button_classes );

$button_attrs = array(
	'type'          => 'button',
	'class'         => esc_attr( $css_classes ),
	'data-order-id' => esc_attr( (string) $order_id ),
	'data-context'  => esc_attr( $context ),
	'data-nonce'    => esc_attr( wp_create_nonce( 'pdfdraft_download_' . $order_id ) ),
);
if ( $download_url !== '' ) {
	$button_attrs['data-download-url'] = esc_url( $download_url );
	$button_attrs['href']              = esc_url( $download_url );
}

if ( 'icon' === $type || ! empty( $tooltip ) ) {
	$button_attrs['data-tip'] = esc_attr( $tooltip );
}

if ( $disabled ) {
	$button_attrs['disabled'] = 'disabled';
}

$attrs_string = '';
foreach ( $button_attrs as $key => $value ) {
	$attrs_string .= sprintf( ' %s="%s"', esc_attr( $key ), esc_attr( $value ) );
}

// Download icon SVG.
$download_icon = '<svg class="PDFDraft-Button-Icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15V3" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="m7 10 5 5 5-5" /></svg>';

// Spinner SVG.
$spinner = '<span class="PDFDraft-Button-Spinner" style="display: none;" aria-hidden="true"><svg class="pdfdraft-spinner-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 11-6.219-8.56"/></svg></span>';
?>

<?php if ( $has_invoice ) : ?>
	<div
		class="PDFDraft-Invoice-Wrap PDFDraft-Invoice-Wrap--<?php echo esc_attr( $context ); ?> PDFDraft-Invoice-Wrap--has-invoice"
		<?php echo ( $show_delete_invoice && '' !== $delete_url ) ? ' data-show-delete-invoice="1" data-delete-url="' . esc_attr( $delete_url ) . '"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
	>
		<div class="PDFDraft-Invoice-Row">
			<a<?php echo $attrs_string; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
				<span class="PDFDraft-Invoice-Filename"><?php echo esc_html( basename( $invoice_filename ) ); ?></span>
				<?php echo $download_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<?php echo $spinner; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<span class="screen-reader-text"><?php echo esc_html( $tooltip ); ?></span>
			</a>
			<?php if ( $show_delete_invoice && '' !== $delete_url ) : ?>
				<?php
				$delete_label = __( 'Remove stored invoice', 'pdfdraft-pdf-invoices-for-woocommerce' );
				?>
				<button
					type="button"
					class="PDFDraft-Invoice-Delete-Button"
					data-order-id="<?php echo esc_attr( (string) $order_id ); ?>"
					data-delete-url="<?php echo esc_url( $delete_url ); ?>"
					aria-label="<?php echo esc_attr( $delete_label ); ?>"
					title="<?php echo esc_attr( $delete_label ); ?>"
				>
					<span class="screen-reader-text"><?php echo esc_html( $delete_label ); ?></span>
					<svg class="PDFDraft-Invoice-Delete-Icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
				</button>
			<?php endif; ?>
		</div>
	</div>
<?php else : ?>
	<div
		class="PDFDraft-Invoice-Wrap PDFDraft-Invoice-Wrap--<?php echo esc_attr( $wrap_modifier ); ?>"
		<?php echo ( $show_delete_invoice && '' !== $delete_url ) ? ' data-show-delete-invoice="1" data-delete-url="' . esc_attr( $delete_url ) . '"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
	>
		<a<?php echo $attrs_string; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
			<?php if ( 'icon' === $type || 'both' === $type ) : ?>
				<?php echo $download_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php endif; ?>

			<?php if ( 'text' === $type || 'both' === $type ) : ?>
				<span class="PDFDraft-Button-Text"><?php echo esc_html( $text ); ?></span>
			<?php endif; ?>

			<span class="screen-reader-text"><?php echo esc_html( $tooltip ); ?></span>
			<?php echo $spinner; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		</a>
	</div>
<?php endif; ?>
