<?php
/**
 * 主插件逻辑：注册分组与挂载组件。
 */

namespace Tooto_Elementor;

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

use Elementor\Plugin as Elementor_Plugin;

class Plugin {
	private const MIN_ELEMENTOR_VERSION = '3.0.0';
	private const MIN_PHP_VERSION      = '7.4';

	/**
	 * @var Plugin|null
	 */
	private static $instance = null;

	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		add_action( 'init', [ $this, 'load_textdomain' ] );
		// 等待 Elementor 完全初始化后再注册分组与组件，避免抢在其之前导致 did_action 检查失败。
		add_action( 'elementor/init', [ $this, 'bootstrap' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'register_assets' ] );
		add_action( 'elementor/editor/after_enqueue_styles', [ $this, 'enqueue_editor_assets' ] );
		// 初始化文件名处理功能
		$this->init_filename_sanitizer();
		// 隐藏前台顶部工具条（所有用户）
		$this->hide_admin_bar();
		// 扩展图片宽度限制
		$this->extend_image_size_limit();
		// 初始化 WooCommerce My Account 自定义功能
		$this->init_woocommerce_myaccount();
		// 初始化 Blocksy 账户弹窗自定义功能
		$this->init_blocksy_account_modal();
		// 初始化产品品牌简码
		$this->init_product_brand_shortcode();
		// 初始化产品库存状态简码
		$this->init_product_stock_status_shortcode();
		// 初始化折扣规则表格简码
		$this->init_discount_table_shortcode();
		// 初始化产品价格范围简码
		$this->init_product_price_range_shortcode();
		// 初始化价格格式覆盖（0元显示TBD）
		$this->init_price_format_override();
	}

	public function load_textdomain(): void {
		load_plugin_textdomain( 'tooto-elementor' );
	}

	/**
	 * 初始化文件名处理功能
	 */
	private function init_filename_sanitizer(): void {
		require_once TOOTO_EA_PATH . 'includes/class-tooto-filename-sanitizer.php';
		Filename_Sanitizer::init();
	}

	/**
	 * 隐藏前台顶部工具条（Admin Bar）
	 * 对所有用户都隐藏，包括管理员
	 */
	private function hide_admin_bar(): void {
		// 方法1：使用过滤器隐藏（适用于所有用户）
		add_filter( 'show_admin_bar', '__return_false' );

		// 方法2：通过 CSS 确保完全隐藏（双重保险）
		add_action( 'wp_head', [ $this, 'hide_admin_bar_css' ], 1 );
		add_action( 'wp_footer', [ $this, 'hide_admin_bar_css' ], 1 );
	}

	/**
	 * 通过 CSS 隐藏 Admin Bar
	 * 确保即使过滤器失效，也能通过 CSS 隐藏
	 */
	public function hide_admin_bar_css(): void {
		if ( ! is_admin() ) {
			echo '<style type="text/css">#wpadminbar { display: none !important; } html { margin-top: 0 !important; }</style>' . "\n";
		}
	}

	/**
	 * 扩展 WordPress 图片宽度限制
	 * 将默认的 2560px 扩展到 3840px
	 */
	private function extend_image_size_limit(): void {
		add_filter( 'big_image_size_threshold', [ $this, 'set_image_size_threshold' ], 10, 1 );
	}

	/**
	 * 设置图片尺寸阈值
	 *
	 * @param int $threshold 当前阈值（默认 2560）
	 * @return int 新的阈值（3840）
	 */
	public function set_image_size_threshold( int $threshold ): int {
		return 3840;
	}

	/**
	 * 初始化 WooCommerce My Account 自定义功能
	 */
	private function init_woocommerce_myaccount(): void {
		// 立即尝试加载，如果 WooCommerce 还没加载则等待
		$this->load_woocommerce_myaccount();
		
		// 如果第一次加载失败，等待 WooCommerce 加载完成
		if ( ! class_exists( 'WooCommerce' ) ) {
			add_action( 'woocommerce_loaded', [ $this, 'load_woocommerce_myaccount' ], 1 );
		}
	}

	/**
	 * 加载 WooCommerce My Account 功能
	 */
	public function load_woocommerce_myaccount(): void {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\WooCommerce_MyAccount' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-woocommerce-myaccount.php';
		}

		// 初始化实例（类内部会处理单例）
		WooCommerce_MyAccount::instance();
	}

	/**
	 * 初始化 Blocksy 账户弹窗自定义功能
	 */
	private function init_blocksy_account_modal(): void {
		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\Blocksy_Account_Modal' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-blocksy-account-modal.php';
		}

		// 初始化实例（类内部会处理单例）
		Blocksy_Account_Modal::instance();
	}

	/**
	 * 初始化产品品牌简码
	 */
	private function init_product_brand_shortcode(): void {
		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\Product_Brand_Shortcode' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-product-brand-shortcode.php';
		}

		// 初始化简码
		Product_Brand_Shortcode::init();
	}

	/**
	 * 初始化产品库存状态简码
	 */
	private function init_product_stock_status_shortcode(): void {
		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\Product_Stock_Status_Shortcode' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-product-stock-status-shortcode.php';
		}

		// 初始化简码
		Product_Stock_Status_Shortcode::init();
	}

	/**
	 * 初始化折扣规则表格简码
	 */
	private function init_discount_table_shortcode(): void {
		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\Discount_Table_Shortcode' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-discount-table-shortcode.php';
		}

		// 初始化简码
		Discount_Table_Shortcode::get_instance();
	}

	/**
	 * 初始化产品价格范围简码
	 */
	private function init_product_price_range_shortcode(): void {
		// 确保类文件只加载一次
		if ( ! class_exists( __NAMESPACE__ . '\\Product_Price_Range_Shortcode' ) ) {
			require_once TOOTO_EA_PATH . 'includes/class-tooto-product-price-range-shortcode.php';
		}

		// 初始化简码
		Product_Price_Range_Shortcode::get_instance();
	}

	/**
	 * 初始化价格格式覆盖（0元显示TBD）
	 */
	private function init_price_format_override(): void {
		add_filter( 'woocommerce_get_price_html', [ $this, 'override_zero_price_html' ], 10, 2 );
		add_filter( 'woocommerce_empty_price_html', [ $this, 'override_empty_price_html' ], 10, 2 );
		// 针对变体价格范围
		add_filter( 'woocommerce_variable_price_html', [ $this, 'override_variable_price_html' ], 10, 2 );

		// 购物车价格计算钩子：预售商品价格设为0
		add_action( 'woocommerce_before_calculate_totals', [ $this, 'set_preorder_price_zero' ], 10, 1 );
	}

	/**
	 * 购物车中预售商品价格设为 0
	 */
	public function set_preorder_price_zero( $cart ) {
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return;
		}

		if ( did_action( 'woocommerce_before_calculate_totals' ) >= 3 ) {
			return;
		}

		foreach ( $cart->get_cart() as $cart_item ) {
			/** @var \WC_Product $product */
			$product = $cart_item['data'];
			
			// 检查库存状态是否为 'onpreorder'
			// 注意：WooCommerce 默认只有 instock, outofstock, onbackorder
			// onpreorder 可能是自定义状态
			if ( 'onpreorder' === $product->get_stock_status() ) {
				$product->set_price( 0 );
			}
		}
	}

	/**
	 * 覆盖 0 元价格显示 (get_price_html)
	 */
	public function override_zero_price_html( $price, $product ) {
		if ( $product->is_type( 'variable' ) ) {
			return $price;
		}
		if ( '' === $product->get_price() || 0 == $product->get_price() ) {
			return '<span class="woocommerce-Price-amount amount">TBD</span>';
		}
		return $price;
	}

	/**
	 * 覆盖空价格显示
	 */
	public function override_empty_price_html( $price, $product ) {
		return '<span class="woocommerce-Price-amount amount">TBD</span>';
	}

	/**
	 * 全局覆盖 wc_price 输出
	 */
	// 移除：避免影响非商品价格（如运费、税费）显示

	/**
	 * 覆盖变体价格范围显示
	 */
	public function override_variable_price_html( $price, $product ) {
		// 如果变体价格范围中包含 0，或者最小价格为 0
		// 这里主要处理 min_price 为 0 的情况
		$min_price = $product->get_variation_price( 'min', true );
		$max_price = $product->get_variation_price( 'max', true );

		if ( 0 == $min_price ) {
			$min_html = '<span class="woocommerce-Price-amount amount">TBD</span>';
			if ( $min_price == $max_price || 0 == $max_price ) {
				return $min_html;
			} else {
				return $min_html . ' - ' . \wc_price( $max_price );
			}
		}

		return $price;
	}

	public function register_assets(): void {
		wp_register_style(
			'tooto-elementor',
			TOOTO_EA_URL . 'assets/css/tooto-elementor.css',
			[],
			TOOTO_EA_VERSION
		);

		// Register Simple Splide Widget Style
		wp_register_style(
			'tooto-simple-splide-css',
			TOOTO_EA_URL . 'assets/css/tooto-simple-splide.css',
			[ 'tooto-splide' ], // Depends on Splide CSS
			TOOTO_EA_VERSION
		);

		// Register Splide
		wp_register_style(
			'tooto-splide',
			'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css',
			[],
			'4.1.4'
		);

		wp_register_script(
			'tooto-splide',
			'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js',
			[],
			'4.1.4',
			true
		);

		wp_register_script(
			'tooto-splide-autoscroll',
			'https://cdn.jsdelivr.net/npm/@splidejs/splide-extension-auto-scroll@0.5.3/dist/js/splide-extension-auto-scroll.min.js',
			[ 'tooto-splide' ],
			'0.5.3',
			true
		);

		wp_register_script(
			'tooto-elementor',
			TOOTO_EA_URL . 'assets/js/tooto-elementor.js',
			[ 'elementor-frontend', 'tooto-splide', 'tooto-splide-autoscroll' ],
			TOOTO_EA_VERSION,
			true
		);

		// Enqueue styles
		wp_enqueue_style( 'tooto-elementor', TOOTO_EA_URL . 'assets/css/tooto-elementor.css', [ 'tooto-splide' ], TOOTO_EA_VERSION );

	}

	public function enqueue_editor_assets(): void {
		wp_enqueue_style( 'tooto-elementor' );
		wp_enqueue_script( 'tooto-elementor' );
	}

	public function enqueue_frontend_assets(): void {
		wp_enqueue_style( 'tooto-elementor' );
		wp_enqueue_script( 'tooto-elementor' );
	}

	public function bootstrap(): void {
		if ( ! did_action( 'elementor/loaded' ) ) {
			add_action( 'admin_notices', [ $this, 'admin_notice_missing_elementor' ] );
			return;
		}

		if ( version_compare( ELEMENTOR_VERSION, self::MIN_ELEMENTOR_VERSION, '<' ) ) {
			add_action( 'admin_notices', [ $this, 'admin_notice_minimum_elementor_version' ] );
			return;
		}

		if ( version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '<' ) ) {
			add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
			return;
		}

		add_action( 'elementor/frontend/after_enqueue_styles', [ $this, 'enqueue_frontend_assets' ] );
		add_action( 'elementor/elements/categories_registered', [ $this, 'register_category' ] );
		add_action( 'elementor/widgets/register', [ $this, 'register_widgets' ] );
	}

	public function register_category( $elements_manager ): void {
		$elements_manager->add_category(
			'tooto',
			[
				'title' => __( 'Tooto 组件', 'tooto-elementor' ),
				'icon'  => 'fa fa-plug',
			]
		);
	}

	public function register_widgets( $widgets_manager ): void {
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-breadcrumbs.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-solutions-tabs.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-loop-grid.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-popover.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-timeline.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-post.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-posts.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-case-add-to-cart.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-image-carousel.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-text-type.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-file-download.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-hover-image-menu.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-product-content.php';
		require_once TOOTO_EA_PATH . 'includes/widgets/class-tooto-simple-splide.php';

		$widgets_manager->register( new Widgets\Breadcrumbs() );
		$widgets_manager->register( new Widgets\Solutions_Tabs() );
		$widgets_manager->register( new Widgets\Loop_Grid() );
		$widgets_manager->register( new Widgets\Popover() );
		$widgets_manager->register( new Widgets\Timeline() );
		$widgets_manager->register( new Widgets\Post() );
		$widgets_manager->register( new Widgets\Posts() );
		$widgets_manager->register( new Widgets\Case_Add_To_Cart() );
		$widgets_manager->register( new Widgets\Image_Carousel() );
		$widgets_manager->register( new Widgets\Text_Type() );
		$widgets_manager->register( new Widgets\File_Download() );
		$widgets_manager->register( new Widgets\Hover_Image_Menu() );
		$widgets_manager->register( new Widgets\Product_Content() );
		$widgets_manager->register( new Widgets\Simple_Splide() );
	}

	public function admin_notice_missing_elementor(): void {
		if ( isset( $_GET['activate'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			unset( $_GET['activate'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		$class   = 'notice notice-error';
		$message = sprintf(
			/* translators: 1: Plugin name */
			esc_html__( '%1$s 需要 Elementor 插件，请先启用 Elementor。', 'tooto-elementor' ),
			'<strong>Tooto Elementor Addons</strong>'
		);

		printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), wp_kses_post( $message ) );
	}

	public function admin_notice_minimum_elementor_version(): void {
		if ( isset( $_GET['activate'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			unset( $_GET['activate'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		$class   = 'notice notice-warning';
		$message = sprintf(
			/* translators: 1: Plugin name, 2: Elementor version */
			esc_html__( '%1$s 需要 Elementor 版本不低于 %2$s。', 'tooto-elementor' ),
			'<strong>Tooto Elementor Addons</strong>',
			self::MIN_ELEMENTOR_VERSION
		);

		printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), wp_kses_post( $message ) );
	}

	public function admin_notice_minimum_php_version(): void {
		if ( isset( $_GET['activate'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			unset( $_GET['activate'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		$class   = 'notice notice-warning';
		$message = sprintf(
			/* translators: 1: Plugin name, 2: PHP version */
			esc_html__( '%1$s 需要 PHP 版本不低于 %2$s。', 'tooto-elementor' ),
			'<strong>Tooto Elementor Addons</strong>',
			self::MIN_PHP_VERSION
		);

		printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), wp_kses_post( $message ) );
	}
}
