<?php
/**
 * Main setup file.
 *
 * @package WkwcAdyen
 * @since   1.2.0
 */

defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
use WkwcAdyen\Includes\Wkwc_Adyen_Integration;
use WkwcAdyen\Includes\Checkout_Blocks;

use WkwcAdyen\Helper\Common;
use WkwcAdyen\Helper\Adyen\Wkwc_Adyen_Helper;
/**
 * Main Wkwc_Adyen Class.
 *
 * @class Wkwc_Adyen
 */
final class Wkwc_Adyen {
	/**
	 * The single instance of the class.
	 *
	 * @var $instance
	 * @since 1.0
	 */
	protected static $instance = null;

	/**
	 * Api class.
	 *
	 * @var Wkwc_Adyen_API_Handler
	 */
	public $api;

	/**
	 * Main Wkwc_Adyen Instance.
	 *
	 * Ensures only one instance of Wkwc_Adyen is loaded or can be loaded.
	 *
	 * @static
	 *
	 * @return Wkwc_Adyen - Main instance.
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * WKWC_ADYEN Constructor.
	 */
	public function __construct() {
		$this->wkwc_adn_define_constants();
		$this->wkwc_adn_init_hooks();
		$this->wkwc_adn_includes();
	}

	/**
	 * Define WKWC_ADYEN Constants.
	 */
	private function wkwc_adn_define_constants() {
		defined( 'WKWC_ADN_NAMESPACE' ) || define( 'WKWC_ADN_NAMESPACE', 'wk_adyen/v1' );
		defined( 'WKWC_ADN_ABSPATH' ) || define( 'WKWC_ADN_ABSPATH', dirname( WKADYEN_FILE ) . '/' );
		defined( 'WKWC_ADN_PLUGIN_BASE' ) || define( 'WKWC_ADN_PLUGIN_BASE', plugin_basename( WKADYEN_FILE ) );
		defined( 'WKWC_ADN_PLUGIN_FILE' ) || define( 'WKWC_ADN_PLUGIN_FILE', plugin_dir_path( WKADYEN_FILE ) );
		defined( 'WKWC_ADN_PLUGIN_URL' ) || define( 'WKWC_ADN_PLUGIN_URL', plugin_dir_url( WKADYEN_FILE ) );
		defined( 'WKWC_ADN_SCRIPT_VERSION' ) || define( 'WKWC_ADN_SCRIPT_VERSION', WKADYEN_VERSION );
		defined( 'WKWC_ADN_PREFIX' ) || define( 'WKWC_ADN_PREFIX', 'wkwc_adyen' );
	}

	/**
	 * Hook into actions and filters.
	 *
	 * @since 2.3
	 */
	private function wkwc_adn_init_hooks() {
		add_action( 'plugins_loaded', array( $this, 'wkwc_adn_load_plugin' ) );

		add_filter( 'plugin_action_links_' . WKWC_ADN_PLUGIN_BASE, array( $this, 'wkwc_adn_plugin_action_links' ) );

		add_filter( 'plugin_row_meta', array( $this, 'wkwc_adn_plugin_row_meta' ), 10, 2 );

		add_action( 'wp_footer', array( $this, 'wkwc_adn_front_footer_info' ) );

		add_action( 'woocommerce_blocks_loaded', array( $this, 'wkwc_adn_register_checkout_blocks' ) );

		add_filter( 'wk_allow_settings_update_to_demo_admin', array( $this, 'wkwc_adn_allowed_editor_to_save_option_settings' ) );

		add_filter( 'cron_schedules', array( $this, 'wkwc_adyen_add_cron_schedule' ) );

		add_action( 'admin_init', array( $this, 'wkwc_adyen_create_connection_cron_jobs' ) );

		add_action( 'wkwc_adyen_connection_cron_job', array( $this, 'wkwc_adyen_run_connection_cron_jobs' ) );

		register_deactivation_hook( WKWC_ADN_PLUGIN_FILE, array( $this, 'wkwc_adyen_remove_connection_cron_jobs' ) );
	}


	/**
	 * Includes function.
	 */
	public static function wkwc_adn_load_plugin() {
		if ( ! function_exists( 'WC' ) ) {
			// Add WooCommerce dependency Message.
			add_action( 'admin_notices', array( __CLASS__, 'wkwc_adyen_wc_not_installed_notice' ) );
		} else {
			require_once WKWC_ADN_PLUGIN_FILE . 'vendor/autoload.php';

			if ( ! class_exists( 'WKWC_Modules_Autoload' ) && file_exists( WKWC_ADN_PLUGIN_FILE . 'modules/class-wkwc-modules-autoload.php' ) ) {
				include_once WKWC_ADN_PLUGIN_FILE . 'modules/class-wkwc-modules-autoload.php';
			}

			load_plugin_textdomain( 'wkwc-adyen', false, plugin_basename( dirname( WKADYEN_FILE ) ) . '/languages' );

			Wkwc_Adyen_Integration::get_instance();
		}
	}

	/**
	 * Show action links on the plugin screen.
	 *
	 * @param array $links Plugin Action links.
	 *
	 * @return array
	 */
	public static function wkwc_adn_plugin_action_links( $links ) {
		$action_links = array(
			'settings' => '<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=adyen_payment' ) . '" aria-label="' . esc_attr__( 'Settings', 'wkwc-adyen' ) . '">' . esc_html__( 'Settings', 'wkwc-adyen' ) . '</a>',
		);

		return array_merge( $action_links, $links );
	}

	/**
	 * Show row meta on the plugin screen.
	 *
	 * @param array  $links Plugin Row Meta.
	 * @param string $file  Plugin Base file.
	 *
	 * @return array
	 */
	public function wkwc_adn_plugin_row_meta( $links, $file ) {
		if ( WKWC_ADN_PLUGIN_BASE !== $file ) {
			return $links;
		}
		$row_meta = array( 'docs' => '<a href="https://webkul.com/blog/woocommerce-adyen-payment-gateway/" aria-label="' . esc_attr__( 'View Doc', 'wkwc-adyen' ) . '">' . esc_html__( 'Documentation', 'wkwc-adyen' ) . '</a>' );

		return array_merge( $links, $row_meta );
	}

	/**
	 * Function include
	 */
	public function wkwc_adn_includes() {
		include_once WKWC_ADN_ABSPATH . 'rest-api/wkwc-adyen-api-file-handler.php';
	}

	/**
	 * Show wc not installed notice.
	 *
	 * @return void
	 */
	public static function wkwc_adyen_wc_not_installed_notice() {
		?>
		<div class="error">
			<p><?php echo wp_sprintf( /* Translators: %s woocommerce links */ esc_html__( 'Adyen payment gateway plugin depends on the last version of %s or later to work!', 'wkwc-adyen' ), '<a href="https://wordpress.org/plugins/woocommerce/" target="_blank">' . esc_html__( 'WooCommerce', 'wkwc-adyen' ) . '</a>' ); ?></p>
		</div>
		<?php
	}

	/**
	 * Templates to use in js.
	 *
	 * @hooked 'wp_footer' action action hook.
	 *
	 * @return void
	 */
	public function wkwc_adn_front_footer_info() {
		$show_info = filter_input( INPUT_GET, 'wkmodule_info', FILTER_SANITIZE_NUMBER_INT );
		$show_info = empty( $show_info ) ? 0 : intval( $show_info );

		if ( 200 === $show_info ) {
			?>
			<input type="hidden" data-lwdt="202404222000" wp-woocommerce-adyen-payment-gateway="<?php echo esc_attr( WKADYEN_VERSION ); ?>">
			<?php
		}
	}

	/**
	 * Register checkout blocks
	 *
	 * @return void
	 */
	public function wkwc_adn_register_checkout_blocks() {

		if ( ! class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
			return;
		}

		add_action(
			'woocommerce_blocks_payment_method_type_registration',
			function ( PaymentMethodRegistry $payment_method_registry ) {

				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Card() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Google_Pay() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Klarna() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Klarna_PayNow() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Klarna_Account() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Klarna_Ideal() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Paypal() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Twint() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_Trustly() );
				$payment_method_registry->register( new Checkout_Blocks\Wkwc_Adyen_Checkout_Blocks_ApplePay() );
			}
		);
	}

	public function isValidHmacKey( string $hmacKey ): bool {
		// Check if the key is Base64 encoded

		if ( base64_decode( $hmacKey, true ) === false ) {
			return false;
		}

		// Decode the HMAC key and check its length (should be 32 bytes for SHA-256)
		$decodedKey = base64_decode( $hmacKey );

		if ( strlen( $decodedKey ) === 48 ) {
			return true;
		}

		return true;
	}

	/**
	 * Allowed for option update
	 *
	 * @param array $settings_hooks setting hook.
	 *
	 * @return array
	 */
	public function wkwc_adn_allowed_editor_to_save_option_settings( $settings_hooks ) {
		$settings_hooks[] = 'option_page_capability_wkwc-adyen-settings-group';

		return $settings_hooks;
	}

	/**
	 * Add Adyen cron schedule.
	 *
	 * @param array $schedules Schedules.
	 *
	 * @return array
	 */
	public function wkwc_adyen_add_cron_schedule( $schedules ) {
		$schedules['wkwc_adyen_connection_cron_schedule'] = array(
			'interval' => DAY_IN_SECONDS * 1,
			'display'  => __( 'Run Adyen Connection Crons Every Day', 'wkwc-adyen' ),
		);

		return $schedules;
	}

	/**
	 * Create Adyen connection cron jobs.
	 */
	public function wkwc_adyen_create_connection_cron_jobs() {
		if ( ! wp_next_scheduled( 'wkwc_adyen_connection_cron_job' ) ) {
			wp_schedule_event( time(), 'wkwc_adyen_connection_cron_schedule', 'wkwc_adyen_connection_cron_job' );
		}
	}

	/**
	 * Run Adyen connection cron jobs.
	 */
	public function wkwc_adyen_run_connection_cron_jobs() {
		wkwc_adn_log( 'Adyen connection cron executed successfully at ' . current_time( 'mysql' ) );
		$adyen_helper    = new Wkwc_Adyen_Helper();
		$adyen_config    = $adyen_helper->adyen_config;
		$checkout_action = new Common\Wkwc_Adyen_Checkout_Action();
		if ( ! $adyen_config->wkwc_adyen_get_merchantcode() ) {
			return;
		}

		wkwc_adn_log( 'Connection Cron Jobs started for merchant code: ' . $adyen_config->wkwc_adyen_get_merchantcode() );

		$url         = $checkout_action->wkwc_adyen_checkout_base_url();
		$api_handler = new Common\Wkwc_Adyen_Api_Handler( $url );

		$payload = array(
			'merchantAccount'  => $adyen_config->wkwc_adyen_get_merchantcode(),
			'shopperReference' => $adyen_helper::get_shopper_reference(),
			'channel'          => 'Web',
		);

		$response = $api_handler->wkwc_adyen_remote_post( 'paymentMethods', $payload );

		$response_body = $response->body;
		if ( 200 === $response->status ) {
			set_transient( 'wkwc_adyen_merchant_account_is_validated', $adyen_config->wkwc_adyen_get_merchantcode(), DAY_IN_SECONDS );
		} else {
			set_transient( 'wkwc_adyen_merchant_account_is_validated', null, DAY_IN_SECONDS );
		}
	}

	/**
	 * Remove Adyen connection cron jobs.
	 */
	public function wkwc_adyen_remove_connection_cron_jobs() {
		if ( wp_next_scheduled( 'wkwc_adyen_connection_cron_job' ) ) {
			wp_clear_scheduled_hook( 'wkwc_adyen_connection_cron_job' );
		}
	}
}
