<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class WC_Verifone_Plugin_Compatibility {
	public function WC_Verifone_Data_collectData( $data, $order ) {
		if ( class_exists( 'PW_Gift_Cards' ) ) {
			$data = self::pw_gift_cards_order_data_fix_totals_and_vat( $data, $order );
		}

		if ( class_exists( 'WC_Verifone_Woocommerce_Subscriptions' ) && WC_Verifone_Woocommerce_Subscriptions::order_contains_subscription( $order ) ) {
			$data = WC_Verifone_Woocommerce_Subscriptions::collect_recurring_payment_data( $data, $order );
		}

		return $data;
	}

	/**
	 * Fix situations where order total excluding tax is negative due to the use of gift cards.
	 * @see eve-36696
	 *
	 * @param array $data Data to be sent
	 * @param WC_Order $order Order object
	 * @return array Modified data to be sent
	 */
	private function pw_gift_cards_order_data_fix_totals_and_vat( $data, $order ) {
		// Check that order has gift cards set by the plugin
		if ( 0 === count( $order->get_items( 'pw_gift_card' ) ) ) {
			return $data;
		}

		// Check that the amount excluding tax is negative
		if ( $data['total_excl_amount'] < 0 ) {
			$data['total_tax'] = 0; // Force tax to 0
			$data['total_excl_amount'] = $data['total_incl_amount']; // Force total excluding tax to be same as including tax
		}

		return $data;
	}
}

new WC_Verifone_Plugin_Compatibility();
