<?php
/**
 * Adds invoice download column to the My Account orders page.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Frontend;

use PDFDraft\Woocommerce\Abstracts\AbstractIntegration;
use PDFDraft\Woocommerce\Core\Assets;
use PDFDraft\Woocommerce\Core\PdfSettingsOption;

/**
 * Integrates invoice downloads into the WooCommerce My Account page.
 */
class MyAccount extends AbstractIntegration {

	/**
	 * Assets service instance.
	 *
	 * @var Assets
	 */
	private Assets $assets;

	/**
	 * Settings option service instance.
	 *
	 * @var PdfSettingsOption
	 */
	private PdfSettingsOption $settingsOption;

	/**
	 * Initialize the MyAccount integration.
	 *
	 * @param Assets            $assets         Assets service.
	 * @param PdfSettingsOption $settingsOption Settings option service.
	 */
	public function __construct( Assets $assets, PdfSettingsOption $settingsOption ) {
		$this->assets         = $assets;
		$this->settingsOption = $settingsOption;
	}

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	public function initHooks() {
		if ( ! $this->hasActiveDesign() ) {
			return;
		}

		$settings      = $this->settingsOption->get();
		$show_button   = (bool) ( $settings['general']['invoice_settings']['show_my_account_download_button'] ?? true );

		if ( ! $show_button ) {
			return;
		}

		$this->addFilter( 'woocommerce_account_orders_columns', array( $this, 'addInvoiceColumn' ) );
		$this->addAction( 'woocommerce_my_account_my_orders_column_pdfdraft-invoice', array( $this, 'renderInvoiceButton' ) );
		$this->addFilter( 'woocommerce_my_account_my_orders_actions', array( $this, 'addInvoiceToOrderActions' ), 10, 2 );
		$this->addFilter( 'woocommerce_locate_template', array( $this, 'locateOrderDetailsTemplate' ), 10, 4 );
		$this->addAction( 'pdfdraft_pdf_invoices_for_woocommerce_order_details_invoice_action', array( $this, 'renderOrderDetailsInvoiceButton' ) );
		$this->addAction( 'wp_enqueue_scripts', array( $this, 'maybeEnqueueAssets' ) );
	}

	/**
	 * Add the invoice column to the My Account orders table.
	 *
	 * @param array $columns Existing table columns.
	 * @return array Modified table columns.
	 */
	public function addInvoiceColumn( $columns ) {
		$new_columns = array();
		foreach ( $columns as $key => $label ) {
			$new_columns[ $key ] = $label;
			if ( 'order-status' === $key ) {
				$new_columns['pdfdraft-invoice'] = __( 'Invoice', 'pdfdraft-pdf-invoices-for-woocommerce' );
			}
		}
		// Fallback if order-status column not found.
		if ( ! isset( $new_columns['pdfdraft-invoice'] ) ) {
			$new_columns['pdfdraft-invoice'] = __( 'Invoice', 'pdfdraft-pdf-invoices-for-woocommerce' );
		}
		return $new_columns;
	}

	/**
	 * Render the invoice download button for a given order row.
	 *
	 * @param \WC_Order $order The order object.
	 * @return void
	 */
	public function renderInvoiceButton( $order ) {
		if ( ! $order instanceof \WC_Order ) {
			return;
		}
		$this->renderTemplate(
			'invoice-download-button.php',
			array(
				'order_id' => $order->get_id(),
				'context'  => 'my-account',
				'type'     => 'icon',
				'size'     => 'small',
			)
		);
	}

	/**
	 * Add native WooCommerce “Invoice” action next to Pay / Cancel in the order Actions row (view-order only).
	 *
	 * The Actions cell is rendered by our `order-details.php` override: PDFDraft markup replaces this entry.
	 *
	 * @param array     $actions Order actions.
	 * @param \WC_Order $order   Order object.
	 * @return array
	 */
	public function addInvoiceToOrderActions( $actions, $order ) {
		if ( ! $order instanceof \WC_Order ) {
			return $actions;
		}
		// Orders list already has the dedicated Invoice column; avoid duplicate buttons there.
		if ( ! is_wc_endpoint_url( 'view-order' ) ) {
			return $actions;
		}
		$order_id = $order->get_id();
		$url      = $order->get_view_order_url() . '#pdfdraft-invoice-' . absint( $order_id );

		$actions['pdfdraft_invoice'] = array(
			'url'        => esc_url( $url ),
			'name'       => __( 'Invoice', 'pdfdraft-pdf-invoices-for-woocommerce' ),
			'aria-label' => sprintf(
				/* translators: %s: order number */
				__( 'Download invoice for order %s', 'pdfdraft-pdf-invoices-for-woocommerce' ),
				$order->get_order_number()
			),
		);

		return $actions;
	}

	/**
	 * Use plugin order-details template on My Account → view order so the invoice action can render PDFDraft UI.
	 *
	 * @param string $template      Located template path.
	 * @param string $template_name Template name.
	 * @param string $template_path Relative path (unused).
	 * @param string $default_path  WooCommerce core templates directory.
	 * @return string
	 */
	public function locateOrderDetailsTemplate( $template, $template_name, $template_path, $default_path = '' ) {
		if ( 'order/order-details.php' !== $template_name ) {
			return $template;
		}
		if ( ! is_account_page() || ! is_wc_endpoint_url( 'view-order' ) ) {
			return $template;
		}
		if ( ! $this->hasActiveDesign() ) {
			return $template;
		}

		$core_default  = trailingslashit( '' !== $default_path ? $default_path : \WC()->plugin_path() . '/templates/' ) . $template_name;
		$core_norm     = wp_normalize_path( $core_default );
		$template_norm = is_string( $template ) ? wp_normalize_path( $template ) : '';
		// Respect theme / child theme overrides.
		if ( '' !== $template_norm && $template_norm !== $core_norm && file_exists( $template ) ) {
			return $template;
		}

		$our = PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR . 'templates/woocommerce/order/order-details.php';
		if ( file_exists( $our ) ) {
			return $our;
		}

		return $template;
	}

	/**
	 * Invoice control in the Actions row: same template as admin order edit (filename when stored, else Download Invoice).
	 *
	 * @param \WC_Order $order Order.
	 * @return void
	 */
	public function renderOrderDetailsInvoiceButton( $order ) {
		if ( ! $order instanceof \WC_Order ) {
			return;
		}
		$order_id     = $order->get_id();
		$download_url = rest_url( 'pdfdraft-pdf-invoices-for-woocommerce/v1/orders/' . $order_id . '/invoice' );
		$download_url = apply_filters( 'pdfdraft_pdf_invoices_for_woocommerce_invoice_download_url', $download_url, $order_id );
		$args         = array(
			'order_id'      => $order_id,
			'context'       => 'my-account',
			'wrap_modifier' => 'view-order',
			'type'          => 'both',
			'text'          => __( 'Download Invoice', 'pdfdraft-pdf-invoices-for-woocommerce' ),
			'size'          => 'medium',
			'download_url'  => $download_url,
		);
		$args         = apply_filters( 'pdfdraft_pdf_invoices_for_woocommerce_invoice_download_button_args', $args, $order );
		$this->renderTemplate( 'invoice-download-button.php', $args );
	}

	/**
	 * Enqueue invoice download scripts and styles on the My Account page.
	 *
	 * @return void
	 */
	public function maybeEnqueueAssets(): void {
		if ( ! is_account_page() ) {
			return;
		}
		$this->assets->enqueueInvoiceDownloadScriptStyle();
	}

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