<?php

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

use \Verifone\Core\DependencyInjection\Configuration\Backend\BackendConfigurationImpl;
use \Verifone\Core\DependencyInjection\Configuration\Backend\GetAvailablePaymentMethodsConfigurationImpl;
use \Verifone\Core\DependencyInjection\Configuration\Frontend\RedirectUrlsImpl;
use \Verifone\Core\DependencyInjection\Configuration\Frontend\FrontendConfigurationImpl;
use \Verifone\Core\DependencyInjection\Service\CustomerImpl;
use \Verifone\Core\DependencyInjection\Service\OrderImpl;

class WC_Verifone_Core
{
    /**
     * @return BackendConfigurationImpl
     */
    public static function getBackedConfigObject()
    {

        $config = WC_Verifone_Config::getInstance();

        $merchant = $config->getMerchantAgreement();
        $keyFile = $config->getShopPrivateKeyFile();

        $configObject = new BackendConfigurationImpl(
            $keyFile,
            $merchant,
            WC_Verifone_System::getSystemName(),
            WC_Verifone_System::getVersion(),
            WC_Verifone_Urls::getUrls('server'),
            $config->isDisableRsaBlinding()
        );

        return $configObject;
    }

    /**
     * @return GetAvailablePaymentMethodsConfigurationImpl
     */
    public static function getAvailablePaymentMethodsConfigObject()
    {
        $config = WC_Verifone_Config::getInstance();

        $merchant = $config->getMerchantAgreement();
        $keyFile = $config->getShopPrivateKeyFile();

        $configObject = new GetAvailablePaymentMethodsConfigurationImpl(
            $keyFile,
            $merchant,
            WC_Verifone_System::getSystemName(),
            WC_Verifone_System::getVersion(),
            WC_Verifone_Urls::getUrls('server'),
            WC_Verifone_System::getCurrencyNumber(),
            $config->isDisableRsaBlinding()
        );

        return $configObject;
    }

    /**
     * @param RedirectUrlsImpl $urls
     * @return FrontendConfigurationImpl
     */
    public static function getFrontendConfigObject(RedirectUrlsImpl $urls)
    {
        $config = WC_Verifone_Config::getInstance();

        $merchant = $config->getMerchantAgreement();
        $keyFile = $config->getShopPrivateKeyFile();

        $configObject = new FrontendConfigurationImpl(
            $urls,
            $keyFile,
            $merchant,
            WC_Verifone_System::getSystemName(),
            WC_Verifone_System::getVersion(),
            (string)$config->isSkipConfirmationPage(),
            $config->isDisableRsaBlinding(),
            $config->getStyleCode()
        );

        return $configObject;
    }

    /**
     * @param $customerData
     * @param null $address
     * @return CustomerImpl
     */
    public static function createCustomerObject( $customerData, $address = null ) {
        $customer = new CustomerImpl(
            sanitize_text_field( $customerData['firstname'] ),
            sanitize_text_field( $customerData['lastname'] ),
            sanitize_text_field( $customerData['phone'] ),
            sanitize_email( $customerData['email'] ),
            $address,
            isset( $customerData['external_id'] ) && $customerData['external_id'] ? (string)$customerData['external_id'] : ''
        );

        return $customer;
    }

    public static function createOrderObject($orderData)
    {
        $order = new OrderImpl(
            (string)$orderData['order_id'],
            $orderData['time'],
            (string)$orderData['currency_code'],
            (string)$orderData['total_incl_amount'],
            (string)$orderData['total_excl_amount'],
            (string)$orderData['total_tax']
        );

        return $order;
    }

    public static function getRedirectUrlsObject( $isCard = false, $links_override = [] )
    {

        if(!$isCard) {
            $link = WC_Verifone_Urls::getPaymentLink();
        } else {
            $link = WC_Verifone_Urls::getCardLink();
        }

		$links = [
			'success'  => add_query_arg( 'status', 'success', $link ),
			'rejected' => add_query_arg( 'status', 'rejected', $link ),
			'cancel'   => add_query_arg( 'status', 'cancel', $link ),
			'expired'  => add_query_arg( 'status', 'expired', $link ),
			'error'    => add_query_arg( 'status', 'error', $link ),
		];

		// Allow overriding the default links if needed
		if ( ! empty( $links_override ) && is_array( $links_override ) ) {
			foreach ( $links_override as $key => $value ) {
				if ( array_key_exists( $key, $links ) && ! empty( $value ) ) {
					$links[ $key ] = $value;
				}
			}
		}

        $urls = new RedirectUrlsImpl(
            $links['success'],
            $links['rejected'],
            $links['cancel'],
            $links['expired'],
            $links['error']
        );

        return $urls;
    }

    public static function renderRequestForm($formData)
    {
        $action = $formData['action'];
        unset($formData['action']);

        $message = esc_html__('Redirecting to Verifone Payment', 'verifone-bluecommerce-for-woocommerce') . '...';

		// If in test mode, add IP allowlisting info to redirect message
		if (!WC_Verifone_Config::getInstance()->isLiveMode()) {
			$message .= '<br><br><b>' . esc_html__( 'If you are not redirected:', 'verifone-bluecommerce-for-woocommerce' ) . '</b>';
			$message .=  '<br>' . esc_html__( 'You are using test envarionment.', 'verifone-bluecommerce-for-woocommerce' );
			/** translators: 1: Link to ipinfo.io, 2: closing link tag */
			$message .=  ' ' . wp_sprintf( esc_html__( 'To test and complete payment process, the IP address of the network you are using needs to be allowlisted. Find your IP address with %1$sipinfo.io%2$s.', 'verifone-bluecommerce-for-woocommerce' ), '<a href="https://ipinfo.io/ip">', '</a>' );
			$message .=  '<br>' . esc_html__( 'Please contact Verifone support to get your IP addresses allowlisted.', 'verifone-bluecommerce-for-woocommerce' );
		}

        $context = [
            'action' => $action,
            'redirectMessage' => $message,
            'formData' => $formData
        ];

        WC_Verifone_Tpl::render($context, WC_Verifone_Tpl::REQUEST_FORM);

        return true;
    }
}
