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

namespace DhlPolska;

use DhlPolska\Exception\ConnectionCheckFailedException;
use DhlPolska\Exception\ExceptionMessageResolver;
use DhlPolska\Exception\WebApiCredentialsMissingException;
use DhlPolskaVendor\Octolize\DhlPolska\API\AuthDataInterface;
use DhlPolskaVendor\Octolize\DhlPolska\API\WebApi\Struct\AuthData as WebApiAuthData;
use DhlPolskaVendor\Octolize\DhlPolska\API\WebAPI;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettings;
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';

	/**
	 * @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' ] );
	}

	/**
	 * @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 WebApiCredentialsMissingException();
			}

			$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' => ExceptionMessageResolver::resolve_throwable( $e, ConnectionCheckFailedException::class ),
				]
			);
		}
	}

	/**
	 * @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 );
	}
}
