<?php

/**
 * @package storzen
 * @since   1.0.0
 */

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

if (! class_exists('Storzen_Init')) {

	class Storzen_Init
	{

		/** @var static */
		protected static $instance;

		public function __construct()
		{
			// Elementor may load before this plugin; hook immediately if Elementor is already booted.
			if (did_action('elementor/loaded')) {
				$this->register_elementor_editor_assets();
			} else {
				add_action('elementor/loaded', array($this, 'register_elementor_editor_assets'));
			}

			// Front-end assets — priority 10 for CSS/general JS.
			add_action('wp_enqueue_scripts', array($this, 'plugin_assets'), 10);
			add_action('wp_enqueue_scripts', array($this, 'finalize_font_awesome_cdn'), 101);

			// After WC core (10) so handles are registered.
			// After WooCommerce Blocks checkout/cart dequeue (20) — they remove wc-checkout when a block renders.
			add_action('wp_enqueue_scripts', array($this, 'enqueue_checkout_scripts'), 100);

			// v1.2 — Enqueue new single-product widget CSS only on product pages.
			add_action('wp_enqueue_scripts', array($this, 'enqueue_product_single_new_styles'), 15);
			// v1.2.1 — Enqueue new cart widget CSS only on the cart page.
			add_action('wp_enqueue_scripts', array($this, 'enqueue_cart_new_styles'), 15);
			// v1.2.2 — Archive toolbar widget CSS on WooCommerce archive pages.
			add_action('wp_enqueue_scripts', array($this, 'enqueue_archive_styles'), 15);
			// v1.1.3 — Trust Badges + Breadcrumbs CSS on product + cart + checkout pages.
			add_action('wp_enqueue_scripts', array($this, 'enqueue_v113_widget_styles'), 15);

			// Admin: override Storzen asset URLs to point to our bundled copy
			add_filter('admin_enqueue_scripts', array($this, 'override_pk_asset_urls'), 5);

			// Load dependency files (elementor, functions, admin panel)
			$this->load_plugin_dependency_files();
		}

		// ── Front-end ─────────────────────────────────────────────────────────

		/**
		 * Register shop sidebar script globally so Elementor editor/preview can enqueue it.
		 */
		public function register_shop_sidebar_script()
		{
			if (wp_script_is('storzen-shop-sidebar', 'registered')) {
				return;
			}
			wp_register_script(
				'storzen-shop-sidebar',
				STORZEN_JS . '/shop-sidebar-widget.js',
				array('jquery', 'jquery-ui-slider'),
				STORZEN_VERSION,
				true
			);
			wp_localize_script(
				'storzen-shop-sidebar',
				'WcommeroProShopSidebar',
				array(
					'ajaxUrl' => admin_url('admin-ajax.php'),
					'action'  => 'storzen_shop_sidebar_filter',
					'nonce'   => wp_create_nonce('storzen_shop_sidebar'),
				)
			);
		}

		/**
		 * Ensure jQuery UI Slider and our handle exist when the Elementor editor loads
		 * (wp_enqueue_scripts does not run on the editor screen the same way as the front end).
		 */
		public function register_elementor_editor_assets()
		{
			add_action('elementor/editor/before_enqueue_scripts', array($this, 'ensure_editor_shop_sidebar_assets'), 12);
		}

		public function ensure_editor_shop_sidebar_assets()
		{
			$this->register_shop_sidebar_script();
			wp_enqueue_script('jquery-ui-slider');
		}

		public function plugin_assets()
		{
			$this->load_plugin_css();
			$this->load_plugin_js();
		}

		public static function storzen_fonts_url()
		{
			$fonts_url    = '';
			$font_families = array();
			// Allow themes/plugins to disable Google Fonts via filter
			// Use apply_filters instead of translation to avoid early loading issues
			if (apply_filters('storzen_enable_google_fonts', true)) {
				$font_families[] = 'Montserrat:ital,wght@0,100..900;1,100..900&display=swap';
				$font_families[] = 'Roboto:ital,wght@0,100..900;1,100..900&display=swap';
				$query_args = array(
					'family'  => urlencode(implode('|', $font_families)),
					'display' => 'swap',
				);
				$fonts_url = add_query_arg($query_args, 'https://fonts.googleapis.com/css2');
			}
			return esc_url_raw($fonts_url);
		}

		/**
		 * Load Font Awesome 6 — theme bundle first, CDN fallback (keeps plugin size small).
		 *
		 * @return string Style handle.
		 */
		private function enqueue_font_awesome()
		{
			if (wp_style_is('fontawesome', 'registered')) {
				wp_enqueue_style('fontawesome');
				return 'fontawesome';
			}

			if (wp_style_is('storzen-fontawesome', 'registered') || wp_style_is('storzen-fontawesome', 'enqueued')) {
				if (! wp_style_is('storzen-fontawesome', 'enqueued')) {
					wp_enqueue_style('storzen-fontawesome');
				}
				return 'storzen-fontawesome';
			}

			if (wp_style_is('storzen-fontawesome', 'registered') || wp_style_is('storzen-fontawesome', 'enqueued')) {
				if (! wp_style_is('storzen-fontawesome', 'enqueued')) {
					wp_enqueue_style('storzen-fontawesome');
				}
				return 'storzen-fontawesome';
			}

			$version = apply_filters('storzen_fontawesome_version', '6.5.1');
			$cdn_url   = apply_filters(
				'storzen_fontawesome_cdn_url',
				'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/' . $version . '/css/all.min.css'
			);

			wp_enqueue_style(
				'storzen-fontawesome',
				$cdn_url,
				array(),
				$version
			);

			return 'storzen-fontawesome';
		}

		/**
		 * Dequeue Elementor FA5 on Storzen pages; prefer theme FA6 Pro over plugin CDN.
		 */
		public function finalize_font_awesome_cdn()
		{
			if ( ! wp_style_is( 'storzen-main', 'enqueued' ) ) {
				return;
			}

			wp_dequeue_style('font-awesome-5-all');
			wp_dequeue_style('font-awesome-4-shim');
			wp_dequeue_style('font-awesome');

			if (wp_style_is('fontawesome', 'registered')) {
				wp_dequeue_style( 'storzen-fontawesome' );
				wp_enqueue_style('fontawesome');
				return;
			}

			if ( ! wp_style_is( 'storzen-fontawesome', 'enqueued' ) ) {
				$this->enqueue_font_awesome();
			}
		}

		public function load_plugin_css()
		{
			wp_enqueue_style('storzen-font',  self::storzen_fonts_url(), array(), STORZEN_VERSION, 'all');
			wp_enqueue_style('storzen-grid',  STORZEN_CSS . '/bootstrap-grid.css',     array(), STORZEN_VERSION, 'all');
			wp_enqueue_style('swiper-bundle',      STORZEN_CSS . '/swiper-bundle.min.css',  array(), STORZEN_VERSION, 'all');
			wp_enqueue_style('nice-select',        STORZEN_CSS . '/nice-select.css',        array(), STORZEN_VERSION, 'all');
			$main_deps = array( $this->enqueue_font_awesome() );
			if (class_exists('WooCommerce') && wp_style_is('woocommerce-general', 'registered')) {
				$main_deps[] = 'woocommerce-general';
			}
			wp_enqueue_style('storzen-main', STORZEN_CSS . '/main.css', $main_deps, STORZEN_VERSION, 'all');
			if (class_exists('WooCommerce')) {
				wp_register_style(
					'storzen-checkout-widgets',
					STORZEN_CSS . '/checkout-widgets.css',
					array('storzen-main'),
					STORZEN_VERSION,
					'all'
				);
				wp_enqueue_style('storzen-checkout-widgets');
				wp_register_style(
					'storzen-thankyou-widgets',
					STORZEN_CSS . '/thankyou-widgets.css',
					array('storzen-main'),
					STORZEN_VERSION,
					'all'
				);
				wp_enqueue_style('storzen-thankyou-widgets');
				wp_register_style(
					'storzen-my-account-widgets',
					STORZEN_CSS . '/my-account-widgets.css',
					array('storzen-main'),
					STORZEN_VERSION,
					'all'
				);
				wp_enqueue_style('storzen-my-account-widgets');

				// v1.2 — new single-product widgets CSS (registered only; enqueued on is_product() pages).
				wp_register_style(
					'storzen-product-single-new',
					STORZEN_CSS . '/sz-product-single-new-widgets.css',
					array( 'storzen-main' ),
					STORZEN_VERSION,
					'all'
				);

					// v1.2.1 — New cart widget styles.
					wp_register_style(
						'storzen-cart-new',
						STORZEN_CSS . '/sz-cart-new-widgets.css',
						array( 'storzen-main' ),
						STORZEN_VERSION,
						'all'
					);

					// v1.2.2 — Archive toolbar widget styles.
					wp_register_style(
						'storzen-archive-toolbar',
						STORZEN_CSS . '/sz-archive-toolbar-widgets.css',
						array( 'storzen-main' ),
						STORZEN_VERSION,
						'all'
					);

					// v1.1.3 — Trust Badges + Product Breadcrumbs widget styles.
					wp_register_style(
						'storzen-v113-widgets',
						STORZEN_CSS . '/sz-v113-widgets.css',
						array( 'storzen-main' ),
						STORZEN_VERSION,
						'all'
					);
			}
		}

	public function load_plugin_js()
	{
		wp_enqueue_script('owl-carousel',                STORZEN_JS . '/owl.carousel.min.js',      array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('imagesloaded',                STORZEN_JS . '/imagesloaded.pkgd.min.js', array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('magnific',                    STORZEN_JS . '/magnific.min.js',          array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('isotope',                     STORZEN_JS . '/isotope.pkgd.min.js',      array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('swiper-bundle',               STORZEN_JS . '/swiper-bundle.min.js',     array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('storzen-main',           STORZEN_JS . '/swp-main.js',              array('jquery'), STORZEN_VERSION, true);
		wp_enqueue_script('storzen-elementor-script', STORZEN_JS . '/elementor-script.js',   array('jquery'), 1.9, true);

		// Register shop sidebar script for use by widgets
		$this->register_shop_sidebar_script();

		// Register My Account tabs script for use by My Account Full widget
		wp_register_script(
			'storzen-my-account-tabs',
			STORZEN_JS . '/my-account-tabs.js',
			array('jquery'),
			STORZEN_VERSION,
			true
		);
	}

		/**
		 * True on the real checkout page, or in Elementor preview/edit when the document
		 * includes Storzen checkout widgets (is_checkout() is often false in the preview iframe).
		 *
		 * @return bool
		 */
		private function szp_should_enqueue_checkout_scripts()
		{
			if (function_exists('is_checkout') && is_checkout()) {
				return (bool) apply_filters('szp_should_enqueue_checkout_scripts', true, 'is_checkout');
			}
			if (! class_exists('\Elementor\Plugin')) {
				return (bool) apply_filters('szp_should_enqueue_checkout_scripts', false, 'no_elementor');
			}
			$pl = \Elementor\Plugin::$instance;
			$in_elementor = false;
			if (! empty($pl->editor) && method_exists($pl->editor, 'is_edit_mode') && $pl->editor->is_edit_mode()) {
				$in_elementor = true;
			}
			if (! empty($pl->preview) && method_exists($pl->preview, 'is_preview_mode') && $pl->preview->is_preview_mode()) {
				$in_elementor = true;
			}
			if (! $in_elementor) {
				return (bool) apply_filters('szp_should_enqueue_checkout_scripts', false, 'not_elementor_context');
			}
			$post_id = (int) get_queried_object_id();
			if (! $post_id) {
				global $post;
				$post_id = isset($post->ID) ? (int) $post->ID : 0;
			}
			if (! $post_id) {
				return (bool) apply_filters('szp_should_enqueue_checkout_scripts', false, 'no_post');
			}
			$raw = get_post_meta($post_id, '_elementor_data', true);
			if (! is_string($raw) || $raw === '') {
				return (bool) apply_filters('szp_should_enqueue_checkout_scripts', false, 'no_elementor_data');
			}
			$match = (bool) preg_match('/storzen-checkout/', $raw);
			return (bool) apply_filters('szp_should_enqueue_checkout_scripts', $match, 'elementor_meta');
		}

		/**
		 * Enqueue WooCommerce checkout scripts for Elementor split-widget checkout.
		 *
		 * Runs at priority 100 so WooCommerce Blocks (priority 20) cannot dequeue wc-checkout first.
		 *
		 * When the checkout page is built with Elementor widgets (no [woocommerce_checkout]
		 * shortcode), WooCommerce may not enqueue wc-checkout. We force it when needed.
		 *
		 * Elementor preview/edit iframes often resolve a template post where is_checkout() is false;
		 * we also load when the current document’s Elementor data includes Storzen checkout widgets.
		 */
		public function enqueue_checkout_scripts()
		{
			if (! class_exists('WooCommerce') || ! function_exists('is_checkout')) {
				return;
			}
			if (function_exists('is_order_received_page') && is_order_received_page()) {
				return;
			}
			if (! $this->szp_should_enqueue_checkout_scripts()) {
				return;
			}

			// Force WooCommerce to load its frontend checkout scripts even when the
			// page uses Elementor widgets instead of the [woocommerce_checkout] shortcode.
			if (! wp_script_is('wc-checkout', 'registered')) {
				// Trigger WC's own script loader if available (WC 3.3+).
				if (class_exists('WC_Frontend_Scripts') && method_exists('WC_Frontend_Scripts', 'load_scripts')) {
					WC_Frontend_Scripts::load_scripts();
				}
			}

			// If wc-checkout is still not registered (very old WC or custom setup),
			// locate and register it manually from WC's assets directory.
			if (! wp_script_is('wc-checkout', 'registered') && defined('WC_PLUGIN_URL')) {
				$wc_checkout_js = WC_PLUGIN_URL . '/assets/js/frontend/checkout' . (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min') . '.js';
				wp_register_script(
					'wc-checkout',
					$wc_checkout_js,
					array('jquery', 'woocommerce', 'wc-country-select', 'wc-address-i18n'),
					defined('WC_VERSION') ? WC_VERSION : STORZEN_VERSION,
					true
				);
			}

			// Ensure wc-checkout is enqueued (WC may have registered but not enqueued it).
			if (wp_script_is('wc-checkout', 'registered') && ! wp_script_is('wc-checkout', 'enqueued')) {
				wp_enqueue_script('wc-checkout');
			}

			// Now enqueue our Elementor checkout bridge (depends on wc-checkout).
			if (wp_script_is('wc-checkout', 'registered')) {
				wp_enqueue_script(
					'storzen-checkout-elementor',
					STORZEN_JS . '/checkout-elementor.js',
					array('jquery', 'wc-checkout'),
					STORZEN_VERSION,
					true
				);
			}
		}

		// ── Admin ─────────────────────────────────────────────────────────────

		/**
		 * When the bundled Storzen enqueues sz-admin, point it to our local copy.
		 * Storzen uses SZ_URL which we already pointed at lib/storzen/ in the
		 * main plugin file, so this is a safety net in case SZ_URL is already set
		 * by a standalone copy.
		 */
		public function override_pk_asset_urls($hook)
		{
			if (strpos($hook, 'storzen') === false) {
				return;
			}
			// Re-register sz-admin assets pointing to our bundled files
			$pk_url = STORZEN_ROOT_URL . 'lib/storzen/';
			wp_deregister_style('sz-admin');
			wp_deregister_script('sz-admin');
			wp_register_style('sz-admin', $pk_url . 'admin/css/admin.css', array(), STORZEN_VERSION);
			wp_register_script('sz-admin', $pk_url . 'admin/js/admin.js',   array('jquery'), STORZEN_VERSION, true);

			// Also enqueue the required-fields JS (our custom layer on top of sz-admin)
			wp_enqueue_script(
				'szp-required-fields',
				STORZEN_ROOT_URL . 'assets/js/admin-required-fields.js',
				array('sz-admin'),
				STORZEN_VERSION,
				true
			);
		}

		// ── Dependency files ──────────────────────────────────────────────────

		public function load_plugin_dependency_files()
		{

			// License manager
			$license_file = STORZEN_INC . '/class-storzen-license.php';
			if ( file_exists( $license_file ) ) {
				require_once $license_file;
				Storzen_License::instance();
			}

			// TGM Plugin Activation
			if (! class_exists('TGM_Plugin_Activation')) {
				$tgm = STORZEN_ROOT_PATH . 'lib/tgma/activate.php';
				if (file_exists($tgm)) {
					require $tgm;
				}
			}

			// ── Storzen Modules system (registry + AJAX save + module loader) ──────
			// Boots Storzen_Modules on plugins_loaded (priority 6) and loads any
			// enabled module class files on init (priority 15). Settings option key
			// `storzen_modules_settings` is shared with the free plugin so toggles
			// and per-module configuration carry across the free → Pro upgrade.
			$sz_modules = STORZEN_INC . '/class-storzen-modules.php';
			if ( file_exists( $sz_modules ) ) {
				require_once $sz_modules;
			}

			// Modules admin page (card UI, gear settings, PRO ribbon) — admin only.
			$sz_modules_page = STORZEN_INC . '/class-storzen-modules-admin-page.php';
			if ( is_admin() && file_exists( $sz_modules_page ) ) {
				require_once $sz_modules_page;
				// Init is auto-called at the bottom of the file; no explicit call needed.
			}

			// "Leave a review" admin notice (shown after 7 days) — admin only.
			$sz_review_notice = STORZEN_INC . '/class-storzen-review-notice.php';
			if ( is_admin() && file_exists( $sz_review_notice ) ) {
				require_once $sz_review_notice;
				new Storzen_Review_Notice();
			}

			$includes = array(
				array(
					'file-name' => 'storzen-elementor-widgets-init',
					'file-path' => STORZEN_ELEMENTOR,
				),
				array(
					'file-name' => 'functions',
					'file-path' => STORZEN_INC,
				),
				array(
					'file-name' => 'cart-functionality',
					'file-path' => STORZEN_INC,
				),
			);

			foreach ($includes as $file) {
				$path = $file['file-path'] . '/' . $file['file-name'] . '.php';
				if (file_exists($path)) {
					require $path;
				}
			}

			// WooCommerce: checkout coupon template (inner row keeps flex when jQuery sets form display:block).
			$szp_coupon_tpl = STORZEN_INC . '/woocommerce-checkout-form-coupon.php';
			if (class_exists('WooCommerce') && file_exists($szp_coupon_tpl)) {
				require_once $szp_coupon_tpl;
			}

			// ── Storzen admin panel ─────────────────────────────────────────
			// Boot on init (after translations load) so Panel can register admin_menu hooks.
			add_action('init', array($this, 'load_admin_panel'), 20);

			// Elementor JSON template import (admin submenu + AJAX).
			$import_tpl = STORZEN_INC . '/class-storzen-elementor-template-import.php';
			if (file_exists($import_tpl)) {
				require_once $import_tpl;
				if (class_exists('Storzen_Elementor_Template_Import')) {
					Storzen_Elementor_Template_Import::init();
				}
			}

			// Shop With Sidebar — AJAX filters (requires shop-sidebar-helpers.php loaded via functions.php).
			$szp_ajax = STORZEN_INC . '/class-storzen-shop-sidebar-ajax.php';
			if (file_exists($szp_ajax) && function_exists('storzen_shop_sidebar_sanitize_settings')) {
				require_once $szp_ajax;
			}

			// Shop Details → Page Templates: apply Elementor library templates to WC views.
			$wc_elementor_tpl = STORZEN_INC . '/class-storzen-wc-elementor-templates.php';
			if (file_exists($wc_elementor_tpl)) {
				require_once $wc_elementor_tpl;
			}
		}

		public function load_admin_panel()
		{
			$panel = STORZEN_INC . '/admin-panel.php';
			if (file_exists($panel)) {
				require_once $panel;
			}
		}
		/**
		 * Conditionally enqueue the new single-product widget stylesheet.
		 *
		 * Runs at priority 15 (after plugin_assets at 10) so storzen-main
		 * is already registered as a dependency.
		 *
		 * @since 1.2.0
		 */
		public function enqueue_product_single_new_styles() {
			if ( ! function_exists( 'is_product' ) || ! is_product() ) {
				return;
			}
			if ( wp_style_is( 'storzen-product-single-new', 'registered' ) ) {
				wp_enqueue_style( 'storzen-product-single-new' );
			}
		}

		/**
		 * Conditionally enqueue new cart-page widget stylesheet.
		 *
		 * @since 1.2.1
		 */
		public function enqueue_cart_new_styles() {
			if ( ! function_exists( 'is_cart' ) || ! is_cart() ) {
				return;
			}
			if ( wp_style_is( 'storzen-cart-new', 'registered' ) ) {
				wp_enqueue_style( 'storzen-cart-new' );
			}
		}

		/**
		 * Conditionally enqueue archive toolbar widget stylesheet.
		 * Loads on all WooCommerce archive contexts (shop, category, tag, search).
		 *
		 * @since 1.2.2
		 */
		public function enqueue_archive_styles() {
			if ( ! function_exists( 'is_woocommerce' ) ) {
				return;
			}
			if ( ! is_woocommerce() && ! is_shop() ) {
				return;
			}
			if ( wp_style_is( 'storzen-archive-toolbar', 'registered' ) ) {
				wp_enqueue_style( 'storzen-archive-toolbar' );
			}
		}

		/**
		 * Conditionally enqueue v1.1.3 widget stylesheet.
		 * Loads on product pages (breadcrumbs) and cart/checkout pages (trust badges).
		 *
		 * @since 1.1.3
		 */
		public function enqueue_v113_widget_styles() {
			if ( ! wp_style_is( 'storzen-v113-widgets', 'registered' ) ) {
				return;
			}
			$load = ( function_exists( 'is_product' )  && is_product() )
				 || ( function_exists( 'is_cart' )     && is_cart() )
				 || ( function_exists( 'is_checkout' ) && is_checkout() );

			if ( $load ) {
				wp_enqueue_style( 'storzen-v113-widgets' );
			}
		}

	} // end class

	add_action('plugins_loaded', function () {
		new Storzen_Init();
	}, 5);
}
