<?php
/**
 * Enqueues checkout page invoice scripts.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Frontend;

use PDFDraft\Woocommerce\Abstracts\AbstractIntegration;

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

/**
 * Handles invoice script enqueuing on the WooCommerce checkout page.
 */
class CheckoutPage extends AbstractIntegration {

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

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

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

		$handle    = 'pdfdraft-pdf-invoices-for-woocommerce-checkout-invoice';
		$assetPath = PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR . '/dist/checkout-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
		);

		if ( ! in_array( 'jquery', $deps, true ) ) {
			$deps[] = 'jquery';
		}

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

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

	/**
	 * Inject order ID and key into the classic checkout payment result so the
	 * JS can generate the invoice even when the redirect URL points to an
	 * external payment gateway (PayPal, Mollie, etc.) and does not contain
	 * the order ID or key.
	 *
	 * @param array $result   Payment result array passed to wp_send_json().
	 * @param int   $order_id The order ID.
	 * @return array
	 */
	public function injectOrderDataIntoResult( array $result, int $order_id ): array {
		$order = wc_get_order( $order_id );
		if ( $order instanceof \WC_Order ) {
			$result['order_id']  = $order_id;
			$result['order_key'] = $order->get_order_key();
		}
		return $result;
	}

	/**
	 * 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;
	}
}
