<?php
/**
* @package CembraPay Payment Gateway for WooCommerce
* @author  Adrian Emil Tudorache
* @license GPL-2.0+
* @link    https://www.tudorache.me/
*/

namespace CembraPayWoo;

if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

class WooCommerce {

	function __construct() {
		add_action( 'wp_footer', array( $this, 'threatmetrix' ) );
        add_action( 'woocommerce_check_cart_items', array( $this, 'clear_woocommerce_notices' ) );
        add_action( 'woocommerce_rest_checkout_process_payment_with_context', array( $this, 'clear_woocommerce_notices' ) );
        add_action( 'woocommerce_blocks_loaded', array( $this, 'cembrapay_block_support' ) );
        add_action( 'woocommerce_order_status_changed', array( $this, 'settle' ), 1, 4 );
		add_action( 'woocommerce_order_status_cancelled', array($this, 'cancel'), 1 );
		add_action( 'woocommerce_order_refunded', array( $this, 'refund' ), 10, 2 );
		add_action( 'woocommerce_pay_order_before_payment', array( $this, 'order_pay' ), 10 );
	}

    function clear_woocommerce_notices() {
        if (WC()->session) {
            WC()->session->set('wc_notices', null);
        }
    }

	function threatmetrix() {

		if( is_checkout() && ! is_wc_endpoint_url('order-received') && WC()->session ) {

            $cembrapay_settings = Service::get_payment_gateway_settings();
            $tmx_enabled = $cembrapay_settings['use_tmx'] ?? 0;

            if( ! $tmx_enabled ) {
                return;
            }

			$session_id = Service::get_threatmetrix_session_id();

			Service::load_template( 'front/threatmetrix', array(
				'session_id' => $session_id
			) );

		}

	}

	public function settle( $order_id, $old_status, $new_status, $order ) {

        $cembrapay_settings = Service::get_payment_gateway_settings();
        $settle_status = $cembrapay_settings['settlements_order_status'] ?? 'completed';
        if( ! $settle_status ) {
            $settle_status = 'completed';
        }

        if( $new_status != $settle_status ) {
            return;
        }

		$order = wc_get_order( $order_id );
		$payment_method = $order->get_payment_method();

		$cembrapay = new CembraPay( $order_id );
		
		if( $payment_method == 'cembrapay' ) {
			$cembrapay->set_request_type('settlement');
			$cembrapay->request();
		}

		if( $payment_method == 'byjuno' ) {
			$cembrapay->set_request_type('settlement_byjuno');
			$cembrapay->request();
		}

	}

	public function cancel( $order_id ) {
		
		$order = wc_get_order( $order_id );
		$payment_method = $order->get_payment_method();

		$cembrapay = new CembraPay( $order_id );
		
		if( $payment_method == 'cembrapay' ) {
			$cembrapay->set_request_type('cancel');
			$cembrapay->request();
		}

		if( $payment_method == 'byjuno' ) {
			$cembrapay->set_request_type('cancel_byjuno');
			$cembrapay->request();
		}

	}

	public function refund( $order_id, $refund_id ) {
		
		$order = wc_get_order( $order_id );
		$payment_method = $order->get_payment_method();
		
		if( $payment_method == 'cembrapay' || $payment_method == 'byjuno' ) {

			$cembrapay_settings = Service::get_payment_gateway_settings();
			if( isset( $cembrapay_settings['enable_on_order_refunds'] ) && 1 == $cembrapay_settings['enable_on_order_refunds'] ) {

                $refund               = new \WC_Order_Refund( $refund_id );
                $refund_amount        = floatval( abs( $refund->get_total() ) );
                $order_total          = $order->get_total();
                $order_total_refunded = $order->get_total_refunded();
                $remaining_amount     = $order_total;

                if( $order_total_refunded ) {
                    $remaining_amount = $order_total - $order_total_refunded;
                }

                $update = $order->update_meta_data( '_initial_total', $remaining_amount );
                
				$order->save();

                $payment_method = $order->get_payment_method();

                $action = '';

                switch( $payment_method ) {
                    case 'cembrapay':
						$action = 'credit_note';
                    break;
                    case 'byjuno':
						$action = 'credit_note_byjuno';
                    break;
					default:
						$action = 'credit_note';
                }

				$cembrapay = new CembraPay( $order_id, $action, array( 'refund_id' => $refund_id, 'amount' => $refund_amount ) );
				$cembrapay->request();

			}

		}

	}

	public function order_pay() {

		$cembra_status = isset( $_POST['cembrapay'] ) && $_POST['cembrapay'] ? sanitize_text_field( wp_unslash( $_POST['cembrapay'] ) ) : '';

		if( $cembra_status && $cembra_status == 'error' ) {
		?>
		<div class="woocommerce-notices-wrapper">
			<ul class="woocommerce-error" role="alert" tabindex="-1">
				<li><?php esc_html_e( 'There was an error with the CembraPay payment', 'cembrapay' ); ?></li>
			</ul>
		</div>
		<?php
		}

		if( $cembra_status && $cembra_status == 'cancel' ) {
		?>
		<div class="woocommerce-notices-wrapper">
			<ul class="woocommerce-notice" role="alert" tabindex="-1">
				<li><?php esc_html_e( 'CembraPay payment was cancelled', 'cembrapay' ); ?></li>
			</ul>
		</div>
		<?php
		}

	}

    function cembrapay_block_support() {
		if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
			require_once CEMBRAPATH . 'inc/payment-gateway-blocks.php';
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function( \Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new \WC_Gateway_CembraPay_Blocks() );
				}
			);
		}
	}

}
?>