<?php
/**
 * Automatic invoice generation on order completion.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Core;

use PDFDraft\Traits\Hooks;

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

/**
 * Generates invoices automatically when orders are marked completed.
 */
class OrderInvoiceGenerator {

	use Hooks;

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

	/**
	 * PDF settings option instance.
	 *
	 * @var PdfSettingsOption
	 */
	private PdfSettingsOption $settings;

	/**
	 * Constructor.
	 *
	 * @param OrderInvoiceService $orderInvoiceService Invoice service instance.
	 * @param PdfSettingsOption   $settings            PDF settings option instance.
	 */
	public function __construct(
		OrderInvoiceService $orderInvoiceService,
		PdfSettingsOption $settings
	) {
		$this->orderInvoiceService = $orderInvoiceService;
		$this->settings            = $settings;
	}

	/**
	 * Register WordPress hooks for automatic invoice generation.
	 *
	 * @return void
	 */
	public function initHooks(): void {
		$this->addAction( 'woocommerce_order_status_completed', array( $this, 'onOrderStatusCompleted' ), 10, 2 );
	}

	/**
	 * Handle order status change to completed.
	 *
	 * @param int   $orderId Order ID.
	 * @param mixed $order   WooCommerce order object or null.
	 * @return void
	 */
	public function onOrderStatusCompleted( int $orderId, $order = null ): void {
		$settings = $this->settings->get();
		$mode     = $settings['general']['invoice_settings']['generation_mode'] ?? 'automatic';
		if ( 'automatic' !== $mode ) {
			return;
		}
		// Use isReserved() — not isGenerated() — so we skip placeholder creation
		// if a path has already been assigned, even before the real PDF is uploaded.
		// isGenerated() returns false for placeholder PDFs by design, which would
		// otherwise cause a second placeholder to be created on every page load.
		if ( $this->orderInvoiceService->isReserved( $orderId ) ) {
			return;
		}
		$order = $order instanceof \WC_Order ? $order : wc_get_order( $orderId );
		if ( ! $order instanceof \WC_Order ) {
			return;
		}

		// Skip free orders if the setting is enabled.
		$disable_free = (bool) ( $settings['general']['invoice_settings']['disable_free_order_invoices'] ?? false );
		if ( $disable_free && (float) $order->get_total() <= 0 ) {
			return;
		}

		$result = $this->orderInvoiceService->generateForOrder( $order );
		if ( is_wp_error( $result ) ) {
			// Log or ignore; do not block order completion.
			if ( function_exists( 'wc_get_logger' ) ) {
				wc_get_logger()->warning( 'PDFDraft: automatic invoice generation failed: ' . $result->get_error_message(), array( 'source' => 'pdfdraft-pdf-invoices-for-woocommerce' ) );
			}
		}
	}
}
