<?php
namespace Svea_Webpay_For_Woocommerce;

use Svea\WebPay\WebPay;
use Svea_Webpay_For_Woocommerce\Gateways\WC_Gateway_Abstract;
use Svea_Webpay_For_Woocommerce\Gateways\WC_Gateway_Svea_Invoice;
use Svea_Webpay_For_Woocommerce\Gateways\WC_Gateway_Svea_Part_Pay;

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

/**
 * Class to handle ajax requests for the Svea plugin
 */
class Ajax_Functions {

	/**
	 * Nonce name, used for securing ajax-requests
	 *
	 * @var string
	 */
	const GET_ADDRESS_NONCE_NAME = 'svea_get_address';

	/**
	 * Initialize the class
	 *
	 * @return void
	 */
	public function init() {
		add_action( 'wp_ajax_svea_get_address', [ $this, 'get_address' ] );
		add_action( 'wp_ajax_nopriv_svea_get_address', [ $this, 'get_address' ] );
	}

	/**
	 * Fetch address credentials from Svea and present as json
	 *
	 * @return void
	 */
	public function get_address() {
		if ( ! check_ajax_referer( self::GET_ADDRESS_NONCE_NAME, 'security' ) ) {
			die();
		}

		if ( ! isset( $_POST['payment_type'] ) ) {
			die();
		}

		$payment_method = sanitize_text_field( wp_unslash( $_POST['payment_type'] ) );

		$wc_gateway = WC_Gateway_Abstract::get_gateway_instance( $payment_method );

		if ( ! $wc_gateway ) {
			exit;
		}

		$wc_gateway::log( 'Getting address' );

		if ( ! isset( $_POST['pers_nr'] ) && ! isset( $_POST['org_nr'] ) ) {
			$wc_gateway::log( 'No organisation or personal number set' );
			die();
		}

		if ( ! isset( $_POST['country_code'] ) ) {
			$wc_gateway::log( 'No country code set' );
			die();
		}

		$customer_country = strtoupper( sanitize_text_field( wp_unslash( $_POST['country_code'] ) ) );

		$customer_type = isset( $_POST['pers_nr'] ) ? 'individual' : 'company';
		$request = WebPay::getAddresses( $wc_gateway->get_config( $customer_country, $customer_type ) );
		$request->setCountryCode( $customer_country );

		if ( isset( $_POST['pers_nr'] ) ) {
			$request->setCustomerIdentifier( sanitize_text_field( wp_unslash( $_POST['pers_nr'] ) ) )
				->getIndividualAddresses();
		} else if ( isset( $_POST['org_nr'] ) ) {
			$request->setCustomerIdentifier( sanitize_text_field( wp_unslash( $_POST['org_nr'] ) ) )
				->getCompanyAddresses();
		}

		try {
			$response = $request->doRequest();
		} catch ( \Exception $e ) {
			$wc_gateway::log( 'Get-address request failed, error: ' . $e->getMessage() );
		}

		if ( ! empty( $response ) ) {
			/** @var array $identity */
			$identity = $response->customerIdentity; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
			foreach ( $identity as &$ci ) { // phpcs:ignore
				if (
					$ci->customerType === 'Individual' && // phpcs:ignore
					strlen( $ci->firstName ) <= 0 && // phpcs:ignore
					strlen( $ci->lastName ) <= 0 // phpcs:ignore
				) {
					$temp = str_replace( ',', '', $ci->fullName ); // phpcs:ignore
					$explode = explode( ' ', $temp );

					if ( count( $explode ) !== 2 )
						continue;

					$ci->firstName = $explode[1]; // phpcs:ignore
					$ci->lastName = $explode[0]; // phpcs:ignore
				}
			}
		}

		$wc_gateway::log( 'Get-address request successful, sending response' );

		wp_send_json( $response );

		die();
	}
}
