<?php
/**
 * Enqueues invoice scripts on the order-received (thank you) page.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Frontend;

use PDFDraft\Woocommerce\Abstracts\AbstractIntegration;

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

/**
 * Handles invoice script enqueuing on the WooCommerce order-received page.
 */
class OrderReceived extends AbstractIntegration {

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	public function initHooks(): void {
		if ( ! $this->hasActiveDesign() ) {
			return;
		}
		$this->addAction( 'wp_enqueue_scripts', array( $this, 'maybeEnqueueScript' ) );
	}

	/**
	 * Enqueue the order-received invoice script if applicable.
	 *
	 * @return void
	 */
	public function maybeEnqueueScript(): void {
		if ( ! is_wc_endpoint_url( 'order-received' ) ) {
			return;
		}

		$order_id = (int) get_query_var( 'order-received' );
		if ( ! $order_id ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$order_key = sanitize_text_field( wp_unslash( $_GET['key'] ?? '' ) );
		if ( ! $order_key ) {
			return;
		}

		$scriptPath = PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR . '/dist/order-received-invoice.js';
		if ( ! file_exists( $scriptPath ) ) {
			return;
		}

		$handle    = 'pdfdraft-pdf-invoices-for-woocommerce-order-received-invoice';
		$assetPath = PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR . '/dist/order-received-invoice.asset.php';
		$asset     = file_exists( $assetPath ) ? require $assetPath : array(
			'dependencies' => array(),
			'version'      => (string) filemtime( $scriptPath ),
		);

		$deps = array_filter(
			$asset['dependencies'],
			static fn( $dep ) => 'wp-react-refresh-runtime' !== $dep
		);

		wp_enqueue_script(
			$handle,
			PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_URL . '/dist/order-received-invoice.js',
			array_values( $deps ),
			$asset['version'],
			true
		);

		wp_localize_script(
			$handle,
			'__PDFDRAFT_ORDER_RECEIVED__',
			array(
				'restUrl'  => esc_url_raw( rest_url( 'pdfdraft-pdf-invoices-for-woocommerce/v1' ) ),
				'nonce'    => wp_create_nonce( 'wp_rest' ),
				'orderId'  => $order_id,
				'orderKey' => $order_key,
			)
		);
	}

	/**
	 * Check whether an active invoice design is configured.
	 *
	 * @return bool
	 */
	private function hasActiveDesign(): bool {
		$slug = get_option( 'pdfdraft_pdf_invoices_for_woocommerce_active_design_slug', '' );
		return is_string( $slug ) && '' !== $slug;
	}
}
