<?php
/**
 * Invoice Template Functions.
 *
 * @package     EDD\Pro\Invoices
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.5.0
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * Outputs the invoice title.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_title( $order ) {
	?>
	<!-- Title -->
	<?php
	printf(
		'<title>%s</title>',
		sprintf(
			/* translators: the invoice number */
			esc_html__( 'Invoice #%s', 'easy-digital-downloads' ),
			esc_html( edd_get_payment_number( $order->id ) )
		)
	);
}
add_action( 'edd_invoices_invoice_head', 'edd_invoices_do_invoice_title' );

/**
 * Loads the invoice stylesheet.
 *
 * @since 3.5.0
 * @return void
 */
function edd_invoices_load_stylesheet() {
	wp_enqueue_style( 'edd-invoice', edd_get_assets_url( 'pro/css/invoice' ) . 'style.min.css', array(), edd_admin_get_script_version(), 'all' );
	$color = edd_get_option( 'edd-invoices-color' );
	if ( $color ) {
		$css = sprintf(
			':root{--accent-color:%1$s;--accent-color-rgba:rgba(%2$s,.2);--border-color:%1$s;}',
			$color,
			edd_invoices_convert_hex_to_rgb( $color )
		);
		wp_add_inline_style( 'edd-invoice', $css );
	}
	wp_print_styles( 'edd-invoice' );
}
add_action( 'edd_invoices_invoice_head', 'edd_invoices_load_stylesheet', 15 );

/**
 * Converts a hex color to RGB for use with rgba in CSS.
 *
 * @since 3.5.0
 * @param string $color The hex color.
 * @return string
 */
function edd_invoices_convert_hex_to_rgb( $color ) {
	$hexcolor = str_replace( '#', '', $color );
	$rgb      = array();
	$rgb[]    = hexdec( substr( $hexcolor, 0, 2 ) );
	$rgb[]    = hexdec( substr( $hexcolor, 2, 2 ) );
	$rgb[]    = hexdec( substr( $hexcolor, 4, 2 ) );

	return implode( ',', $rgb );
}

/**
 * Outputs the invoice logo, if set.
 *
 * @since 3.5.0
 * @return void
 */
function edd_invoices_do_invoice_logo() {
	$logo = edd_get_option( 'edd-invoices-logo' );
	if ( ! $logo ) {
		return;
	}
	?>
	<!-- Logo -->
	<div class="logo">
		<img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>"/>
	</div>
	<?php
}
add_action( 'edd_invoices_invoice_header', 'edd_invoices_do_invoice_logo' );

/**
 * Outputs the invoice number as the heading.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_order_heading( $order ) {
	?>
	<!-- Invoice Details -->
	<div class="invoice-details">
		<div class="order-number">
			<?php
			printf(
				'<h1>%s</h1>',
				sprintf(
					/* translators: the invoice number */
					esc_html__( 'Invoice %s', 'easy-digital-downloads' ),
					esc_html( edd_get_payment_number( $order->id ) )
				)
			);
			?>

			<?php
			switch ( $order->status ) {
				case 'publish':
				case 'complete':
				case 'edd_subscription':
					$status_label = __( 'Paid', 'easy-digital-downloads' );
					break;

				case 'refunded':
					$status_label = __( 'Refunded', 'easy-digital-downloads' );
					break;

				case 'partially_refunded':
					$status_label = __( 'Partially Refunded', 'easy-digital-downloads' );
					break;

				default:
					$status_label = false;
			}

			if ( $status_label ) {
				printf(
					'<div class="payment-status-badge payment-%s">%s</div>',
					esc_attr( $order->status ),
					esc_html( $status_label )
				);
			}
			?>
		</div>

		<?php
		$date = edd_invoices_get_order_date( $order );
		if ( $date ) {
			?>
			<div class="date">
				<!-- Purchase Date -->
				<?php
				$date_format   = get_option( 'date_format' );
				$purchase_date = edd_date_i18n( $date, get_option( 'date_format' ) );

				/* Translators: %s - Date of purchase */
				printf( esc_html__( 'Purchase Date: %s', 'easy-digital-downloads' ), esc_html( $purchase_date ) );
				?>
			</div>
			<?php
		}
		?>
	</div>
	<?php
}
add_action( 'edd_invoices_invoice_header', 'edd_invoices_do_invoice_order_heading', 11 );

/**
 * Outputs the storefront and customer contact information.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_contacts( $order ) {
	edd_get_template_part( 'invoice/invoice-contacts' );
}
add_action( 'edd_invoices_invoice_contacts', 'edd_invoices_do_invoice_contacts' );

/**
 * Outputs the invoice items table.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_items_table( $order ) {
	edd_get_template_part( 'invoice/invoice-table' );
}
add_action( 'edd_invoices_invoice_items_table', 'edd_invoices_do_invoice_items_table' );

/**
 * Outputs the additional info section for the invoice.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_invoice_do_additional_info( $order ) {
	edd_get_template_part( 'invoice/invoice-additional-info' );
}
add_action( 'edd_invoices_invoice_additional_info', 'edd_invoices_invoice_do_additional_info' );

/**
 * Outputs action buttons (print, back) for the invoice.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_action_buttons( $order ) {
	$home_button = ! empty( $_GET['home'] );
	?>
	<div class="invoice-actions" data-html2canvas-ignore>
		<?php
		if ( $home_button ) {
			?>
			<a class="button home" href="<?php echo esc_url( home_url() ); ?>"><?php esc_html_e( 'Home', 'easy-digital-downloads' ); ?></a>
			<?php
		} else {
			?>
			<button class="button back" onclick="window.history.back()"><?php esc_html_e( 'Back', 'easy-digital-downloads' ); ?></button>
			<?php
		}
		?>
		<button class="button print" onclick="window.print()"><?php esc_html_e( 'Print', 'easy-digital-downloads' ); ?></button>
		<button class="button pdf" data-name="<?php echo esc_attr( edd_invoices_get_pdf_filename( $order->id ) ); ?>"><?php esc_html_e( 'Download PDF', 'easy-digital-downloads' ); ?></button>
		<?php
		if ( edd_get_option( 'edd-invoices-ubl', false ) ) {
			$url = add_query_arg( array( 'edd_action' => 'invoices_generate_xml' ) );
			?>
			<a class="button ubl" href="<?php echo esc_url( $url ); ?>">
					<?php esc_html_e( 'Download Electronic Invoice', 'easy-digital-downloads' ); ?>
			</a>
			<?php
		}
		?>
	</div>
	<?php
}
add_action( 'edd_invoices_invoice_footer', 'edd_invoices_do_invoice_action_buttons', 20 );

/**
 * If the current user can edit the invoice, output an edit button.
 *
 * @since 3.5.0
 * @param \EDD\Orders\Order|EDD_Payment $order The order/payment object.
 * @return void
 */
function edd_invoices_do_invoice_edit_button( $order ) {
	if ( ! edd_invoices_can_user_edit_invoice_data( get_current_user_id() ) ) {
		return;
	}
	?>
	<a href="<?php echo esc_url( edd_invoices_get_invoice_form_url( $order->id ) ); ?>" class="button hide-on-print" data-html2canvas-ignore>
		<?php
		printf(
			/* Translators: %1$s - opening <span> tag; %2$s - closing </span> tag */
			__( 'Update %1$sbilling information%2$s', 'easy-digital-downloads' ),
			'<span class="screen-reader-text">',
			'</span>'
		);
		?>
	</a>
	<?php
}

/**
 * Enqueues and loads the scripts needed to generate PDF invoices.
 *
 * @since 1.3
 * @return void
 */
function edd_invoices_load_pdf_scripts() {
	edd_invoices_register_pdf_scripts();
	wp_print_scripts( 'edd-invoices-pdf' );
}
add_action( 'edd_invoices_invoice_head', 'edd_invoices_load_pdf_scripts' );

/**
 * Registers the scripts needed to generate PDF invoices.
 *
 * @return void
 */
function edd_invoices_register_pdf_scripts() {
	$minify = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
	wp_register_script( 'html2pdf', edd_get_assets_url( 'vendor/pro' ) . "html2pdf.bundle{$minify}.js", array(), '0.9.3', true );
	wp_register_script( 'edd-invoices-pdf', edd_get_assets_url( 'pro/js/invoice' ) . 'invoices-pdf.js', array( 'html2pdf' ), edd_admin_get_script_version(), true );
	wp_localize_script(
		'edd-invoices-pdf',
		'eddInvoicesPDF',
		edd_invoices_get_localization_options()
	);
}

/**
 * Returns the options passed to the edd-invoices-pdf.js script.
 *
 * @since 1.4.0
 * @return array
 */
function edd_invoices_get_localization_options() {
	/**
	 * Filters the options passed to the edd-invoices-pdf.js script.
	 *
	 * @since 1.4.0
	 * @param array $options The array of options passed to the edd-invoices-pdf.js script.
	 */
	return apply_filters(
		'edd_invoices_pdf_options',
		array(
			'html2pdf' => array(
				'margin'      => array( 1, 1 ),
				'image'       => array(
					'type'    => 'jpeg',
					'quality' => 0.98,
				),
				'html2canvas' => array(
					'scale'           => 2,
					'letterRendering' => true,
				),
				'jsPDF'       => array(
					'unit'        => 'in',
					'format'      => 'letter',
					'orientation' => 'portrait',
				),
			),
		)
	);
}

/**
 * Adds the EDD Invoices templates directory to the stack.
 *
 * @param array $paths Array of template directories.
 *
 * @deprecated 3.5.0
 * @return array
 */
function edd_invoices_add_template_stack( $paths ) {
	return $paths;
}
