<?php
/**
 * Handles functions related to emails.
 */

namespace Flo_Checkout\Gateways\BNPL;

use Flo_Checkout\Gateways\Northmill_BNPL;
use WC_Abstract_Order;
use WC_Order;

/**
 * Class BNPL_Emails
 */
class BNPL_Emails {

	/**
	 * Setup email functions.
	 */
	public static function setup(): void {
		add_action(
			'woocommerce_email_before_order_table',
			array( __CLASS__, 'maybe_add_email_order_email_action' ),
			10,
			2
		);
		add_action(
			'woocommerce_email_after_order_table',
			array( __CLASS__, 'maybe_remove_email_order_email_action' )
		);
	}

	/**
	 * Adds an email order email action if applicable.
	 *
	 * @param WC_Abstract_Order $order         The order object.
	 * @param bool              $sent_to_admin Whether the email is being sent to the admin or not.
	 *
	 * @return void
	 */
	public static function maybe_add_email_order_email_action( WC_Abstract_Order $order, bool $sent_to_admin ): void {
		if ( $order->get_parent_id() ) {
			$order = wc_get_order( $order->get_parent_id() );
		}
		/**
		 * This is an order, not a refund.
		 *
		 * @var WC_Order $order
		 */
		if ( $sent_to_admin ) {
			if ( $order->get_payment_method() === Northmill_BNPL::get_id() ) {
				add_action(
					'woocommerce_get_order_item_totals',
					array( __CLASS__, 'add_bnpl_transaction_id_to_order_details' ),
					10,
					2
				);
			}
		}
	}

	/**
	 * Removes an email order email action if applicable.
	 *
	 * @return void
	 */
	public static function maybe_remove_email_order_email_action(): void {
		remove_action(
			'woocommerce_get_order_item_totals',
			array( __CLASS__, 'add_bnpl_transaction_id_to_order_details' )
		);
	}

	/**
	 * Adds the BNPL transaction ID to the order details array.
	 *
	 * @param array    $total_rows The array of total rows.
	 * @param WC_Order $order      The order object.
	 *
	 * @return array    The updated array of total rows.
	 */
	public static function add_bnpl_transaction_id_to_order_details( array $total_rows, WC_Order $order ): array {
		if ( $order->get_parent_id() ) {
			$order = wc_get_order( $order->get_parent_id() );
		}

		$transaction_id = $order->get_transaction_id();

		if ( $transaction_id ) {
			$new_total_rows = array();

			// Loop through existing rows and insert the new row after the payment method.
			foreach ( $total_rows as $key => $value ) {
				$new_total_rows[ $key ] = $value;

				if ( 'payment_method' === $key ) {
					// Insert the new element after the specified key.
					$new_total_rows['transaction_id'] = array(
						'label' => __( 'Transaction ID', 'flo-checkout-plugin' ),
						'value' => $transaction_id,
					);
				}
			}

			$total_rows = $new_total_rows;
		}

		return $total_rows;
	}
}
