<?php
/**
 * Main Plugin class.
 *
 * @package Ugcify
 */

namespace Ugcify;

use Ugcify\Elementor\Integration as ElementorIntegration;
use Ugcify\Helpers\FeatureGate;
use Ugcify\License\Licensing;
use Ugcify\License\LicenseHelper;
use Ugcify\License\Updater;
use Ugcify\Rest\V1\LicenseController;
use Ugcify\Tracking\Telemetry;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main Plugin class.

 * phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
 */
class Plugin {

	/**
	 * Creator foundation services.
	 *
	 * @var array<string,object>
	 */
	private $influencer_services = array();

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->init_hooks();
		$this->load_dependencies();
	}

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	private function init_hooks() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_assets' ), 100 );
		add_action( 'ugcify_assets_needed', array( $this, 'mark_ugcify_needed' ) );
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
		add_action( 'init', array( $this, 'maybe_ensure_creator_portal_page' ), 20 );
		add_action( 'wp_head', array( $this, 'print_creator_lms_compat_shim' ), 1 );
		add_action( 'wp_head', array( $this, 'inject_social_share_meta_tags' ), 2 );
		add_action( 'admin_head', array( $this, 'print_creator_lms_compat_shim' ), 1 );
		add_action( 'init', array( $this, 'schedule_share_cleanup_cron' ) );
		add_action( 'ugcify_cleanup_share_tokens', array( $this, 'cleanup_expired_share_tokens' ) );

		// License state filters — consumed by the admin JS localize data.
		add_filter( 'ugcify_is_pro_active', array( $this, 'filter_is_pro_active' ) );
		add_filter( 'ugcify_license_plan', array( $this, 'filter_license_plan' ) );
		add_filter( 'ugcify_license_status', array( $this, 'filter_license_status' ) );

		// AJAX handler: triggered by LicensePage.jsx after activation to install the pro ZIP.
		add_action( 'wp_ajax_ugcify_install_pro_build', array( $this, 'ajax_install_pro_build' ) );

		// AJAX handler: triggered by LicensePage.jsx after deactivation to restore the
		// free build from WordPress.org (replaces the pro build with the free version).
		add_action( 'wp_ajax_ugcify_install_free_build', array( $this, 'ajax_install_free_build' ) );
	}

	/**
	 * Load plugin dependencies.
	 *
	 * @return void
	 */
	private function load_dependencies() {
		// Initialize plugin updater (handles pro/free update routing).
		if ( file_exists( UGCIFY_PATH . 'includes/License/Updater.php' ) ) {
			require_once UGCIFY_PATH . 'includes/License/Updater.php';
			new Updater( UGCIFY_BASENAME );
		}

		// Boot telemetry (PostHog-backed via linno/telemetry SDK).
		Telemetry::init();
		
		// Load admin menu and notice suppressor.
		if ( is_admin() ) {
			require_once UGCIFY_PATH . 'includes/Admin/Menu.php';
			require_once UGCIFY_PATH . 'includes/Admin/AdminNoticeSuppressor.php';
			new Admin\Menu();
			new Admin\AdminNoticeSuppressor();

			// Clear any stale coupon failure notices from prior versions.
			if ( get_option( 'ugcify_reward_failures' ) ) {
				delete_option( 'ugcify_reward_failures' );
			}
		}

		// Load frontend assets handler.
		require_once UGCIFY_PATH . 'includes/Frontend/Assets.php';
		require_once UGCIFY_PATH . 'includes/Frontend/ShareMetaInjector.php';

		// Load Gutenberg blocks.
		require_once UGCIFY_PATH . 'includes/Blocks/ReviewsBlock.php';


		// Load form components.
		require_once UGCIFY_PATH . 'includes/Form/FormRenderer.php';
		require_once UGCIFY_PATH . 'includes/Review/ReviewShortcode.php';

		// Initialize form renderer (always needed for display).
		$form_renderer = new Form\FormRenderer();

		// GROWTH: customer upload form — visitors can submit UGC.
		if ( FeatureGate::is_enabled( 'customer_upload_form' ) && file_exists( UGCIFY_PATH . 'includes/Form/FormShortcode.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Form/FormShortcode.php';
			new Form\FormShortcode( $form_renderer );
		}

		// Creator portal foundation services.
		if ( file_exists( UGCIFY_PATH . 'includes/Influencer/Settings.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Influencer/Settings.php';
			require_once UGCIFY_PATH . 'includes/Influencer/Capabilities.php';
			require_once UGCIFY_PATH . 'includes/Database/UserRepository.php';
			require_once UGCIFY_PATH . 'includes/Influencer/InvitationService.php';
			require_once UGCIFY_PATH . 'includes/Influencer/RightsManager.php';
			require_once UGCIFY_PATH . 'includes/Influencer/InfluencerManager.php';
			require_once UGCIFY_PATH . 'includes/Influencer/PortalRenderer.php';
			require_once UGCIFY_PATH . 'includes/Influencer/PortalShortcode.php';

			$creator_user_repository = new Database\UserRepository();
			$invitation_service      = new Influencer\InvitationService();
			$rights_manager          = new Influencer\RightsManager( $creator_user_repository );
			$influencer_manager      = new Influencer\InfluencerManager( $creator_user_repository, $rights_manager, $invitation_service );
			$portal_renderer         = new Influencer\PortalRenderer( $influencer_manager, $rights_manager, $invitation_service );

			$this->influencer_services = array(
				'user_repository'    => $creator_user_repository,
				'invitation_service' => $invitation_service,
				'rights_manager'     => $rights_manager,
				'influencer_manager' => $influencer_manager,
				'portal_renderer'    => $portal_renderer,
			);

			new Influencer\PortalShortcode( $portal_renderer );
		}

		// Initialize shortcodes and blocks.
		new Review\ReviewShortcode( $form_renderer );
		new Blocks\ReviewsBlock();

		// Load Elementor integration.
		new ElementorIntegration();

		// WooCommerce integration.
		if ( class_exists( 'WooCommerce' ) ) {
			// Basic WC hooks (product meta, order events) — always enabled.
			require_once UGCIFY_PATH . 'includes/Integrations/WooCommerce/Hooks.php';
			new Integrations\WooCommerce\Hooks( $form_renderer );

			// BUSINESS: A/B testing suite.
			if ( FeatureGate::is_enabled( 'ab_testing' ) && file_exists( UGCIFY_PATH . 'includes/Analytics/ABTestAnalytics.php' ) ) {
				require_once UGCIFY_PATH . 'includes/Analytics/ABTestAnalytics.php';
				new Analytics\ABTestAnalytics();
			}

			// BUSINESS: advanced gamification — points dashboard & checkout redemption.
			if ( FeatureGate::is_enabled( 'advanced_gamification' ) && file_exists( UGCIFY_PATH . 'includes/Points/PointsManager.php' ) ) {
				require_once UGCIFY_PATH . 'includes/Integrations/WooCommerce/MyAccountDashboard.php';
				require_once UGCIFY_PATH . 'includes/Integrations/WooCommerce/CheckoutRedemption.php';
				new Integrations\WooCommerce\MyAccountDashboard();
				new Integrations\WooCommerce\CheckoutRedemption();
			}

			// Influencer invitations WC tab — only when Influencer module is present.
			if ( ! empty( $this->influencer_services ) ) {
				require_once UGCIFY_PATH . 'includes/Integrations/WooCommerce/MyAccountInfluencerInvitations.php';
				new Integrations\WooCommerce\MyAccountInfluencerInvitations(
					$this->influencer_services['user_repository'],
					$this->influencer_services['invitation_service']
				);
			}
		}

		// SEO: Product + Review schema (frontend), Yoast content analysis (admin).
		require_once UGCIFY_PATH . 'includes/SEO/Schema.php';
		require_once UGCIFY_PATH . 'includes/SEO/YoastIntegration.php';
		new SEO\Schema();
		new SEO\YoastIntegration();

		// Email module: settings, sender and placeholders are always loaded
		// (the admin UI reads/saves email settings even on free).
		require_once UGCIFY_PATH . 'includes/Email/EmailSettings.php';
		require_once UGCIFY_PATH . 'includes/Email/EmailPlaceholders.php';
		require_once UGCIFY_PATH . 'includes/Email/EmailSender.php';
		require_once UGCIFY_PATH . 'includes/Email/ReviewRequestSettings.php';

		// GROWTH: review-request emails; PRO: advanced email automation.
		if (
			( FeatureGate::is_enabled( 'review_request_email' ) || FeatureGate::is_enabled( 'email_automation' ) )
			&& file_exists( UGCIFY_PATH . 'includes/Email/EmailTriggers.php' )
		) {
			require_once UGCIFY_PATH . 'includes/Email/EmailTriggers.php';
			require_once UGCIFY_PATH . 'includes/Email/ReviewRequestScheduler.php';
			new Email\EmailTriggers();
			new Email\ReviewRequestScheduler();
		}

		// PRO: coupon rewards — generate discount coupons on review approval.
		if ( FeatureGate::is_enabled( 'reward_coupons' ) && file_exists( UGCIFY_PATH . 'includes/Rewards/RewardCoupon.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Rewards/RewardCoupon.php';
		}

		// BUSINESS: advanced gamification — points, badges, leaderboards.
		if ( FeatureGate::is_enabled( 'advanced_gamification' ) && file_exists( UGCIFY_PATH . 'includes/Points/PointsManager.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Rewards/RewardTrigger.php';
			require_once UGCIFY_PATH . 'includes/Rewards/BadgeResolver.php';
			require_once UGCIFY_PATH . 'includes/Rewards/BadgeProgression.php';
			require_once UGCIFY_PATH . 'includes/Database/PointsRepository.php';
			require_once UGCIFY_PATH . 'includes/Points/PointsManager.php';
			require_once UGCIFY_PATH . 'includes/Points/TierManager.php';
			require_once UGCIFY_PATH . 'includes/Points/RewardRecalculator.php';
			new Rewards\RewardTrigger();
			new Rewards\BadgeProgression();
		}

		// GROWTH: social hashtag import — Instagram OAuth + background sync cron.
		if ( FeatureGate::is_enabled( 'social_import' ) && file_exists( UGCIFY_PATH . 'includes/Integrations/Social/InstagramOAuth.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Automation/SocialCron.php';
			require_once UGCIFY_PATH . 'includes/Integrations/Social/InstagramOAuth.php';
			new Integrations\Social\InstagramOAuth();
			new Automation\SocialCron();
		}

		// PRO: Mail Mint advanced automation flows + coupon rewards.
		if ( FeatureGate::is_enabled( 'advanced_email_integration' ) && defined( 'MAILMINT' ) && file_exists( UGCIFY_PATH . 'includes/Integrations/MailMint/MailMint.php' ) ) {
			require_once UGCIFY_PATH . 'includes/Integrations/MailMint/MailMint.php';
			require_once UGCIFY_PATH . 'includes/Integrations/MailMint/ConnectorUGC.php';
			require_once UGCIFY_PATH . 'includes/Integrations/MailMint/Triggers/UGCTriggers.php';
			Integrations\MailMint\ConnectorUGC::get_instance();
		}
	}

	/**
	 * Register REST API routes.
	 *
	 * @return void
	 */
	public function register_rest_routes() {
		require_once UGCIFY_PATH . 'includes/Admin/API.php';
		$api = new Admin\API();
		$api->register_routes();

		// License REST routes.
		$license_controller = new LicenseController();
		$license_controller->register_routes();
	}

	// =========================================================================
	// License state filter callbacks
	// =========================================================================

	/**
	 * Whether a valid license is active.
	 *
	 * @param bool $active Default false.
	 * @return bool
	 */
	public function filter_is_pro_active( $active ) {
		return LicenseHelper::is_pro_active();
	}

	/**
	 * Return the canonical plan slug for the current license.
	 *
	 * @param string $plan Default empty string.
	 * @return string
	 */
	public function filter_license_plan( $plan ) {
		return LicenseHelper::get_license_plan();
	}

	/**
	 * Return the license status string.
	 *
	 * @param string $status Default 'inactive'.
	 * @return string 'active' | 'deactivate' | 'inactive'
	 */
	public function filter_license_status( $status ) {
		$effective_status = Licensing::get_license_status();
		return $effective_status ? $effective_status : $status;
	}

	/**
	 * Auto-create or reassign the creator portal page when enabled.
	 *
	 * @return void
	 */
	public function maybe_ensure_creator_portal_page() {
		if ( ! class_exists( '\\Ugcify\\Influencer\\Settings' ) ) {
			return;
		}

		if ( Influencer\Settings::is_enabled() ) {
			Influencer\Settings::ensure_portal_page();
		}
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook The current admin page hook.
	 * @return void
	 */
	public function enqueue_admin_assets( $hook ) {
		// Only load on our plugin pages.
		if ( strpos( $hook, 'ugcify' ) === false ) {
			return;
		}

		// Load WordPress native media uploader assets for admin attachment handling.
		wp_enqueue_media();

		// Load WordPress editor scripts for TinyMCE (used by email settings).
		wp_enqueue_editor();

		$admin_app_path     = UGCIFY_PATH . 'assets/admin/app.js';
		$admin_app_version  = file_exists( $admin_app_path ) ? (string) filemtime( $admin_app_path ) : UGCIFY_VERSION;
		$admin_css_path     = UGCIFY_PATH . 'assets/admin/styles.css';
		$admin_css_version  = file_exists( $admin_css_path ) ? (string) filemtime( $admin_css_path ) : UGCIFY_VERSION;
		$admin_app_css_path = UGCIFY_PATH . 'assets/admin/app.css';
		$admin_app_css_ver  = file_exists( $admin_app_css_path ) ? (string) filemtime( $admin_app_css_path ) : UGCIFY_VERSION;

		// Enqueue admin React app.
		wp_enqueue_script(
			'ugcify-admin',
			UGCIFY_URL . 'assets/admin/app.js',
			array( 'wp-element', 'wp-i18n', 'wp-components', 'wp-data' ),
			$admin_app_version,
			true
		);

		// Set script translations for the admin app.
		wp_set_script_translations(
			'ugcify-admin',
			'ugcify',
			UGCIFY_PATH . 'languages'
		);

		// Enqueue admin styles.
		wp_enqueue_style(
			'ugcify-admin',
			UGCIFY_URL . 'assets/admin/styles.css',
			array(),
			$admin_css_version
		);

		// Enqueue admin app styles (includes automation canvas styles).
		wp_enqueue_style(
			'ugcify-admin-app',
			UGCIFY_URL . 'assets/admin/app.css',
			array( 'ugcify-admin', 'wp-components', 'wp-block-editor', 'wp-edit-site' ),
			$admin_app_css_ver
		);

		// Get custom logo URL.
		$logo_url = '';
		$custom_logo_id = get_theme_mod( 'custom_logo' );
		if ( $custom_logo_id ) {
			$logo_url = wp_get_attachment_image_url( $custom_logo_id, 'full' );
		}

		// Get site icon/favicon URL.
		$favicon_url = get_site_icon_url();

		// Check if WooCommerce has any reviews.
		$wc_review_count = 0;
		if ( class_exists( 'WooCommerce' ) ) {
			global $wpdb;
			$wc_review_count = (int) $wpdb->get_var(
				"SELECT COUNT(*) FROM {$wpdb->comments} 
				WHERE comment_type = 'review' 
				AND comment_approved = '1'"
			);
		}

		// Collect feature-gate state so the React admin UI can show upgrade prompts.
		$feature_keys = array(
			'customer_upload_form',
			'product_tagging',
			'social_import',
			'email_automation',
			'advanced_email_integration',
			'reward_coupons',
			'ab_testing',
			'advanced_gamification',
			'fraud_management',
			'review_request_email',
			'block_studio_advanced',
			'block_studio_reels',
			'block_studio_gallery',
			'unlimited_reviews',
			'image_edit',
			'influencer_portal',
			's3_storage',
		);
		$enabled_features = array();
		foreach ( $feature_keys as $key ) {
			$enabled_features[ $key ] = FeatureGate::is_enabled( $key );
		}

		// Localize script with data.
		require_once UGCIFY_PATH . 'includes/Admin/API/OnboardingTourAPI.php';

		wp_localize_script(
			'ugcify-admin',
			'ugcCommerce',
			array(
				'apiUrl'           => rest_url( 'ugcify/v1' ),
				'nonce'            => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'        => UGCIFY_URL,
				'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
				'adminUrl'         => admin_url(),
				'isAdmin'          => current_user_can( 'manage_options' ),
				'currentUserId'    => get_current_user_id(),
				'adminName'        => wp_get_current_user()->display_name,
				'adminEmail'       => get_option( 'admin_email' ),
				'siteUrl'          => site_url(),
				'siteLogo'         => $logo_url,
				'siteFavicon'      => $favicon_url,
				'isMailMintActive' => defined( 'MAILMINT' ),
				'wcReviewCount'    => $wc_review_count,
				// License / plan data — values provided by ugcify-pro when active.
				'isProActive'      => (bool) apply_filters( 'ugcify_is_pro_active', false ),
				'licensePlan'      => (string) apply_filters( 'ugcify_license_plan', '' ),
				'licenseStatus'    => (string) apply_filters( 'ugcify_license_status', 'inactive' ),
				'features'         => $enabled_features,
				'upgradeUrl'       => esc_url( apply_filters( 'ugcify_upgrade_url', 'https://rextheme.com/ugc-for-woocommerce/' ) ),
				'onboardingTourStatus' => \Ugcify\Admin\API\OnboardingTourAPI::get_status(),
			)
		);

		// Add inline script to handle menu navigation without page reload.
		wp_add_inline_script(
			'ugcify-admin',
			"
			document.addEventListener('DOMContentLoaded', function() {
				const menuLinks = document.querySelectorAll('#adminmenu a[href*=\"ugcify\"]');

				const getHashFromMenuHref = function(href) {
					if (!href) {
						return '#/';
					}

					const normalizedHref = href.replace(/%23/gi, '#');
					const hashIndex = normalizedHref.indexOf('#');

					if (hashIndex !== -1) {
						return normalizedHref.substring(hashIndex);
					}

					try {
						const parsedUrl = new URL(href, window.location.href);
						const page = decodeURIComponent(parsedUrl.searchParams.get('page') || '');
						const pageHashIndex = page.indexOf('#');

						return pageHashIndex !== -1 ? page.substring(pageHashIndex) : '#/';
					} catch (error) {
						return '#/';
					}
				};
				
				menuLinks.forEach(function(link) {
					link.addEventListener('click', function(e) {
						const href = link.getAttribute('href');
						
						// Check if we're already on the ugcify admin page
						if (window.location.href.indexOf('ugcify') !== -1) {
							e.preventDefault();
							// Extract hash from raw or encoded menu URLs (e.g. %23/settings/email).
							const newHash = getHashFromMenuHref(href);
							
							// Update hash without page reload
							window.location.hash = newHash;
							
							// Update active menu item
							menuLinks.forEach(l => l.parentElement.classList.remove('current'));
							link.parentElement.classList.add('current');
						}
					});
				});
			});
			",
			'after'
		);

		$this->localize_mrm_vars();
	}

	/**
	 * Whether UGC assets are needed on the current page.
	 *
	 * @var bool
	 */
	private $is_ugcify_needed = false;

	/**
	 * Mark that UGC assets are needed on the current page.
	 *
	 * @return void
	 */
	public function mark_ugcify_needed() {
		$this->is_ugcify_needed = true;
	}

	/**
	 * Check if UGC assets should be loaded on the current page.
	 *
	 * @return bool
	 */
	private function should_load_ugcify_assets() {
		// If explicitly marked as needed via shortcode/block.
		if ( $this->is_ugcify_needed ) {
			return true;
		}

		if ( $this->current_content_needs_ugcify_assets() ) {
			return true;
		}

		// Load on single product pages (where reviews typically display).
		if ( function_exists( 'is_product' ) && is_product() ) {
			return true;
		}

		// Load on shop/archive pages if reviews are enabled there.
		if ( function_exists( 'is_shop' ) && is_shop() ) {
			return apply_filters( 'ugcify_load_assets_on_shop', false );
		}

		// Allow themes/plugins to filter.
		return apply_filters( 'ugcify_load_frontend_assets', false );
	}

	/**
	 * Check queried content before shortcode rendering, so assets load in the head.
	 *
	 * @return bool
	 */
	private function current_content_needs_ugcify_assets() {
		$queried_object = get_queried_object();
		if ( ! $queried_object instanceof \WP_Post ) {
			return false;
		}

		$content = (string) $queried_object->post_content;
		if ( '' === $content ) {
			return false;
		}

		foreach ( array( 'ugcify_reviews', 'ugcify_review_form', 'ugcify_review_button' ) as $shortcode ) {
			if ( has_shortcode( $content, $shortcode ) ) {
				return true;
			}
		}

		return function_exists( 'has_block' ) && has_block( 'ugcify/reviews', $queried_object );
	}

	/**
	 * Enqueue frontend assets.
	 *
	 * @return void
	 */
	public function enqueue_frontend_assets() {
		// Only load assets where UGC is needed.
		if ( ! $this->should_load_ugcify_assets() ) {
			return;
		}
		$frontend_asset_file = UGCIFY_PATH . 'assets/frontend/app.asset.php';
		$frontend_asset      = array(
			'dependencies' => array( 'jquery', 'wp-i18n' ),
			'version'      => UGCIFY_VERSION,
		);

		if ( file_exists( $frontend_asset_file ) ) {
			$loaded_asset = require $frontend_asset_file;
			if ( is_array( $loaded_asset ) ) {
				$frontend_asset = array_merge( $frontend_asset, $loaded_asset );
			}
		}

		$frontend_asset['dependencies'] = array_values(
			array_unique(
				array_merge(
					array( 'jquery', 'wp-i18n' ),
					isset( $frontend_asset['dependencies'] ) && is_array( $frontend_asset['dependencies'] ) ? $frontend_asset['dependencies'] : array()
				)
			)
		);

		// Enqueue frontend JavaScript.
		wp_enqueue_script(
			'ugcify-frontend',
			UGCIFY_URL . 'assets/frontend/app.js',
			$frontend_asset['dependencies'],
			$frontend_asset['version'],
			true
		);

		// Set script translations for the frontend app.
		wp_set_script_translations(
			'ugcify-frontend',
			'ugcify',
			UGCIFY_PATH . 'languages'
		);

		// Enqueue frontend styles.
		wp_enqueue_style(
			'ugcify-frontend',
			UGCIFY_URL . 'assets/frontend/styles.css',
			array(),
			UGCIFY_VERSION
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-product-reviews-container.ugcify-reviews-wrapper{width:100%;max-width:100%;box-sizing:border-box;background:transparent;box-shadow:none}.ugcify-product-reviews-container.ugcify-reviews-wrapper *,.ugcify-product-reviews-container.ugcify-reviews-wrapper *:before,.ugcify-product-reviews-container.ugcify-reviews-wrapper *:after{box-sizing:border-box}.ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section{max-width:100%}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,.woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title{display:block!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'body.wp-theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.wp-theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.wp-theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.wp-theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper,body.theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper{width:100%!important;max-width:100%!important;margin-left:0!important;margin-right:0!important;transform:none!important}body.wp-theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.wp-theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.wp-theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.wp-theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section,body.theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-reviews-section{width:100%!important;max-width:100%!important}body.wp-theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.wp-theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.theme-twentytwenty .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.theme-twentytwenty .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.wp-theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.wp-theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.theme-twentytwentyone .woocommerce-tabs .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title,body.theme-twentytwentyone .woocommerce-Tabs-panel .ugcify-product-reviews-container.ugcify-reviews-wrapper .ugcify-main-title{display:block!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-reels-modal-overlay .ugcify-reels-modal-close,.ugcify-reels-modal-overlay .ugcify-reels-nav,.ugcify-reels-modal-overlay .ugcify-reels-video-control,.ugcify-reels-modal-overlay .ugcify-reels-direct-cart-close{-webkit-appearance:none!important;appearance:none!important;padding:0!important;margin:0!important;min-width:0!important;min-height:0!important;line-height:1!important;font:inherit!important;text-decoration:none!important;text-shadow:none!important;box-shadow:none!important;background-image:none!important;overflow:visible!important}.ugcify-reels-modal-overlay .ugcify-reels-modal-close:before,.ugcify-reels-modal-overlay .ugcify-reels-modal-close:after,.ugcify-reels-modal-overlay .ugcify-reels-nav:before,.ugcify-reels-modal-overlay .ugcify-reels-nav:after,.ugcify-reels-modal-overlay .ugcify-reels-video-control:before,.ugcify-reels-modal-overlay .ugcify-reels-video-control:after,.ugcify-reels-modal-overlay .ugcify-reels-direct-cart-close:before,.ugcify-reels-modal-overlay .ugcify-reels-direct-cart-close:after{content:none!important;display:none!important}.ugcify-reels-modal-overlay .ugcify-reels-modal-close svg,.ugcify-reels-modal-overlay .ugcify-reels-nav svg,.ugcify-reels-modal-overlay .ugcify-reels-video-control svg,.ugcify-reels-modal-overlay .ugcify-reels-direct-cart-close svg{display:block!important;flex:0 0 auto!important;pointer-events:none!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-star-display{display:inline-block!important;width:18px;height:18px;min-width:18px;flex:0 0 auto;margin:0!important;padding:0!important;border:0!important;line-height:0!important;font-size:0!important;vertical-align:middle;background-image:none}.ugcify-stars-summary,.ugcify-stars-display,.ugcify-card-rating,.ugcify-gallery-review-stars{display:inline-flex!important;align-items:center!important;gap:4px;line-height:1!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers{-webkit-appearance:none!important;appearance:none!important;display:flex!important;align-items:center!important;justify-content:center!important;width:38px!important;height:38px!important;padding:0!important;margin:0!important;border:1px solid #e5e7eb!important;border-radius:8px!important;outline:none!important;box-shadow:none!important;background-color:#fff!important;background-image:none!important;line-height:1!important;text-decoration:none!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers:before,.ugcify-pagination-wrapper .ugcify-pagination .page-numbers:after{content:none!important;display:none!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers span{display:block!important;margin-top:-1px!important;line-height:1!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers:hover{border-color:#201cfe!important;background-color:#f8f8ff!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers.disabled{border-color:#e5e7eb!important}.ugcify-pagination-wrapper .ugcify-pagination .page-numbers.current{border-color:#201cfe!important;background-color:#201cfe!important;color:#fff!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-slider-nav{-webkit-appearance:none!important;appearance:none!important;width:42px!important;height:42px!important;min-width:42px!important;min-height:42px!important;border:1px solid #eef0f6!important;border-radius:999px!important;background:#fff!important;background-image:none!important;color:#3b6ef5!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;padding:0!important;margin:0!important;line-height:1!important;text-shadow:none!important;overflow:visible!important}.ugcify-slider-nav:before,.ugcify-slider-nav:after{content:none!important;display:none!important}.ugcify-slider-nav svg{display:block!important;width:14px!important;height:14px!important;flex:0 0 auto!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}.ugcify-slider-nav svg path{fill:none!important;stroke:currentColor!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-slider-pagination .ugcify-slider-dot{-webkit-appearance:none!important;appearance:none!important;width:8px!important;height:8px!important;min-width:8px!important;min-height:8px!important;border:0!important;border-radius:999px!important;outline:0!important;box-shadow:none!important;background:#cfd5e2!important;background-image:none!important;padding:0!important;margin:0!important;line-height:0!important;font-size:0!important;text-shadow:none!important;overflow:hidden!important}.ugcify-slider-pagination .ugcify-slider-dot:before,.ugcify-slider-pagination .ugcify-slider-dot:after{content:none!important;display:none!important}.ugcify-slider-pagination .ugcify-slider-dot.is-active{width:10px!important;height:10px!important;min-width:10px!important;min-height:10px!important;background:#3b6ef5!important}.ugcify-pinned-badge,.ugcify-featured-badge{box-shadow:none!important;text-shadow:none!important}.ugcify-pinned-badge:before,.ugcify-pinned-badge:after,.ugcify-featured-badge:before,.ugcify-featured-badge:after{content:none!important;display:none!important}.ugcify-pinned-badge img,.ugcify-pinned-badge svg,.ugcify-featured-badge img,.ugcify-featured-badge svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;filter:none!important;opacity:1!important;visibility:visible!important;max-width:none!important}.ugcify-card-media-badges .ugcify-pinned-badge img,.ugcify-card-media-badges .ugcify-pinned-badge svg,.ugcify-review-indicators .ugcify-pinned-badge img,.ugcify-review-indicators .ugcify-pinned-badge svg{width:20px!important;height:20px!important}.ugcify-gallery-carousel-btn svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important}.ugcify-gallery-carousel-btn svg path{fill:none!important;stroke:currentColor!important}.ugcify-gallery-carousel-play{background:transparent!important;border:0!important;box-shadow:none!important}.ugcify-gallery-carousel-play svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;opacity:1!important;visibility:visible!important}.ugcify-gallery-carousel-play svg circle{fill:rgba(255,255,255,.88)!important;stroke:none!important}.ugcify-gallery-carousel-play svg path{fill:#201CFE!important;stroke:none!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-gallery-see-all{-webkit-appearance:none!important;appearance:none!important;display:inline-flex!important;align-items:center!important;gap:6px!important;border:0!important;padding:0!important;background:transparent!important;background-image:none!important;color:#2563eb!important;box-shadow:none!important;text-shadow:none!important;line-height:1.2!important}.ugcify-gallery-see-all:before,.ugcify-gallery-see-all:after{content:none!important;display:none!important}.ugcify-gallery-see-all svg{display:block!important;width:10px!important;height:10px!important;flex:0 0 auto!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}.ugcify-gallery-see-all svg path{fill:none!important;stroke:currentColor!important}.ugcify-gallery-review-card .ugcify-featured-badge svg rect,.ugcify-featured-badge svg rect{fill:#201CFE!important;stroke:none!important}.ugcify-gallery-review-card .ugcify-featured-badge svg path,.ugcify-featured-badge svg path{fill:none!important;stroke:#fff!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-attachment-lightbox__close{-webkit-appearance:none!important;appearance:none!important;width:36px!important;height:36px!important;min-width:36px!important;min-height:36px!important;border:0!important;border-radius:8px!important;background:transparent!important;background-image:none!important;color:#111827!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;padding:0!important;margin:0!important;line-height:1!important;box-shadow:none!important;text-shadow:none!important}.ugcify-attachment-lightbox__close:hover,.ugcify-attachment-lightbox__close:focus{background:#f3f4f6!important;background-image:none!important;color:#111827!important;border:0!important;box-shadow:none!important}.ugcify-attachment-lightbox__close:before,.ugcify-attachment-lightbox__close:after{content:none!important;display:none!important}.ugcify-attachment-lightbox__close svg{display:block!important;width:24px!important;height:24px!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}.ugcify-attachment-lightbox__close svg path{fill:none!important;stroke:currentColor!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'#ugcify-review-modal .ugcify-review-modal-close,#ugcify-review-details-modal .ugcify-review-modal-close{-webkit-appearance:none!important;appearance:none!important;background:#fff!important;background-image:none!important;border:0!important;color:inherit!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;box-shadow:none!important;text-shadow:none!important}#ugcify-review-modal .ugcify-review-modal-close:hover,#ugcify-review-modal .ugcify-review-modal-close:focus,#ugcify-review-modal .ugcify-review-modal-close:active,#ugcify-review-details-modal .ugcify-review-modal-close:hover,#ugcify-review-details-modal .ugcify-review-modal-close:focus,#ugcify-review-details-modal .ugcify-review-modal-close:active{background:#fff!important;background-image:none!important;border:0!important;color:inherit!important;box-shadow:none!important}#ugcify-review-modal .ugcify-review-modal-close:before,#ugcify-review-modal .ugcify-review-modal-close:after,#ugcify-review-details-modal .ugcify-review-modal-close:before,#ugcify-review-details-modal .ugcify-review-modal-close:after{content:none!important;display:none!important}#ugcify-review-modal .ugcify-review-modal-close svg,#ugcify-review-details-modal .ugcify-review-modal-close svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}#ugcify-review-modal .ugcify-review-modal-close svg path,#ugcify-review-details-modal .ugcify-review-modal-close svg path{fill:#E56829!important;stroke:none!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-reviews-stats .ugcify-stats-dropdown-icon{display:inline-flex!important;align-items:center!important;justify-content:center!important;width:12px!important;height:12px!important;background:transparent!important;border:0!important;border-radius:0!important}.ugcify-reviews-stats .ugcify-stats-dropdown-icon svg{display:block!important;width:12px!important;height:7px!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important}.ugcify-reviews-stats .ugcify-stats-dropdown-icon svg path{fill:none!important;stroke:currentColor!important}.ugcify-filter-btn{-webkit-appearance:none!important;appearance:none!important;width:46px!important;height:46px!important;min-width:46px!important;min-height:46px!important;background:#fff!important;background-image:none!important;border:1.5px solid #dfdffc!important;border-radius:8px!important;color:#292d32!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;padding:0!important;margin:0!important;line-height:1!important;text-shadow:none!important;box-shadow:none!important;overflow:visible!important}.ugcify-filter-btn:before,.ugcify-filter-btn:after{content:none!important;display:none!important}.ugcify-filter-btn svg{display:block!important;width:24px!important;height:24px!important;flex:0 0 auto!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}.ugcify-filter-btn svg path{fill:none!important;stroke:currentColor!important}.ugcify-card-media .ugcify-play-overlay{background:transparent!important;border:0!important;box-shadow:none!important;color:#fff!important;pointer-events:none!important}.ugcify-card-media .ugcify-play-overlay svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important}.ugcify-card-media .ugcify-play-overlay svg circle,.ugcify-card-media .ugcify-play-overlay svg path{fill:transparent!important;stroke:currentColor!important}'
		);
		wp_add_inline_style(
			'ugcify-frontend',
			'.ugcify-review-details-modal .ugcify-review-details-carousel-nav,.ugcify-review-details-modal .ugcify-carousel-arrow{-webkit-appearance:none!important;appearance:none!important;padding:0!important;margin:0!important;line-height:1!important;text-shadow:none!important;box-shadow:none!important;overflow:visible!important}.ugcify-review-details-modal .ugcify-review-details-carousel-nav:before,.ugcify-review-details-modal .ugcify-review-details-carousel-nav:after,.ugcify-review-details-modal .ugcify-carousel-arrow:before,.ugcify-review-details-modal .ugcify-carousel-arrow:after{content:none!important;display:none!important}.ugcify-review-details-modal .ugcify-review-details-carousel-nav svg,.ugcify-review-details-modal .ugcify-carousel-arrow svg,.ugcify-review-details-modal .ugcify-nav-btn svg{display:block!important;flex:0 0 auto!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}.ugcify-review-details-modal .ugcify-review-details-carousel-nav svg path,.ugcify-review-details-modal .ugcify-carousel-arrow svg path,.ugcify-review-details-modal .ugcify-nav-btn svg path{fill:none!important;stroke:currentColor!important}.ugcify-review-details-modal .ugcify-nav-btn{-webkit-appearance:none!important;appearance:none!important;background:none!important;background-image:none!important;text-shadow:none!important;box-shadow:none!important}.ugcify-review-details-modal .ugcify-nav-btn:before,.ugcify-review-details-modal .ugcify-nav-btn:after{content:none!important;display:none!important}'
		);

		// Get WooCommerce settings for add to cart behavior.
		$wc_cart_redirect = 'no';
		$wc_cart_url      = '';
		if ( class_exists( 'WooCommerce' ) ) {
			$wc_cart_redirect = get_option( 'woocommerce_cart_redirect_after_add', 'no' );
			$wc_cart_url      = wc_get_cart_url();
		}

		// Localize script.
		wp_localize_script(
			'ugcify-frontend',
			'ugcCommerce',
			array(
				'apiUrl'           => rest_url( 'ugcify/v1' ),
				'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
				'nonce'            => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'        => UGCIFY_URL,
				'productId'        => get_the_ID(),
				'perPage'          => apply_filters( 'ugcify_reviews_per_page', 3 ),
				'locale'           => str_replace( '_', '-', get_locale() ),
				'gmtOffset'        => (float) get_option( 'gmt_offset', 0 ),
				'wcCartRedirect'   => $wc_cart_redirect === 'yes',
				'wcCartUrl'        => $wc_cart_url,
				'rewardsEnabled'   => \Ugcify\Admin\API\RewardSettingsAPI::is_enabled(),
				'socialShareEnabled' => \Ugcify\Admin\API\RewardSettingsAPI::is_social_share_enabled(),
				'i18n'      => array(
					'guest'                => __( 'Guest', 'ugcify' ),
					'reviewMediaAlt'       => __( 'Review Media', 'ugcify' ),
					'errorLoadingReview'   => __( 'Error loading review. Please try again.', 'ugcify' ),
					'failedFetchReview'    => __( 'Failed to fetch review', 'ugcify' ),
					'failedFetchReviewIds' => __( 'Failed to fetch review ids', 'ugcify' ),
					'addingToCart'         => __( 'Adding...', 'ugcify' ),
					'addedToCart'          => __( 'Added', 'ugcify' ),
					'addToCartError'       => __( 'Try Again', 'ugcify' ),
					'readMore'             => __( 'Read More', 'ugcify' ),
					'readLess'             => __( 'Read less', 'ugcify' ),
					'shareDefaultText'     => __( 'Check out this review:', 'ugcify' ),
					'shareCopiedLabel'     => __( 'Copied!', 'ugcify' ),
					'shareCopyManualLabel' => __( 'Press Ctrl+C to copy', 'ugcify' ),
					'shareErrorLabel'      => __( 'Could not create share link. Please try again.', 'ugcify' ),
				),
			)
		);
	}

	/**
	 * Inject social share OG tags.
	 *
	 * @return void
	 */
	public function inject_social_share_meta_tags() {
		$injector = new Frontend\ShareMetaInjector();
		$injector->inject();
	}

	/**
	 * Ensure weekly cleanup cron for share tokens exists.
	 *
	 * @return void
	 */
	public function schedule_share_cleanup_cron() {
		if ( ! wp_next_scheduled( 'ugcify_cleanup_share_tokens' ) ) {
			wp_schedule_event( time(), 'weekly', 'ugcify_cleanup_share_tokens' );
		}
	}

	/**
	 * Delete expired share tokens.
	 *
	 * @return void
	 */
	public function cleanup_expired_share_tokens() {
		$repository = new Database\ReviewRepository();
		$repository->delete_expired_share_tokens();
	}

	/**
	 * Localize MRM_Vars for automation canvas compatibility.
	 * Pulls real data from Mail Mint classes when available.
	 *
	 * @return void
	 */
	private function localize_mrm_vars() {
		$current_user       = wp_get_current_user();
		$current_user_email = $current_user->user_email;
		$current_user_name  = $current_user->display_name;
		$admin_email        = get_option( 'admin_email' );
		$admin_user         = get_user_by( 'email', $admin_email );
		$admin_name         = $admin_user ? $admin_user->display_name : '';
		$wc_active          = class_exists( 'WooCommerce' );

		$default = array(
			'company'    => '',
			'phone'      => '',
			'address'    => '',
			'logo_url'   => '',
			'socialMedia' => array(),
		);

		// Build base MRM_Vars.
		$mrm_vars = array(
			'ajaxurl'                        => admin_url( 'admin-ajax.php' ),
			'api_base_url'                   => get_rest_url(),
			'nonce'                          => wp_create_nonce( 'wp_rest' ),
			'current_userID'                 => get_current_user_id(),
			'current_user_email'             => $current_user_email,
			'current_user_name'              => $current_user_name,
			'admin_url'                      => admin_url(),
			'admin_name'                     => $admin_name,
			'admin_email'                    => $admin_email,
			'site_url'                       => site_url(),
			'date_format'                    => get_option( 'date_format', 'F j, Y' ),
			'time_format'                    => get_option( 'time_format', 'H:i' ),
			'gmt_offset'                     => get_option( 'gmt_offset' ),
			'local_time'                     => date_i18n( 'Y-m-d H:i:s' ),
			'start_of_week'                  => get_option( 'start_of_week', 1 ),
			'is_wc_active'                   => $wc_active,
			'currency_format'                => $wc_active ? html_entity_decode( get_woocommerce_currency_symbol() ) : '',
			'unsubscribe_url'                => home_url(),
			'preference_url'                 => home_url(),
			'business_basic_settings'        => get_option( '_mrm_business_basic_info_setting', $default ),
			'business_social_settings'       => get_option( '_mrm_business_social_info_setting', array( 'socialMedia' => array() ) ),
			'email_settings'                 => get_option( '_mrm_email_settings', array() ),
			'mint_page'                      => 'automation',
			'is_mailmint_pro_active'         => false,
			'is_mailmint_pro_license_active' => false,
			'wp_uuid4'                       => wp_generate_uuid4(),
			// Always provide mint_trans fallback so HelpResource.jsx never crashes
			// even when Mail Mint is freshly activated without a page reload.
			'mint_trans'                     => array(
				'Video'              => __( 'Video', 'ugcify' ),
				'Documentation'      => __( 'Documentation', 'ugcify' ),
				'SocialGroup'        => __( 'Social Group', 'ugcify' ),
				'YoutubeVideo'       => __( 'Youtube Video', 'ugcify' ),
				'YouTubeVideoPlayer' => __( 'YouTube Video Player', 'ugcify' ),
				'NoStepSelected'     => __( 'No step selected', 'ugcify' ),
				'UnknownStepType'    => __( 'Unknown step type', 'ugcify' ),
				'Automation'         => __( 'Automation', 'ugcify' ),
				'Exit'               => __( 'Exit', 'ugcify' ),
			),
		);

		// Pull real data from Mail Mint classes when available.
		if ( defined( 'MAILMINT' ) ) {
			// Contact lists and tags.
			if ( class_exists( 'Mint\\MRM\\DataBase\\Models\\ContactGroupModel' ) ) {
				$mrm_vars['lists'] = \Mint\MRM\DataBase\Models\ContactGroupModel::get_all_to_custom_select( 'lists' );
				$mrm_vars['tags']  = \Mint\MRM\DataBase\Models\ContactGroupModel::get_all_to_custom_select( 'tags' );
			}

			// Constants data.
			if ( class_exists( 'Mint\\MRM\\Internal\\Constants' ) ) {
				$mrm_vars['timezone_list']      = \Mint\MRM\Internal\Constants::get_timezone_list();
				$mrm_vars['countries']           = \Mint\MRM\Internal\Constants::get_country_name();
				$mrm_vars['states']              = \Mint\MRM\Internal\Constants::get_country_state();
				$mrm_vars['exist_contact_field'] = \Mint\MRM\Internal\Constants::get_exsiting_fields_array();
			}

			// Email defaults.
			if ( class_exists( 'Mint\\MRM\\Utilites\\Helper\\Email' ) ) {
				$mrm_vars['email_settings'] = get_option( '_mrm_email_settings', \Mint\MRM\Utilites\Helper\Email::default_email_settings() );
			}

			// MrmCommon helpers.
			if ( class_exists( 'MRM\\Common\\MrmCommon' ) ) {
				$mrm_vars['is_mailmint_pro_active']         = \MRM\Common\MrmCommon::is_mailmint_pro_active();
				$mrm_vars['is_mailmint_pro_license_active'] = \MRM\Common\MrmCommon::is_mailmint_pro_license_active();
				$mrm_vars['contact_general_fields']         = \MRM\Common\MrmCommon::get_contact_general_fields();
				$mrm_vars['contact_custom_fields']          = \MRM\Common\MrmCommon::get_contact_custom_fields();
				$mrm_vars['contacts_map_attrs']             = \MRM\Common\MrmCommon::import_contacts_map_attrs();
				$mrm_vars['post_types']                     = \MRM\Common\MrmCommon::get_all_post_types();
				$mrm_vars['address']                        = \MRM\Common\MrmCommon::get_business_full_address();
				$mrm_vars['bounce_configs']                 = \MRM\Common\MrmCommon::get_bounce_configs();
				$mrm_vars['is_wpf_active']                  = \MRM\Common\MrmCommon::is_wpfnl_active();
			}

			// Translation strings.
			if ( class_exists( 'Mint\\MRM\\Utilities\\Helper\\TranslationString\\TransStrings' ) ) {
				$mrm_vars['mint_trans'] = \Mint\MRM\Utilities\Helper\TranslationString\TransStrings::getStrings();
			} else {
				// Fallback when Mail Mint is activated but not yet loaded (before page reload).
				$mrm_vars['mint_trans'] = array(
					'Video'             => __( 'Video', 'ugcify' ),
					'Documentation'     => __( 'Documentation', 'ugcify' ),
					'SocialGroup'       => __( 'Social Group', 'ugcify' ),
					'YoutubeVideo'      => __( 'Youtube Video', 'ugcify' ),
					'YouTubeVideoPlayer' => __( 'YouTube Video Player', 'ugcify' ),
				);
			}

			// Automation helper functions.
			if ( class_exists( 'MintMail\\App\\Internal\\Automation\\HelperFunctions' ) ) {
				$mrm_vars['sequences']              = \MintMail\App\Internal\Automation\HelperFunctions::get_sequences();
				$mrm_vars['is_edd_active']          = \MintMail\App\Internal\Automation\HelperFunctions::is_edd_active();
				$mrm_vars['is_tutor_active']        = \MintMail\App\Internal\Automation\HelperFunctions::is_tutor_active();
				$mrm_vars['tutor_courses']          = \MintMail\App\Internal\Automation\HelperFunctions::get_tutor_lms_courses();
				$mrm_vars['tutor_lessons']          = \MintMail\App\Internal\Automation\HelperFunctions::get_tutor_lms_lessons();
				$mrm_vars['is_learndash_active']    = \MintMail\App\Internal\Automation\HelperFunctions::is_learndash_lms_active();
				$mrm_vars['is_memberpress_active']  = \MintMail\App\Internal\Automation\HelperFunctions::is_memberpress_active();
				$mrm_vars['is_lifterlms_active']    = \MintMail\App\Internal\Automation\HelperFunctions::is_lifter_lms_active();
				$mrm_vars['lifter_courses']         = \MintMail\App\Internal\Automation\HelperFunctions::get_lifter_lms_courses();
				$mrm_vars['lifter_memberships']     = \MintMail\App\Internal\Automation\HelperFunctions::get_lifter_lms_memberships();
				$mrm_vars['get_mailmint_forms']     = \MintMail\App\Internal\Automation\HelperFunctions::get_mailmint_forms();
				$mrm_vars['wc_coupons']             = \MintMail\App\Internal\Automation\HelperFunctions::get_woocommerce_coupons();
				$mrm_vars['wc_order_statuses']      = \MintMail\App\Internal\Automation\HelperFunctions::get_woocommerce_order_statuses();
				$mrm_vars['is_fluent_booking_active'] = \MintMail\App\Internal\Automation\HelperFunctions::is_fluent_booking_active();
				$mrm_vars['is_mailpoet_active']     = \MintMail\App\Internal\Automation\HelperFunctions::is_mailpoet_active();
				$mrm_vars['is_gform_active']        = \MintMail\App\Internal\Automation\HelperFunctions::is_gform_active();
				$mrm_vars['get_gforms']             = \MintMail\App\Internal\Automation\HelperFunctions::get_gform_forms();
				$mrm_vars['is_jetform_active']      = \MintMail\App\Internal\Automation\HelperFunctions::is_jetform_active();
				$mrm_vars['is_fluentform_active']   = \MintMail\App\Internal\Automation\HelperFunctions::is_fluentform_active();
				$mrm_vars['is_contact_form_active'] = \MintMail\App\Internal\Automation\HelperFunctions::is_contact_form_7_active();
			}

			// Mail Mint images URL.
			if ( defined( 'MRM_DIR_URL' ) ) {
				$mrm_vars['images_url']    = MRM_DIR_URL . 'app/Internal/Admin/Email-Templates/images/';
				$mrm_vars['admin_img_url'] = MRM_DIR_URL . 'admin/assets/images';
			}

			// reCAPTCHA settings.
			$recaptcha_default = array(
				'api_type'        => 'v3',
				'v2_site_key'     => '',
				'v2_secret_key'   => '',
				'v3_site_key'     => '',
				'v3_secret_key'   => '',
				'v3_score'        => 0.5,
			);
			$mrm_vars['recaptcha_settings'] = get_option( '_mint_recaptcha_settings', $recaptcha_default );

			// Pro features (safe checks with class_exists).
			if ( class_exists( 'MintMailPro\\Mint_Pro_Helper' ) && class_exists( 'MRM\\Common\\MrmCommon' ) && \MRM\Common\MrmCommon::is_mailmint_pro_active() ) {
				$mrm_vars['is_wcs_active'] = \MRM\Common\MrmCommon::is_mailmint_pro_version_compatible( '1.15.0' ) ? \MintMailPro\Mint_Pro_Helper::is_woocommerce_subscription_active() : false;
				$mrm_vars['is_wcm_active'] = \MRM\Common\MrmCommon::is_mailmint_pro_version_compatible( '1.15.0' ) ? \MintMailPro\Mint_Pro_Helper::is_woocommerce_membership_active() : false;
				$mrm_vars['is_wcw_active'] = \MRM\Common\MrmCommon::is_mailmint_pro_version_compatible( '1.15.0' ) ? \MintMailPro\Mint_Pro_Helper::is_woocommerce_wishlist_active() : false;
			}
		}

		wp_localize_script( 'ugcify-admin', 'MRM_Vars', apply_filters( 'ugcify_mrm_vars', $mrm_vars ) );
	}

	/**
	 * Print compatibility shim for plugins expecting a global config object.
	 *
	 * Some third-party scripts (e.g., creator-lms) throw a fatal runtime error
	 * when `crlms_frontend_params` is missing, which can interrupt page scripts.
	 *
	 * @return void
	 */
	public function print_creator_lms_compat_shim(): void {
		wp_add_inline_script( 'jquery', 'window.crlms_frontend_params=window.crlms_frontend_params||{};', 'after' );
	}

	/** @deprecated No-op — pro install is now triggered inline from LicensePage.jsx. */
	public function maybe_enqueue_pro_install_assets(): void {}

	/**
	 * AJAX handler: download and install the pro ZIP directly.
	 *
	 * Uses Plugin_Upgrader::run() with the stored EDD package URL so the install
	 * replaces the free build in-place with no version-comparison gate.
	 *
	 * @return void  Terminates via wp_send_json_success / wp_send_json_error.
	 */
	public function ajax_install_pro_build(): void {
		check_ajax_referer( 'ugcify_install_pro_build' );

		if ( ! current_user_can( 'update_plugins' ) ) {
			wp_send_json_error( __( 'You do not have permission to install plugins.', 'ugcify' ) );
		}

		$download_url = (string) get_option( 'ugcify_pro_download_url', '' );

		if ( empty( $download_url ) ) {
			wp_send_json_error( __( 'No download URL found. Please deactivate and reactivate your license to try again.', 'ugcify' ) );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/plugin.php';

		$skin     = new \WP_Ajax_Upgrader_Skin();
		$upgrader = new \Plugin_Upgrader( $skin );

		// run() downloads the ZIP, extracts it, and replaces the plugin directory.
		// clear_destination:true wipes the old files first — free→pro replacement.
		// action:'update' keeps the plugin activated after the file swap.
		$result = $upgrader->run(
			array(
				'package'           => $download_url,
				'destination'       => WP_PLUGIN_DIR,
				'clear_destination' => true,
				'clear_working'     => true,
				'hook_extra'        => array(
					'plugin' => UGCIFY_BASENAME,
					'type'   => 'plugin',
					'action' => 'update',
				),
			)
		);

		if ( \is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		if ( ! $result ) {
			$errors = $skin->get_errors();
			$msg    = \is_wp_error( $errors ) ? $errors->get_error_message() : __( 'Installation failed. Please try again.', 'ugcify' );
			wp_send_json_error( $msg );
		}

		// Belt-and-suspenders cleanup (on_upgrade_complete also fires via upgrader hook).
		delete_option( 'ugcify_needs_pro_install' );
		delete_option( 'ugcify_pro_download_url' );
		delete_transient( 'ugcify_force_edd_install' );

		wp_send_json_success( array( 'message' => __( 'Pro build installed successfully.', 'ugcify' ) ) );
	}

	/**
	 * AJAX: restore the free build from WordPress.org after license deactivation.
	 *
	 * Mirrors ajax_install_pro_build() in the opposite direction. Downloads the
	 * latest free ZIP straight from the WordPress.org repo and replaces the
	 * installed pro build with it. The direct package download bypasses the update
	 * API, so it succeeds even though the pro build carries an "Update URI" header
	 * that blocks WordPress.org auto-updates.
	 *
	 * @return void
	 */
	public function ajax_install_free_build(): void {
		check_ajax_referer( 'ugcify_install_free_build' );

		if ( ! current_user_can( 'update_plugins' ) ) {
			wp_send_json_error( __( 'You do not have permission to install plugins.', 'ugcify' ) );
		}

		$download_url = defined( 'UGCIFY_WP_ORG_PACKAGE' ) ? (string) UGCIFY_WP_ORG_PACKAGE : '';

		if ( empty( $download_url ) ) {
			wp_send_json_error( __( 'No WordPress.org package URL is configured.', 'ugcify' ) );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/plugin.php';

		$skin     = new \WP_Ajax_Upgrader_Skin();
		$upgrader = new \Plugin_Upgrader( $skin );

		// run() downloads the ZIP, extracts it, and replaces the plugin directory.
		// clear_destination:true wipes the pro files first — pro→free replacement.
		// action:'update' keeps the plugin activated after the file swap.
		$result = $upgrader->run(
			array(
				'package'           => $download_url,
				'destination'       => WP_PLUGIN_DIR,
				'clear_destination' => true,
				'clear_working'     => true,
				'hook_extra'        => array(
					'plugin' => UGCIFY_BASENAME,
					'type'   => 'plugin',
					'action' => 'update',
				),
			)
		);

		if ( \is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		if ( ! $result ) {
			$errors = $skin->get_errors();
			$msg    = \is_wp_error( $errors ) ? $errors->get_error_message() : __( 'Installation failed. Please try again.', 'ugcify' );
			wp_send_json_error( $msg );
		}

		// Clean up any pro-install bookkeeping that may still be set.
		delete_option( 'ugcify_needs_pro_install' );
		delete_option( 'ugcify_pro_download_url' );
		delete_transient( 'ugcify_force_edd_install' );

		wp_send_json_success( array( 'message' => __( 'Free build restored successfully.', 'ugcify' ) ) );
	}
}
