<?php
/**
 * Initializes plugin data.
 * Contains defination of common functions.
 *
 * @package miniorange-sms-order-notification-otp-verification
 */

use WCSMSOTP\Helper\MoFormList;
use WCSMSOTP\Helper\FormSessionData;
use WCSMSOTP\Helper\MoUtility;
use WCSMSOTP\Objects\FormHandler;
use WCSMSOTP\Objects\IFormHandler;
use WCSMSOTP\SplClassLoader;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'MOV_WC_DIR', plugin_dir_path( __FILE__ ) );
define( 'MOV_WC_URL', plugin_dir_url( __FILE__ ) );

$mowc_response     = wp_remote_retrieve_body( wp_remote_get( MOV_WC_URL . 'package.json', array( 'sslverify' => false ) ) );
$mowc_package_data = json_decode( $mowc_response );
if ( json_last_error() !== 0 ) {
	$mowc_package_data = json_decode( mowc_initialize_wc_package_json() );
}

define( 'MOV_WC_VERSION', $mowc_package_data->version );
define( 'MOV_WC_TYPE', $mowc_package_data->type );
define( 'MOV_WC_HOST', $mowc_package_data->hostname );
define( 'MOV_WC_PORTAL', $mowc_package_data->portal );
define( 'MOV_WC_FORGOT_PASSWORD_URL', MOV_WC_PORTAL . '/forgotpassword' );
define( 'MOV_WC_DEFAULT_CUSTOMERKEY', $mowc_package_data->dcustomerkey );
define( 'MOV_WC_DEFAULT_APIKEY', $mowc_package_data->dapikey );
define( 'MOV_WC_SSL_VERIFY', $mowc_package_data->sslverify );
define( 'MOV_WC_CSS_URL', MOV_WC_URL . 'includes/css/mo_customer_validation_style.css?version=' . MOV_WC_VERSION );
define( 'MOV_WC_FORM_CSS', MOV_WC_URL . 'includes/css/mo_forms_css.css?version=' . MOV_WC_VERSION );
define( 'MO_WC_INTTELINPUT_CSS', MOV_WC_URL . 'includes/css/intlTelInput.min.css?version=' . MOV_WC_VERSION );
define( 'MOV_WC_JS_URL', MOV_WC_URL . 'includes/js/mowc_wc_settings.js?version=' . MOV_WC_VERSION );
define( 'WC_VALIDATION_JS_URL', MOV_WC_URL . 'includes/js/formValidation.js?version=' . MOV_WC_VERSION );
define( 'MO_WC_INTTELINPUT_JS', MOV_WC_URL . 'includes/js/intlTelInput.min.js?version=' . MOV_WC_VERSION );
define( 'MO_WC_DROPDOWN_JS', MOV_WC_URL . 'includes/js/dropdown.js?version=' . MOV_WC_VERSION );
define( 'MOV_WC_LOADER_URL', MOV_WC_URL . 'includes/images/loader.gif' );
define( 'MOV_WC_DONATE', MOV_WC_URL . 'includes/images/donate.png' );
define( 'MOV_WC_PAYPAL', MOV_WC_URL . 'includes/images/paypal.png' );
define( 'MOV_WC_FIREBASE', MOV_WC_URL . 'includes/images/firebase.png' );
define( 'MOV_WC_NETBANK', MOV_WC_URL . 'includes/images/netbanking.png' );
define( 'MOV_WC_CARD', MOV_WC_URL . 'includes/images/card.png' );
define( 'MOV_WC_LOGO_URL', MOV_WC_URL . 'includes/images/logo.png' );
define( 'MOV_WC_ICON', MOV_WC_URL . 'includes/images/miniorange_icon.png' );
define( 'MOV_WC_ICON_GIF', MOV_WC_URL . 'includes/images/mo_icon.gif' );
define( 'MO_WC_CUSTOM_FORM', MOV_WC_URL . 'includes/js/customForm.js?version=' . MOV_WC_VERSION );
define( 'MOV_WC_ADDON_DIR', MOV_WC_DIR . 'notifications/' );
define( 'MOV_WC_USE_POLYLANG', false );
define( 'MO_WC_TEST_MODE', false );
define( 'MO_WC_FAIL_MODE', $mowc_package_data->failmode );
define( 'MOV_WC_SESSION_TYPE', $mowc_package_data->session );
define( 'MOV_WC_MAIL_LOGO', MOV_WC_URL . 'includes/images/mo_support_icon.png' );
define( 'MOV_WC_OFFERS_LOGO', MOV_WC_URL . 'includes/images/mo_sale_icon.png' );
define( 'MOV_WC_FEATURES_GRAPHIC', MOV_WC_URL . 'includes/images/mo_features_graphic.png' );
define( 'MOV_WC_TYPE_PLAN', $mowc_package_data->typeplan );
define( 'MOV_WC_LICENSE_NAME', $mowc_package_data->licensename );

define( 'MOV_WC_MAIN_CSS', MOV_WC_URL . 'includes/css/mow-main.css' );


$mowc_spl_class_loader_file = MOV_WC_DIR . 'class-splclassloader.php';
if ( ! file_exists( $mowc_spl_class_loader_file ) || ! is_readable( $mowc_spl_class_loader_file ) ) {
	return;
}
$mowc_real_spl_file = realpath( $mowc_spl_class_loader_file );
$mowc_real_base_dir = realpath( MOV_WC_DIR );
if ( false === $mowc_real_spl_file || false === $mowc_real_base_dir || strpos( $mowc_real_spl_file, $mowc_real_base_dir ) !== 0 ) {
	return;
}
require $mowc_spl_class_loader_file;

$mowc_idp_class_loader = new SplClassLoader( 'WCSMSOTP', realpath( __DIR__ . DIRECTORY_SEPARATOR . '..' ) );
$mowc_idp_class_loader->register();
$mowc_common_elements_file = MOV_WC_DIR . 'views/common-elements.php';
if ( ! MoUtility::mo_require_file( $mowc_common_elements_file, MOV_WC_DIR ) ) {
	return;
}
require_once $mowc_common_elements_file;

$mowc_plugin_dir_name = basename( MOV_WC_DIR );
load_plugin_textdomain( 'miniorange-sms-order-notification-otp-verification', false, $mowc_plugin_dir_name . '/lang/' );

mowc_initialize_wc_forms();

/**
 * Initializes hanlders of forms.
 */
function mowc_initialize_wc_forms() {
	$iterator = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator( MOV_WC_DIR . 'handler/forms', RecursiveDirectoryIterator::SKIP_DOTS ),
		RecursiveIteratorIterator::LEAVES_ONLY
	);

	foreach ( $iterator as $it ) {
		$filename   = $it->getFilename();
		$filename   = str_replace( 'class-', '', $filename );
		$class_name = 'WCSMSOTP\\Handler\\Forms\\' . str_replace( '.php', '', $filename );

		$handler_list = MoFormList::instance();

		$form_handler = $class_name::instance();
		$handler_list->add( $form_handler->get_form_key(), $form_handler );
	}
}

/**
 * Returns admin post url.
 */
function mowc_admin_wc_post_url() {
	return admin_url( 'admin-post.php' ); }

/**
 * Returns wp ajax url.
 */
function mowc_wp_wc_ajax_url() {
	return admin_url( 'admin-ajax.php' ); }

/**
 * Used for transalating the string
 *
 * @param string $text - option name to be deleted.
 */
function mowc_( $text ) {
	// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- This is a wrapper function that accepts dynamic strings for translation.
	return __( $text, 'miniorange-sms-order-notification-otp-verification' );
}

/**
 * Updates the option set in the wp_option table.
 *
 * @param string $value - option name to be deleted.
 * @param string $type - value of the option.
 */
function mowc_esc_string( $value, $type ) {

	if ( 'attr' === $type ) {
		return esc_attr( $value );
	} elseif ( 'url' === $type ) {
		return esc_url( $value );
	}

	return esc_attr( $value );
}

/**
 * Retrieved the value of the option in the wp_option table.
 *
 * @param string $option - option name to be deleted.
 * @param string $prefix - prefix of the option.
 */
function get_mo_wc_option( $option, $prefix = null ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Legacy function name, used throughout codebase.
	$string = ( null === $prefix ? 'mo_wc_customer_validation_' : $prefix ) . $option;
	return apply_filters( 'get_mo_wc_option', get_site_option( $string ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Legacy hook name for backward compatibility.
}

/**
 * Updates the option set in the wp_option table.
 *
 * @param string $option - option name to be deleted.
 * @param string $value - value of the option.
 * @param string $prefix - prefix of the option.
 */
function update_mo_wc_option( $option, $value, $prefix = null ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Legacy function name, used throughout codebase.
	$string = ( null === $prefix ? 'mo_wc_customer_validation_' : $prefix ) . $option;
	update_site_option( $string, apply_filters( 'update_mo_wc_option', $value, $string ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Legacy hook name for backward compatibility.
}

/**
 * Deletes the option set in the wp_option table.
 *
 * @param string $option - option name to be deleted.
 * @param string $prefix - prefix of the option.
 */
function delete_mo_wc_option( $option, $prefix = null ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Legacy function name, used throughout codebase.
	$string = ( null === $prefix ? 'mo_wc_customer_validation_' : $prefix ) . $option;
	delete_site_option( $string );
}

/**
 * Returns the plugin details like version, plan name.
 *
 * @param object $obj - object of the class.
 */
function get_mo_wc_class( $obj ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Legacy function name, used throughout codebase.
	$namespace_class = get_class( $obj );
	return substr( $namespace_class, strrpos( $namespace_class, '\\' ) + 1 );
}

/**
 * Returns the plugin details like version, plan name.
 */
function mowc_initialize_wc_package_json() {
			$package = wp_json_encode(
				array(
					'name'         => 'miniorange-otp-verification',
					'version'      => '4.4.0',
					'type'         => 'MiniOrangeGateway',
					'testmode'     => false,
					'failmode'     => false,
					'hostname'     => 'https://login.xecurify.com',
					'dcustomerkey' => '16555',
					'dapikey'      => 'fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq',
					'sslverify'    => false,
					'session'      => 'TRANSIENT',
					'typeplan'     => 'wp_otp_verification_basic_plan',
					'licensename'  => 'WP_OTP_VERIFICATION_PLUGIN',
				)
			);
			return $package;
}

/**
 * Determines if the WooCommerce checkout page uses block-based checkout.
 *
 * This version does not rely on WooCommerce Blocks PHP classes being loaded.
 * Instead, it inspects the WooCommerce Checkout page content for the
 * `woocommerce/checkout` block, so it can be safely called early (e.g. in
 * constructors) without depending on plugin load order.
 *
 * @return bool
 */
function mowc_is_block_based_checkout() {
	if ( ! function_exists( 'is_plugin_active' ) ) {
		include_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	if ( ! is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
		return false;
	}

	// Get the Checkout page ID directly from WooCommerce options.
	$checkout_page_id = (int) get_option( 'woocommerce_checkout_page_id' );
	if ( $checkout_page_id <= 0 ) {
		return false;
	}

	$checkout_page = get_post( $checkout_page_id );
	if ( ! $checkout_page || empty( $checkout_page->post_content ) ) {
		return false;
	}

	// Prefer core has_block() if available (WP 5+).
	if ( function_exists( 'has_block' ) ) {
		return has_block( 'woocommerce/checkout', $checkout_page );
	}

	// Fallback: simple string search for the block name in post content.
	return ( false !== strpos( $checkout_page->post_content, 'woocommerce/checkout' ) );
}
