<?php
/**
 * Receipt Manager
 *
 * Manages receipt generation queue and delivery.
 *
 * @package DonorCore\Receipts
 */

namespace DonorCore\Receipts;

defined( 'ABSPATH' ) || exit;

/**
 * Receipt Manager Class
 */
class Receipt_Manager {

	/**
	 * Action hook for receipt generation.
	 */
	const GENERATE_HOOK = 'donor_core_generate_receipt';

	/**
	 * PDF generator.
	 *
	 * @var PDF_Generator
	 */
	private $pdf_generator;

	/**
	 * Email sender.
	 *
	 * @var Email_Sender
	 */
	private $email_sender;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->pdf_generator = new PDF_Generator();
		$this->email_sender  = new Email_Sender();
	}

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_action( 'woocommerce_payment_complete', array( $this, 'queue_receipt_generation' ), 30, 1 );
		add_action( 'woocommerce_order_status_completed', array( $this, 'queue_receipt_generation' ), 30, 1 );
		add_action( self::GENERATE_HOOK, array( $this, 'generate_and_send' ), 10, 1 );
	}

	/**
	 * Queue receipt generation.
	 *
	 * @param int $order_id Order ID.
	 */
	public function queue_receipt_generation( $order_id ) {
		if ( ! function_exists( 'as_schedule_single_action' ) ) {
			// Fallback: generate immediately.
			$this->generate_and_send( $order_id );
			return;
		}

		// Schedule immediately (async) to send receipt as fast as possible.
		as_schedule_single_action(
			time(),
			self::GENERATE_HOOK,
			array( 'order_id' => $order_id ),
			'donor-core-receipts'
		);
	}

	/**
	 * Generate and send receipt.
	 *
	 * @param int $order_id Order ID.
	 */
	public function generate_and_send( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return;
		}

		// Check if receipt already generated.
		$existing = $order->get_meta( '_donorcore_receipt_path', true );
		if ( $existing && file_exists( $existing ) ) {
			return;
		}

		// Use default universal template
		$template = 'default';

		// Generate PDF.
		$file_path = $this->pdf_generator->generate( $order_id, $template );

		if ( ! $file_path ) {
			return;
		}

		// Store file path.
		$order->update_meta_data( '_donorcore_receipt_path', $file_path );
		$order->update_meta_data( '_donorcore_receipt_generated_at', current_time( 'mysql' ) );
		$order->save();

		// Send email with attachment.
		$this->email_sender->send_receipt_email( $order_id, $file_path );
	}

	/**
	 * Get template name for order.
	 *
	 * @param \WC_Order $order Order object.
	 * @return string
	 */
	private function get_template_for_order( $order ) {
		return 'default';
	}

	/**
	 * Get receipt download URL.
	 *
	 * @param int $order_id Order ID.
	 * @return string|false
	 */
	public function get_download_url( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return false;
		}

		$file_path = $order->get_meta( '_donorcore_receipt_path', true );

		if ( ! $file_path || ! file_exists( $file_path ) ) {
			return false;
		}

		return wp_nonce_url(
			add_query_arg(
				array(
					'action'   => 'donorcore_download_receipt',
					'order_id' => $order_id,
				),
				admin_url( 'admin-ajax.php' )
			),
			'download_receipt_' . $order_id
		);
	}
}
