<?php
/**
 * Class CheckConnectionStatus
 *
 * @package DhlPolska
 */

namespace DhlPolska;

use DhlPolska\API\AuthDataInterface;
use DhlPolska\API\ParcelShop;
use DhlPolska\API\WebApi\Struct\AuthData as WebApiAuthData;
use DhlPolska\API\ParcelShop\Struct\AuthData as ParcelShopAuthData;
use DhlPolska\API\WebAPI;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettings;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettingsFields;
use DhlPolskaVendor\Psr\Log\LoggerInterface;
use DhlPolskaVendor\Psr\Log\NullLogger;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Check connection
 */
class CheckConnectionStatus implements Hookable {

	public const AJAX_ACTION_WEBAPI     = 'dhl_polska_check_connection_status_webapi';
	public const AJAX_ACTION_PARCELSHOP = 'dhl_polska_check_connection_status_parcelshop';

	/**
	 * @var WooCommerceDHLPolskaSettings
	 */
	private WooCommerceDHLPolskaSettings $settings;

	/**
	 * @var LoggerInterface
	 */
	private LoggerInterface $logger;

	/**
	 * CheckConnectionStatus constructor.
	 *
	 * @param WooCommerceDHLPolskaSettings $settings .
	 * @param LoggerInterface|null         $logger   .
	 */
	public function __construct( WooCommerceDHLPolskaSettings $settings, ?LoggerInterface $logger = null ) {
		$this->settings = $settings;
		$this->logger   = $logger ?? new NullLogger();
	}

	/**
	 * @return void
	 */
	public function hooks() {
		add_action( 'wp_ajax_' . self::AJAX_ACTION_WEBAPI, [ $this, 'check_connection_status_webapi' ] );
		add_action( 'wp_ajax_' . self::AJAX_ACTION_PARCELSHOP, [ $this, 'check_connection_status_parcelshop' ] );
	}

	/**
	 * @return void
	 */
	public function check_connection_status_webapi() {
		check_ajax_referer( self::AJAX_ACTION_WEBAPI );

		try {
			$login    = $this->settings->get_webapi_login();
			$password = $this->settings->get_webapi_password();

			if ( empty( $login ) || empty( $password ) ) {
				throw new \Exception( __( 'Proszę wpisać login i hasło.', 'dhl-polska' ) );
			}

			$auth_data = new WebApiAuthData(
				$login,
				$password
			);

			$api = $this->get_webapi(
				$auth_data,
				$this->settings->get_webapi_sap_number(),
				$this->settings->is_test_mode()
			);
			$api->check_connection();

			wp_send_json_success( [ 'message' => __( 'Połączono', 'dhl-polska' ) ] );
		} catch ( \Exception $e ) {
			wp_send_json_error(
				[
					'message' => sprintf(
						// Translators: error message.
						__( 'Błąd połączenia: %s', 'dhl-polska' ),
						$e->getMessage()
					),
				]
			);
		}
	}

	/**
	 * @return void
	 */
	public function check_connection_status_parcelshop() {
		check_ajax_referer( self::AJAX_ACTION_PARCELSHOP );

		try {
			$login    = $this->settings->get_parcelshop_login();
			$password = $this->settings->get_parcelshop_password();

			if ( empty( $login ) || empty( $password ) ) {
				throw new \Exception( __( 'Proszę wpisać login i hasło.', 'dhl-polska' ) );
			}

			$auth_data = new ParcelShopAuthData(
				$login,
				$password
			);

			$api = $this->get_parcelshop(
				$auth_data,
				$this->settings->is_test_mode()
			);
			$api->check_connection();

			wp_send_json_success( [ 'message' => __( 'Połączono', 'dhl-polska' ) ] );
		} catch ( \Exception $e ) {
			wp_send_json_error(
				[
					'message' => sprintf(
						// Translators: error message.
						__( 'Błąd połączenia: %s', 'dhl-polska' ),
						$e->getMessage()
					),
				]
			);
		}
	}

	/**
	 * @param AuthDataInterface $auth_data .
	 * @param string            $sap       .
	 * @param bool              $test_mode .
	 *
	 * @return WebAPI
	 */
	protected function get_webapi( AuthDataInterface $auth_data, string $sap, bool $test_mode ): WebAPI {
		return new WebAPI( $auth_data, $sap, $test_mode, $this->logger );
	}

	/**
	 * @param AuthDataInterface $auth_data .
	 * @param bool              $test_mode .
	 *
	 * @return ParcelShop
	 */
	protected function get_parcelshop( AuthDataInterface $auth_data, bool $test_mode ): ParcelShop {
		return new ParcelShop( $auth_data, '', $test_mode, $this->logger );
	}
}
