<?php
namespace Svea_Webpay_For_Woocommerce\Traits;

use Svea_Webpay_For_Woocommerce\Service_Providers\Config_Production;
use Svea_Webpay_For_Woocommerce\Service_Providers\Config_Test;

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

/**
 * Trait for gateways that uses username instead of merchant id
 */
trait Gateway_Username {

	/**
	 * Get config for the specified country
	 *
	 * @param string $country
	 * @param bool $alt
	 *
	 * @return Config_Production|Config_Test
	 */
	public function get_config( $country = null, $customer_type = '' ) {
		if ( is_null( $country ) && $this->config ) {
			return $this->config;
		}

		$this->set_config( strtolower( $country ?: '' ), $customer_type );

		return $this->config;
	}

	/**
	 * Set the initial config
	 *
	 * @param string|bool $suffix
	 * @param string $customer_type
	 * @return void
	 */
	public function set_config( $suffix = false, $customer_type = '' ) {
		if ( $suffix === false && ! isset( WC()->customer ) ) {
			return;
		}

		if ( ! $suffix ) {
			$country = strtolower( WC()->customer->get_billing_country() );
			$suffix = $country;
		}

		if (
			$this->get_option( 'merchant_' . $suffix . '_use_b2b' ) === 'yes' &&
			$customer_type === 'company'
		) {
			$suffix .= '_b2b';
		}

		$this->testmode = $this->get_option( 'testmode_' . $suffix ) === 'yes';
		$this->username = $this->get_option( 'username_' . $suffix );
		$this->password = $this->get_option( 'password_' . $suffix );
		$this->client_nr = $this->get_option( 'client_nr_' . $suffix );

		$args = [ false, false, $this->client_nr, $this->password, $this->username ];
		$this->config = $this->testmode ? new Config_Test( ...$args ) : new Config_Production( ...$args );
	}
}
