<?php
/**
 * Handles Swish settings outside the gateway class itself.
 *
 * @package flo-checkout
 */

namespace Flo_Checkout\Gateways\Swish;

use Flo_Checkout\Gateways\Helpers\Abstract_Gateway_Settings;
use Flo_Checkout\Gateways\Swish_Pay;
use Flo_Checkout\Shared;

/**
 * Class Swish_Settings
 */
class Swish_Settings extends Abstract_Gateway_Settings {

	/**
	 * Get the gateway ID.
	 *
	 * @return string The gateway ID.
	 */
	public static function get_gateway_id(): string {
		return Swish_Pay::get_id();
	}


	/**
	 * Retrieves a specific Swish setting.
	 *
	 * @param string $key The key of the setting to retrieve.
	 *
	 * @return mixed|null The value of the setting if found, otherwise null.
	 */
	public static function get_swish_setting( string $key ): mixed {
		$swish_settings = self::get_swish_settings();
		return $swish_settings[ $key ] ?? null;
	}

	/**
	 * Retrieves the Swish settings.
	 *
	 * @return array The Swish settings.
	 * @noinspection PhpUndefinedConstantInspection -- Swish constants optionally defined, but are checked by Swish_Certificates::nmf_certs_exist().
	 */
	public static function get_swish_settings(): array {
		static $swish_settings = array();

		if ( ! empty( $swish_settings ) ) {
			return $swish_settings;
		}

		$swish_settings['swish_environment'] = self::get( 'swish_environment' );
		switch ( $swish_settings['swish_environment'] ) {
			case 'mss':
				$swish_settings['api_end_url']         = 'mss.cpc.getswish.net';
				$swish_settings['root_certificate']    = Shared::instance()->package_info->paths->get_path() . 'certs/swish/CA/RootCA-prod_mss.pem';
				$swish_settings['public_certificate']  = Shared::instance()->package_info->paths->get_path() . 'certs/swish/MSS/Swish_TechnicalSupplier_TestCertificate_9870474641.p12';
				$swish_settings['private_certificate'] = '';
				$swish_settings['private_key']         = 'swish';
				$swish_settings['payee_number']        = '1234679304';
				break;
			case 'sandbox':
				$swish_settings['api_end_url']         = 'staging.getswish.pub.tds.tieto.com';
				$swish_settings['root_certificate']    = Shared::instance()->package_info->paths->get_path() . 'certs/swish/CA/RootCA-sandbox.pem';
				$swish_settings['public_certificate']  = self::get( Swish_Certificates::get_cert_info_by_type( 'sandbox_public', 'option_name' ) );
				$swish_settings['private_certificate'] = self::get( Swish_Certificates::get_cert_info_by_type( 'sandbox_private', 'option_name' ) );
				$swish_settings['private_key']         = self::get( 'sandbox_private_key' );
				$swish_settings['payee_number']        = self::get( 'sandbox_payee_number' );
				break;
			case 'prod':
			default:
				$swish_settings['api_end_url']      = 'cpc.getswish.net';
				$swish_settings['root_certificate'] = Shared::instance()->package_info->paths->get_path() . 'certs/swish/CA/RootCA-prod_mss.pem';
				$swish_settings['payee_number']     = self::get( 'payee_number' );

				if (
					'yes' === self::get( 'swish_user_server_certs' ) &&
					Swish_Certificates::nmf_certs_exist()
				) {
					$swish_settings['public_certificate']  = NMF_CHECKOUT_SWISH_PEM_PATH;
					$swish_settings['private_certificate'] = NMF_CHECKOUT_SWISH_KEY_PATH;
					$swish_settings['private_key']         = defined( 'NMF_CHECKOUT_SWISH_KEY_PASS' ) ? NMF_CHECKOUT_SWISH_KEY_PASS : false;
				} else {
					$swish_settings['public_certificate']  = self::get( Swish_Certificates::get_cert_info_by_type( 'public', 'option_name' ) );
					$swish_settings['private_certificate'] = self::get( Swish_Certificates::get_cert_info_by_type( 'private', 'option_name' ) );
					$swish_settings['private_key']         = self::get( 'live_private_key' );
				}

				break;

		}

		return $swish_settings;
	}

	/**
	 * Get the settings fields for the payment method.
	 *
	 * @return array An array of form fields settings for BNPL payment method.
	 */
	public static function get_settings_fields(): array {
		$gateway_environment_desc =
			// translators: %1$s and %2$s are placeholders for the opening and closing <strong> tags, respectively.
			sprintf( __( '%1$sProduction (Live): %2$s Use this mode for live transactions.', 'flo-checkout-plugin' ), '<strong>', '</strong>' ) . '<br>' .
			// translators: %1$s and %2$s are placeholders for the opening and closing <strong> tags, respectively.
			sprintf( __( '%1$sMerchant Swish Simulator: %2$s For basic testing.', 'flo-checkout-plugin' ), '<strong>', '</strong>' ) . '<br>' .
			// translators: %1$s and %2$s are placeholders for the opening and closing <strong> tags, respectively.
			sprintf( __( '%1$sSwish Sandbox: %2$s For advanced verification of the full payment request flow. A Sandbox account from Swish is required.', 'flo-checkout-plugin' ), '<strong>', '</strong>' ) . '<br><br>' .
			// translators: %1$s and %2$s are placeholders for the opening and closing <a> tags, respectively.
			sprintf( __( 'Read more about Swish Environments %1$shere%2$s.', 'flo-checkout-plugin' ), '<a href="https://developer.swish.nu/documentation/environments" target="_blank">', '</a>' );

		$prod_public_file_desc =
			__( 'Upload .pem file downloaded from the Swish Portal (.p12 file can also be used).', 'flo-checkout-plugin' ) .
			Swish_Certificates::generate_cert_download_link( 'public' );

		$prod_private_file_desc =
			__( 'Upload your private .key certificate file. This key file is generated and automatically stored when generating a new certificate request above.', 'flo-checkout-plugin' ) .
			Swish_Certificates::generate_cert_download_link( 'private' );

		$connection_test_status = self::is_setting_enabled( 'swish_connection_test_enabled' ) ? '<i class="spinner is-active" style="float: none;"></i>' : __( 'Disabled', 'flo-checkout-plugin' );

		$support_url  = 'https://supportflo.northmill.com/s/article/Flo-Checkout-Ta-betalt-med-kort-i-Wordpress';
		$support_info = __( 'Read more on how to set this up on our support page:', 'flo-checkout-plugin' ) . '<br>' .
						sprintf( '<a href="%s" target="_blank">%s</a>', $support_url, $support_url );

		$form_fields = array();

		$form_fields['enabled'] = array(
			'title'       => __( 'Enable/Disable', 'flo-checkout-plugin' ),
			'label'       => __( 'Enable Swish Payments', 'flo-checkout-plugin' ),
			'type'        => 'checkbox',
			'description' => '',
			'default'     => 'no',
		);

		$form_fields['title'] = array(
			'title'       => __( 'Title', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( 'Title for payment type displayed in checkout.', 'flo-checkout-plugin' ),
			'default'     => __( 'Swish Pay', 'flo-checkout-plugin' ),
		);

		$form_fields['description'] = array(
			'title'       => __( 'Description', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( '(optional) Description for payment type displayed in checkout.', 'flo-checkout-plugin' ),
			'default'     => '',
		);

		$form_fields['swish_environment'] = array(
			'title'       => __( 'Swish Environment', 'flo-checkout-plugin' ),
			'type'        => 'select',
			'description' => $gateway_environment_desc,
			'default'     => 'production',
			'options'     => array(
				'prod'    => __( 'Production', 'flo-checkout-plugin' ),
				'mss'     => __( 'Merchant Swish Simulator', 'flo-checkout-plugin' ),
				'sandbox' => __( 'Swish Sandbox', 'flo-checkout-plugin' ),
			),
		);
		/**
		 * Production.
		 */
		$form_fields['swish_prod_settings'] = array(
			'title' => __( 'Production settings', 'flo-checkout-plugin' ),
			'type'  => 'title',
		);

		if ( Swish_Certificates::nmf_certs_exist() ) {
			$form_fields['swish_user_server_certs'] = array(
				'title'       => __( 'Use Server Swish Certificates', 'flo-checkout-plugin' ),
				'label'       => __( 'Uses certificates stored on server instead of custom certificates.', 'flo-checkout-plugin' ),
				'type'        => 'checkbox',
				'description' => '',
				'default'     => 'no',
			);
		}
		$form_fields['swish_prod_settings_generate_csr']                                   = array(
			'title'       => '',
			'type'        => 'title',
			'description' => Swish_Certificates::get_certificate_generation_html(),
		);
		$form_fields[ Swish_Certificates::get_cert_info_by_type( 'public', 'filename' ) ]  = array(
			'title'             => __( 'Public certificate file', 'flo-checkout-plugin' ),
			'type'              => 'file',
			'description'       => $prod_public_file_desc,
			'custom_attributes' => array(
				'no_value' => true,
			),
		);
		$form_fields[ Swish_Certificates::get_cert_info_by_type( 'private', 'filename' ) ] = array(
			'title'             => __( 'Private certificate file', 'flo-checkout-plugin' ),
			'type'              => 'file',
			'description'       => $prod_private_file_desc,
			'custom_attributes' => array(
				'no_value' => true,
			),
		);
		$form_fields['live_private_key'] = array(
			'title'       => __( 'Private key', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( 'Password for certificate.', 'flo-checkout-plugin' ),
			'default'     => 'swish',
		);
		$form_fields['payee_number']     = array(
			'title'       => __( 'Swish Number', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( 'Swish number you want to get paid to.', 'flo-checkout-plugin' ),
			'default'     => '',
		);
		/**
		 * MSS.
		 */
		$form_fields['swish_mss_settings'] = array(
			'title'       => __( 'Merchant Swish Simulator settings', 'flo-checkout-plugin' ),
			'description' => __( 'No extra setup needed when in Merchant Swish Simulator environment.', 'flo-checkout-plugin' ),
			'type'        => 'title',
		);
		/**
		 * Sandbox settings.
		 */
		$form_fields['swish_sandbox_settings'] = array(
			'title' => __( 'Sandbox settings', 'flo-checkout-plugin' ),
			'type'  => 'title',
		);
		$form_fields[ Swish_Certificates::get_cert_info_by_type( 'sandbox_public', 'filename' ) ]  = array(
			'title'             => __( 'Public certificate upload', 'flo-checkout-plugin' ),
			'type'              => 'file',
			'description'       => __( 'Upload your .pem or .p12 certificate file.', 'flo-checkout-plugin' ) .
									Swish_Certificates::generate_cert_download_link( 'sandbox_public' ),
			'custom_attributes' => array(
				'no_value' => true,
			),
		);
		$form_fields[ Swish_Certificates::get_cert_info_by_type( 'sandbox_private', 'filename' ) ] = array(
			'title'             => __( 'Private certificate upload', 'flo-checkout-plugin' ),
			'type'              => 'file',
			'description'       => __( 'Upload your private .key certificate file.', 'flo-checkout-plugin' ) .
									Swish_Certificates::generate_cert_download_link( 'sandbox_private' ),
			'custom_attributes' => array(
				'no_value' => true,
			),
		);
		$form_fields['sandbox_private_key']  = array(
			'title'       => __( 'Private key', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( 'Password for private certificate.', 'flo-checkout-plugin' ),
			'default'     => 'swish',
		);
		$form_fields['sandbox_payee_number'] = array(
			'title'       => __( 'Merchant Swish Number', 'flo-checkout-plugin' ),
			'type'        => 'text',
			'description' => __( 'Swish number receiving payments.', 'flo-checkout-plugin' ),
			'default'     => '',
		);
		/**
		 * Connection test.
		 */
		$form_fields['swish_connection_test']         = array(
			'title'       => __( 'Connection test', 'flo-checkout-plugin' ),
			'description' => '<strong>' . __( 'Test status', 'flo-checkout-plugin' ) . ':</strong><br><span id="swish-connection-test-result">' . $connection_test_status . '</span>',
			'type'        => 'title',
		);
		$form_fields['swish_connection_test_enabled'] = array(
			'title'       => __( 'Connection test', 'flo-checkout-plugin' ),
			'label'       => __( 'Enable connection test', 'flo-checkout-plugin' ),
			'description' => __( 'Enable to run connection test when this page is loaded.', 'flo-checkout-plugin' ) . '<br>' .
							__( 'Connection will be based on current Swish Environment settings.', 'flo-checkout-plugin' ),
			'type'        => 'checkbox',
			'default'     => 'no',
		);
		$form_fields['test_payer_number']             = array(
			'title'       => __( 'Test Payer Number', 'flo-checkout-plugin' ),
			'type'        => 'text',
			// translators: %1$s and %2$s are placeholders for the HTML tags <strong> and </strong> respectively.
			'description' => sprintf( __( 'Optional phone number used for connection test, on a successful connection test a payment request will be made to this number. %1$sNote that when in Production environment, this request will be real. Do not accept the request unless you want to perform a real transaction.%2$sThe request is canceled automatically after a few seconds.', 'flo-checkout-plugin' ), '<br><strong style="color: red;">', '</strong><br>' ),
			'default'     => '',
		);
		$form_fields['support_info']                  = array(
			'title'       => __( 'Guide and support', 'flo-checkout-plugin' ),
			'description' => $support_info,
			'type'        => 'title',
		);
		$form_fields['log_enabled']                   = array(
			'title'       => __( 'Debug Log', 'flo-checkout-plugin' ),
			'label'       => __( 'Enable Logging', 'flo-checkout-plugin' ),
			'description' => parent::maybe_get_log_file_link(),
			'type'        => 'checkbox',
			'default'     => 'yes',
		);

		return $form_fields;
	}
}
