<?php
/**
 * Attaches invoice PDFs to WooCommerce order emails.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Core;

use PDFDraft\Traits\Hooks;

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

/**
 * Handles attaching generated invoices to order completion emails.
 */
class OrderEmailAttachment {

	use Hooks;

	/**
	 * Invoice service instance.
	 *
	 * @var OrderInvoiceService
	 */
	private OrderInvoiceService $invoiceService;

	/**
	 * Constructor.
	 *
	 * @param OrderInvoiceService $invoiceService Invoice service instance.
	 */
	public function __construct( OrderInvoiceService $invoiceService ) {
		$this->invoiceService = $invoiceService;
	}

	/**
	 * Register WordPress hooks for email attachments.
	 *
	 * @return void
	 */
	public function initHooks(): void {
		$this->addFilter( 'woocommerce_email_attachments', array( $this, 'attachInvoice' ), 10, 3 );
	}

	/**
	 * Attach invoice PDF to the completed order email.
	 *
	 * @param array  $attachments Existing email attachments.
	 * @param string $emailId     WooCommerce email identifier.
	 * @param mixed  $order       WooCommerce order object.
	 * @return array Modified attachments array.
	 */
	public function attachInvoice( array $attachments, string $emailId, $order ): array {
		if ( 'customer_completed_order' !== $emailId ) {
			return $attachments;
		}
		if ( ! $order instanceof \WC_Order ) {
			return $attachments;
		}

		$order_id = $order->get_id();

		if ( ! $this->invoiceService->isGenerated( $order_id ) ) {
			return $attachments;
		}
		$path = $this->invoiceService->getFullInvoicePathForOrder( $order_id );
		if ( null !== $path ) {
			$attachments[] = $path;
		}
		return $attachments;
	}
}
