<?php


declare ( strict_types=1 );

namespace Simplyin\Simplyin_W_Plugin;

use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
use Exception;
use Simplyin\Simplyin_W_Plugin\Controller\Ajax\Widget\Widget_Controller;
use Simplyin\Simplyin_W_Plugin\Lib\Base_Plugin\Abstract_Base_Plugin;
use Simplyin\Simplyin_W_Plugin\Lib\Base_Plugin\Logger\Logger_Interface;
use Simplyin\Simplyin_W_Plugin\Lib\Base_Plugin\Logger\Null_Logger;
use Simplyin\Simplyin_W_Plugin\Lib\Base_Plugin\Woocommerce_Logger;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\Sin_Core_Api\Simplyin_Api_Legacy_Client;
use Simplyin\Simplyin_W_Plugin\Lib\Session\Simplyin_Session;
use Simplyin\Simplyin_W_Plugin\Payments\Ajax\Blik\Blik_Ajax_Handler;
use Simplyin\Simplyin_W_Plugin\Payments\Ajax\Card\Card_Ajax_Handler;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Woocommerce_Blocks\Payment_Blocks_Support;


class Plugin extends Abstract_Base_Plugin {


	const SHORT_SLUG = 'simplyin';

	private static ?Legacy_App $app = null;

	public static bool $logger_enabled = false;
	private static array $simplyin_config = [];
	private static array $locked_options = [];

	/**
	 * @throws Exception
	 */
	protected function before_init() {
		$this->before_init_when_api_connected();
	}

	private function before_init_when_api_connected() {
		if ( get_option( 'SimplyInApiConnection' ) === '1' ) {
			( new Widget_Controller() )->register_ajax_hooks();
			$this->init_payment_gateway();

			add_action( 'woocommerce_blocks_loaded',
				[ $this, 'woocommerce_block_support' ] );


			$blik_ajax_handler = new Blik_Ajax_Handler();
			$blik_ajax_handler->register_ajax_hooks();
			$card_ajax_handler = new Card_Ajax_Handler();
			$card_ajax_handler->register_ajax_hooks();

		}
	}

	protected function plugins_loaded_hooks() {

	}

	/**
	 * @throws Exception
	 */
	public function enqueue_frontend_scripts() {

		if ( ! get_option( 'SimplyInApiConnection' ) ) {
			return;

		}

		$public_url = $this->get_plugin_url() . 'public';

		if ( ( is_checkout() && ! has_block( 'woocommerce/checkout' ) ) || is_checkout_pay_page() ) {

			wp_enqueue_script(
				'SimplyInGatewayJs',
				$public_url . '/gateway/front.js',
				[ 'jquery' ],
				wp_rand(),
				true
			);
		}

		wp_enqueue_style( 'SimplyInGatewayCss',
			$public_url . '/gateway/front.css',
			[],
			wp_rand() );

		wp_enqueue_style( 'SimplyInThankYouPageCss',
			$public_url . '/thankyoupage/status/status.css',
			[],
			wp_rand() );

		do_action( 'simplyin_enqueue_frontend_scripts', $public_url );

	}

	public function enqueue_dashboard_scripts() {
		$public_url = $this->get_plugin_url() . 'public';

		wp_enqueue_script(
			'SimplyInAdminJs',
			$public_url . '/admin/admin.js',
			[ 'jquery' ],
			wp_rand(),
			true
		);

		wp_enqueue_style( 'SimplyInAdminCss',
			$public_url . '/admin/admin.css',
			[],
			wp_rand() );

		wp_enqueue_style( 'SimplyInGatewayOptionsCss',
			$public_url . '/admin/gateway_options.css',
			[],
			wp_rand() );


	}

	public function init(): void {


	}

	public function get_woocommerce_logger( ?string $log_id = null
	): Logger_Interface {

		$log_id = $log_id
			? $this->prefix_by_short_slug( $log_id )
			: $this->get_from_config( 'slug' );

		if ( self::$logger_enabled ) {
			$logger = new Woocommerce_Logger( $log_id );
		} else {
			$logger = new Null_Logger();
		}

		return $logger;
	}

	public function get_simplyin_logger(): Simplyin_Logger {
		return new Simplyin_Logger();
	}

	public function prefix_by_short_slug( string $string ): string {
		return self::SHORT_SLUG . '_' . $string;
	}


	public function get_app(): Legacy_App {
		if ( ! self::$app ) {
			self::$app = new Legacy_App();
		}

		return self::$app;
	}

	public function update_option(
		$key,
		$value,
		?string $context = null,
		$locked = false
	) {
		if ( key_exists( $key, self::$locked_options ) ) {
			$this->get_woocommerce_logger( $context )->log_debug(
				sprintf( "[update_option] [key: %s] [locked!]",
					$key ) );

			return;
		}

		if ( $locked ) {
			self::$locked_options[ $key ] = true;
		}

		$this->get_woocommerce_logger( $context )->log_debug(
			sprintf( "[update_option] [key: %s] [value: %s]",
				$key,
				wp_json_encode( $value ) ) );


		update_option( $key, $value );
	}

	public function get_api(): Simplyin_Api_Legacy_Client {
		return new Simplyin_Api_Legacy_Client( 'simplyin',
			SimplyInGetPluginVersion() );
	}

	public function get_simplyin_config(): array {

		return self::$simplyin_config;
	}

	public function set_simplyin_config( array $simplyin_config ): void {
		self::$simplyin_config = $simplyin_config;
	}

	public function get_backend_simplyin_url(): string {
		$simplyin_config = $this->get_simplyin_config();

		if ( isset( $simplyin_config['backendSimplyIn'] ) ) {
			return $simplyin_config['backendSimplyIn'];
		} else {
			return '';
		}
	}

	public function get_environment_version_prefix(): string {
		$simplyin_config = $this->get_simplyin_config();

		if ( isset( $simplyin_config['environmentVersion'] ) ) {
			return $simplyin_config['environmentVersion'];
		} else {
			return '';
		}
	}

	public function get_simplyin_session(): Simplyin_Session {
		return new Simplyin_Session();
	}

	private function init_payment_gateway() {
		add_filter( 'woocommerce_payment_gateways',
			function ( $gateways ) {
				$gateways[]
					= 'Simplyin\Simplyin_W_Plugin\Payments\Gateway\Simplyin_Gateway';

				return $gateways;
			}
		);
	}

	public function woocommerce_block_support() {
		$host = $request_uri = '';
		if ( isset( $_SERVER['HTTP_HOST'] ) ) {
			$host = sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) );
		}

		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			$request_uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) );
		}

		$current_url = $host . $request_uri;

		$search_phrase = "order-received";
		if ( strpos( $current_url, $search_phrase ) !== false ) {
			return;
		}

		if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new Payment_Blocks_Support() );
				}
			);
		}
	}

	public function handle_api_unauthorized(): void {
		$this->update_option( 'SimplyInSettingsErrorMsg',
			__( 'Error connecting to Simply.IN - check the API key.',
				'simplyin' ),
			null,
			true );

		$this->update_option( 'SimplyInApiConnection',
			0,
			'sync' );
		$this->update_option( 'SimplyInApiConnectedLastTry',
			time(),
			'sync' );

		$simplyin_session = $this->get_simplyin_session();

		$simplyin_session->clear();

		$simplyin_session->set( 'simplyin_user_data_commerce', null );
		$simplyin_session->set(
			'simplyin_user_data_commerce_timestamp',
			null
		);
	}

}
