<?php
/**
 * WooCommerce My Account 页面自定义
 * 
 * 提供对 WooCommerce 我的账户页面的自定义功能，包括：
 * - 自定义菜单项
 * - 自定义样式
 * - 自定义内容区域
 * - 添加自定义端点
 */

namespace Tooto_Elementor;

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

use function add_action;
use function add_filter;
use function remove_action;
use function remove_all_actions;
use function apply_filters;


class WooCommerce_MyAccount {
	/**
	 * @var WooCommerce_MyAccount|null
	 */
	private static $instance = null;

	/**
	 * 获取单例实例
	 *
	 * @return WooCommerce_MyAccount
	 */
	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		// 立即初始化，不等待 init 钩子
		// 这样可以确保钩子在 WooCommerce 模板加载之前注册
		$this->maybe_init();
	}

	/**
	 * 检查并初始化功能
	 */
	public function maybe_init(): void {
		// 检查 WooCommerce 是否已加载
		// 如果还没有加载，等待 woocommerce_loaded 钩子
		if ( ! class_exists( 'WooCommerce' ) ) {
			add_action( 'woocommerce_loaded', [ $this, 'init' ], 1 );
			return;
		}

		// 如果 WooCommerce 已加载，立即初始化
		$this->init();
	}

	/**
	 * 初始化功能
	 */
	private function init(): void {
		// 注册重写端点（必须在 init 钩子中）
		add_action( 'init', [ $this, 'add_rewrite_endpoints' ], 10 );

		// 添加查询变量
		add_filter( 'query_vars', [ $this, 'add_query_vars' ], 10, 1 );

		// 使用更高的优先级确保在主题之后执行
		// 自定义菜单项 - 使用高优先级确保最后执行
		add_filter( 'woocommerce_account_menu_items', [ $this, 'customize_menu_items' ], 999, 1 );

		// 自定义导航样式 - 在主题之后执行
		add_action( 'woocommerce_before_account_navigation', [ $this, 'before_account_navigation' ], 999 );
		add_action( 'woocommerce_after_account_navigation', [ $this, 'after_account_navigation' ], 999 );

		// 替换导航输出以支持子菜单
		add_action( 'woocommerce_account_navigation', [ $this, 'custom_navigation_output' ], 1 );
		\remove_action( 'woocommerce_account_navigation', 'woocommerce_account_navigation', 10 );

		// 注册自定义端点
		add_filter( 'woocommerce_get_query_vars', [ $this, 'add_custom_query_vars' ], 10, 1 );
		add_action( 'woocommerce_account_store-information_endpoint', [ $this, 'store_information_endpoint' ] );
		add_action( 'woocommerce_account_delivery-address_endpoint', [ $this, 'delivery_address_endpoint' ] );
		add_action( 'woocommerce_account_invoice-information_endpoint', [ $this, 'invoice_information_endpoint' ] );
		
		// 处理 Store Information 表单提交
		add_action( 'template_redirect', [ $this, 'handle_store_information_submit' ] );

		// 替换导航输出以支持子菜单
		add_filter( 'woocommerce_account_menu_items', [ $this, 'customize_menu_items' ], 999, 1 );
		add_filter( 'woocommerce_account_menu_item_classes', [ $this, 'add_menu_item_classes' ], 10, 2 );

		// 限制地址修改
		add_filter( 'woocommerce_checkout_fields', [ $this, 'restrict_checkout_address_fields' ], 999 );
		add_filter( 'woocommerce_ship_to_different_address_checked', [ $this, 'force_ship_to_different_address' ] );
		add_action( 'template_redirect', [ $this, 'prevent_address_editing' ] );
		
		// 为地址编辑表单添加包裹容器
		add_action( 'woocommerce_before_edit_account_address_form', [ $this, 'before_edit_address_form' ] );
		add_action( 'woocommerce_after_edit_account_address_form', [ $this, 'after_edit_address_form' ] );

		// 保存自定义地址字段
		add_action( 'woocommerce_customer_save_address', [ $this, 'save_custom_address_fields' ], 10, 2 );

		// 替换导航输出以支持子菜单
		add_action( 'woocommerce_account_navigation', [ $this, 'custom_navigation_output' ], 1 );

		// 自定义内容区域 - 使用高优先级
		add_action( 'woocommerce_account_content', [ $this, 'before_account_content' ], 1 );
		add_action( 'woocommerce_account_content', [ $this, 'after_account_content' ], 999 );

		// 自定义端点内容 - 使用高优先级
		// 替换 dashboard 默认内容为订单列表
		add_action( 'woocommerce_account_dashboard', [ $this, 'customize_dashboard' ], 1 );
		\remove_action( 'woocommerce_account_dashboard', 'woocommerce_account_dashboard', 10 );

		// 替换 view-order 内容
		add_action( 'woocommerce_account_view-order_endpoint', [ $this, 'customize_view_order' ], 1 );
		\remove_action( 'woocommerce_account_view-order_endpoint', 'woocommerce_account_view_order', 10 );
		
		// 拦截并替换 dashboard 内容，移除欢迎信息
		// 使用高优先级在 WooCommerce 默认内容之前执行
		add_action( 'woocommerce_account_content', [ $this, 'replace_dashboard_content' ], 1 );

		// 添加 tooto-woo-account 类名到 woocommerce div
		// 使用比 blocksy 更高的优先级（10000 > 9999）
		add_filter( 'do_shortcode_tag', [ $this, 'add_tooto_account_class' ], 10000, 4 );

		// 注册自定义样式和脚本 - 确保在主题样式之后加载
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ], 999 );
		
		// 注册 Checkout 页面脚本
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_checkout_assets' ] );

		// 输出 Checkout 页面自定义样式
		add_action( 'wp_head', [ $this, 'output_checkout_styles' ], 999 );


		// 添加自定义 CSS 类 - 使用高优先级
		add_filter( 'body_class', [ $this, 'add_body_classes' ], 999, 1 );

		// 在管理员后台添加商店信息字段
		add_action( 'show_user_profile', [ $this, 'add_store_information_fields' ] );
		add_action( 'edit_user_profile', [ $this, 'add_store_information_fields' ] );
		add_action( 'personal_options_update', [ $this, 'save_store_information_fields' ] );
		add_action( 'edit_user_profile_update', [ $this, 'save_store_information_fields' ] );
		
		// 在管理员后台加载样式
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );

		// 在 my-account 页面禁用页脚渲染
		add_filter( 'blocksy:builder:footer:enabled', [ $this, 'disable_footer_on_account_page' ], 999 );

		// 调试：在页面底部添加一个隐藏的标记，确认功能已加载
		add_action( 'wp_footer', [ $this, 'debug_marker' ], 999 );
		
		// 调试：输出加载状态信息（仅管理员可见）
		add_action( 'wp_head', [ $this, 'debug_info' ], 998 );

		// 检查并刷新重写规则（仅在需要时）
		add_action( 'admin_init', [ $this, 'maybe_flush_rewrite_rules' ] );
		
		// 添加 WooCommerce 账户设置选项
		add_filter( 'woocommerce_get_settings_account', [ $this, 'add_account_settings' ] );

		// 自定义配送地址字段（Full Name 和 Address Type）
		add_filter( 'woocommerce_shipping_fields', [ $this, 'customize_shipping_fields' ], 100 );

		// 自定义账单地址字段 (Invoice Information)
		add_filter( 'woocommerce_billing_fields', [ $this, 'customize_billing_fields' ], 100 );

		// 订单创建前强制恢复配送地址（防止前端篡改）
		add_action( 'woocommerce_checkout_update_order_meta', [ $this, 'force_restore_shipping_address_on_checkout' ], 10, 2 );

		// 在 Checkout 页面 Shipping 字段前添加 "Checkout" 标题
		add_action( 'woocommerce_before_checkout_shipping_form', [ $this, 'add_checkout_section_heading' ] );
	}

	/**
	 * 在 Checkout 页面添加 Checkout 标题
	 */
	public function add_checkout_section_heading() {
		echo '<h3 class="tooto-checkout-heading">' . esc_html__( 'Checkout', 'tooto-elementor' ) . '</h3>';
	}

	/**
	 * 在 Checkout 流程中强制恢复配送地址
	 * 这是最后一道防线，即使用户在前端绕过了限制，提交的订单也会使用其账户中保存的地址
	 *
	 * @param int $order_id 订单 ID
	 * @param array $data 提交的数据
	 */
	public function force_restore_shipping_address_on_checkout( $order_id, $data ) {
		// 管理员不限制
		if ( current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return;
		}

		$customer = new \WC_Customer( $user_id );
		
		// 只有当用户已有配送地址时才强制覆盖
		if ( ! empty( $customer->get_shipping_address_1() ) ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				return;
			}

			// 强制覆盖 Shipping 信息
			$order->set_shipping_first_name( $customer->get_shipping_first_name() );
			$order->set_shipping_last_name( $customer->get_shipping_last_name() );
			$order->set_shipping_company( $customer->get_shipping_company() );
			$order->set_shipping_address_1( $customer->get_shipping_address_1() );
			$order->set_shipping_address_2( $customer->get_shipping_address_2() );
			$order->set_shipping_city( $customer->get_shipping_city() );
			$order->set_shipping_state( $customer->get_shipping_state() );
			$order->set_shipping_postcode( $customer->get_shipping_postcode() );
			$order->set_shipping_country( $customer->get_shipping_country() );
			$order->set_shipping_phone( $customer->get_shipping_phone() );
			
			// 还要恢复自定义字段 Address Type
			$address_type = get_user_meta( $user_id, 'shipping_address_type', true );
			if ( $address_type ) {
				$order->update_meta_data( 'shipping_address_type', $address_type );
			}

			$order->save();
		}
	}

	/**
	 * 自定义账单地址字段 (Invoice Information)
	 * 匹配设计稿：
	 * Row 1: Legal Company Name | Tax ID / EIN
	 * Row 2: Business Address | Phone Number (Company)
	 * Row 3: Contact Person | Email
	 * Row 4: Phone (Contact)
	 * 
	 * @param array $fields 字段数组
	 * @return array 修改后的字段数组
	 */
	public function customize_billing_fields( array $fields ): array {
		// 1. Legal Company Name (原 Company)
		if ( isset( $fields['billing_company'] ) ) {
			$fields['billing_company']['label'] = __( 'Legal Company Name', 'tooto-elementor' );
			$fields['billing_company']['class'] = [ 'form-row-first' ];
			$fields['billing_company']['priority'] = 10;
		}

		// 2. Tax ID / EIN (新字段)
		$fields['billing_tax_id'] = [
			'label'    => __( 'Tax ID / EIN', 'tooto-elementor' ),
			'required' => false,
			'class'    => [ 'form-row-last' ],
			'priority' => 10,
		];

		// 3. Business Address (原 Address 1)
		if ( isset( $fields['billing_address_1'] ) ) {
			$fields['billing_address_1']['label'] = __( 'Business Address', 'tooto-elementor' );
			$fields['billing_address_1']['class'] = [ 'form-row-wide' ];
			$fields['billing_address_1']['priority'] = 20;
			$fields['billing_address_1']['required'] = true;
			// 移除默认占位符
			$fields['billing_address_1']['placeholder'] = '';
		}

		// 5. Contact Person (原 First Name)
		if ( isset( $fields['billing_first_name'] ) ) {
			$fields['billing_first_name']['label'] = __( 'Contact Person', 'tooto-elementor' );
			$fields['billing_first_name']['class'] = [ 'form-row-wide' ];
			$fields['billing_first_name']['priority'] = 30;
			$fields['billing_first_name']['required'] = true;
		}

		// 移除 Last Name (合并到 Contact Person)
		if ( isset( $fields['billing_last_name'] ) ) {
			unset( $fields['billing_last_name'] );
		}

		// 6. Email (原 Email)
		if ( isset( $fields['billing_email'] ) ) {
			$fields['billing_email']['label'] = __( 'Email', 'tooto-elementor' );
			$fields['billing_email']['class'] = [ 'form-row-wide' ];
			$fields['billing_email']['priority'] = 31;
		}

		// 7. Phone (Contact) (原 Phone)
		if ( isset( $fields['billing_phone'] ) ) {
			$fields['billing_phone']['label'] = __( 'Phone', 'tooto-elementor' );
			$fields['billing_phone']['class'] = [ 'form-row-wide' ];
			$fields['billing_phone']['priority'] = 32;
			$fields['billing_phone']['required'] = true;
		}

		// 移除不需要的字段
		$fields_to_remove = [ 'billing_address_2' ];
		foreach ( $fields_to_remove as $field_name ) {
			if ( isset( $fields[ $field_name ] ) ) {
				unset( $fields[ $field_name ] );
			}
		}

		// 地址字段顺序调整：Country | City, State | Postcode
		if ( isset( $fields['billing_country'] ) ) {
			$fields['billing_country']['class'] = [ 'form-row-first' ];
			$fields['billing_country']['priority'] = 15;
		}
		if ( isset( $fields['billing_city'] ) ) {
			$fields['billing_city']['class'] = [ 'form-row-last' ];
			$fields['billing_city']['priority'] = 16;
			$fields['billing_city']['required'] = true;
		}
		if ( isset( $fields['billing_state'] ) ) {
			$fields['billing_state']['class'] = [ 'form-row-wide' ];
			$fields['billing_state']['priority'] = 17;
			$fields['billing_state']['label'] = __( 'State / County', 'tooto-elementor' );
		}
		if ( isset( $fields['billing_postcode'] ) ) {
			$fields['billing_postcode']['class'] = [ 'form-row-wide' ];
			$fields['billing_postcode']['priority'] = 18;
			$fields['billing_postcode']['required'] = true;
		}

		return $fields;
	}

	/**
	 * 自定义配送地址字段
	 * 1. 添加 Address Type, Phone
	 * 2. 将 First Name 改为 Full Name
	 * 3. 移除 Last Name, Company, Address 2
	 * 4. 调整布局为两列
	 *
	 * @param array $fields 字段数组
	 * @return array 修改后的字段数组
	 */
	public function customize_shipping_fields( array $fields ): array {
		// 1. 修改 "First Name" 为 "Full Name"
		if ( isset( $fields['shipping_first_name'] ) ) {
			$fields['shipping_first_name']['label'] = __( 'Full Name', 'tooto-elementor' );
			$fields['shipping_first_name']['class'] = [ 'form-row-first' ];
			$fields['shipping_first_name']['priority'] = 10;
		}

		// 2. 添加 "Phone Number" 字段 (WooCommerce 默认配送地址没有电话)
		$fields['shipping_phone'] = [
			'label'    => __( 'Phone Number', 'tooto-elementor' ),
			'required' => false, // 根据需求，这里设为可选或必填，通常为了联系方便建议设为 true
			'class'    => [ 'form-row-last' ],
			'priority' => 20,
		];

		// 3. 移除不需要的字段
		$fields_to_remove = [ 'shipping_last_name', 'shipping_company', 'shipping_address_2' ];
		foreach ( $fields_to_remove as $field_name ) {
			if ( isset( $fields[ $field_name ] ) ) {
				unset( $fields[ $field_name ] );
			}
		}

		// 4. 调整其他字段布局和优先级以匹配设计稿

		// Row 2: Country (Left) | State (Right)
		if ( isset( $fields['shipping_country'] ) ) {
			$fields['shipping_country']['class'] = [ 'form-row-first' ];
			$fields['shipping_country']['priority'] = 30;
		}
		if ( isset( $fields['shipping_state'] ) ) {
			$fields['shipping_state']['class'] = [ 'form-row-last' ];
			$fields['shipping_state']['priority'] = 40;
			$fields['shipping_state']['label'] = __( 'State/Province', 'tooto-elementor' ); // 修改标签以匹配设计稿
		}

		// Row 3: City (Left) | Street Address (Right)
		if ( isset( $fields['shipping_city'] ) ) {
			$fields['shipping_city']['class'] = [ 'form-row-first' ];
			$fields['shipping_city']['priority'] = 50;
		}
		if ( isset( $fields['shipping_address_1'] ) ) {
			$fields['shipping_address_1']['class'] = [ 'form-row-last' ];
			$fields['shipping_address_1']['priority'] = 60;
			$fields['shipping_address_1']['label'] = __( 'Street Address', 'tooto-elementor' ); // 确保标签一致
		}

		// Row 4: ZIP (Left) | Address Type (Right)
		if ( isset( $fields['shipping_postcode'] ) ) {
			$fields['shipping_postcode']['class'] = [ 'form-row-first' ];
			$fields['shipping_postcode']['priority'] = 70;
			$fields['shipping_postcode']['label'] = __( 'ZIP/Postal Code', 'tooto-elementor' ); // 修改标签以匹配设计稿
		}

		// Address Type
		$fields['shipping_address_type'] = [
			'label'    => __( 'Address Type', 'tooto-elementor' ),
			'type'     => 'radio',
			'options'  => [
				'residential' => __( 'Residential Address', 'tooto-elementor' ),
				'commercial'  => __( 'Commercial Address', 'tooto-elementor' ),
			],
			'required' => true,
			'class'    => [ 'form-row-last' ],
			'priority' => 80,
			'default'  => 'residential',
		];

		return $fields;
	}

	/**
	 * 保存自定义地址字段
	 *
	 * @param int    $user_id User ID.
	 * @param string $load_address Type of address; 'billing' or 'shipping'.
	 */
	public function save_custom_address_fields( $user_id, $load_address ) {
		if ( 'billing' === $load_address ) {
			if ( isset( $_POST['billing_tax_id'] ) ) {
				update_user_meta( $user_id, 'billing_tax_id', sanitize_text_field( $_POST['billing_tax_id'] ) );
			}
		} elseif ( 'shipping' === $load_address ) {
			if ( isset( $_POST['shipping_address_type'] ) ) {
				update_user_meta( $user_id, 'shipping_address_type', sanitize_text_field( $_POST['shipping_address_type'] ) );
			}
			if ( isset( $_POST['shipping_phone'] ) ) {
				update_user_meta( $user_id, 'shipping_phone', sanitize_text_field( $_POST['shipping_phone'] ) );
			}
		}
	}


	/**
	 * 检查并刷新重写规则（如果需要）
	 */
	public function maybe_flush_rewrite_rules(): void {
		$option_name = 'tooto_woocommerce_endpoints_flushed';
		if ( ! \get_option( $option_name ) ) {
			\flush_rewrite_rules();
			\update_option( $option_name, true );
		}
	}

	/**
	 * 添加 tooto-woo-account 类名到 woocommerce div
	 * 在 blocksy 主题添加 ct-woo-account 之后执行
	 *
	 * @param string $output 短代码输出
	 * @param string $tag 短代码标签
	 * @param array  $attr 短代码属性
	 * @param array  $m 匹配结果
	 * @return string 修改后的输出
	 */
	public function add_tooto_account_class( string $output, string $tag, array $attr, array $m ): string {
		// 只处理 woocommerce_my_account 短代码
		if ( $tag !== 'woocommerce_my_account' ) {
			return $output;
		}

		// 检查是否包含 ct-woo-account 类（blocksy 主题添加的）
		if ( strpos( $output, 'ct-woo-account' ) !== false ) {
			// 如果已经有 ct-woo-account，添加 tooto-woo-account
			$output = str_replace(
				'class="woocommerce ct-woo-account',
				'class="woocommerce ct-woo-account tooto-woo-account',
				$output
			);
		} elseif ( strpos( $output, 'class="woocommerce' ) !== false ) {
			// 如果没有 ct-woo-account，直接添加到 woocommerce 类后面
			$output = str_replace(
				'class="woocommerce',
				'class="woocommerce tooto-woo-account',
				$output
			);
		}

		return $output;
	}

	/**
	 * 调试标记 - 用于确认功能是否已加载
	 * 可以在页面源代码中搜索 "tooto-myaccount-loaded" 来确认
	 */
	public function debug_marker(): void {
		if ( \is_account_page() ) {
			echo '<!-- tooto-myaccount-loaded -->' . "\n";
		}
	}

	/**
	 * 自定义菜单项
	 * 可以重命名、重新排序、添加或移除菜单项
	 *
	 * @param array $items 菜单项数组
	 * @return array 修改后的菜单项数组
	 */
	public function customize_menu_items( array $items ): array {
		// 创建新的菜单结构
		$new_items = [];

		// 1. Dashboard
		if ( isset( $items['dashboard'] ) ) {
			$new_items['dashboard'] = __( 'Dashboard', 'tooto-elementor' );
		}

		// 2. Management (父级菜单，不直接链接)
		$new_items['management'] = __( 'Management', 'tooto-elementor' );

		// 3. 保留其他需要的菜单项
		// if ( isset( $items['downloads'] ) ) {
		// 	$new_items['downloads'] = __( 'Download Center', 'tooto-elementor' );
		// }

		// 移除不需要的菜单项
		unset( $items['orders'] );
		unset( $items['addresses'] );
		unset( $items['payment-methods'] );
		unset( $items['edit-account'] );

		// 保留登出
		if ( isset( $items['customer-logout'] ) ) {
			$new_items['customer-logout'] = $items['customer-logout'];
		}

		return $new_items;
	}

	/**
	 * 自定义导航输出，支持子菜单
	 */
	public function custom_navigation_output(): void {
		$endpoints = \wc_get_account_menu_items();
		$current_endpoint = \is_account_page() ? \WC()->query->get_current_endpoint() : '';
		
		// 如果当前没有端点，说明在 dashboard 页面
		if ( empty( $current_endpoint ) ) {
			$current_endpoint = 'dashboard';
		}

		?>
		<div class="tooto-account-mobile-toggle">
			<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
				<path d="M9 18L15 12L9 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
			</svg>
		</div>
		<div class="tooto-account-mobile-overlay"></div>
		<nav class="woocommerce-MyAccount-navigation tooto-custom-navigation" aria-label="<?php esc_attr_e( 'Account pages', 'woocommerce' ); ?>">
			<ul>
				<?php foreach ( $endpoints as $endpoint => $label ) : ?>
					<?php
					$url = '';
					$classes = [ 'woocommerce-MyAccount-navigation-link', 'woocommerce-MyAccount-navigation-link--' . $endpoint ];
					
					// Management 是父级菜单，没有直接链接
					if ( $endpoint !== 'management' ) {
						$url = \wc_get_account_endpoint_url( $endpoint );
					}
					
					// 检查是否为激活状态
					if ( $current_endpoint === $endpoint ) {
						$classes[] = 'is-active';
					}

					// Management 特殊处理
					if ( $endpoint === 'management' ) {
						$is_submenu_active = in_array( $current_endpoint, [ 'store-information', 'delivery-address', 'invoice-information' ], true );
						$classes[] = 'tooto-has-submenu';
						if ( $is_submenu_active ) {
							$classes[] = 'tooto-submenu-expanded';
							$classes[] = 'is-active'; // 子菜单激活时，父菜单也显示为激活
						}
						?>
						<li class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>">
							<a href="#" class="tooto-menu-toggle">
								<span class="tooto-menu-icon">
									<?php echo $this->get_menu_icon( $endpoint ); ?>
								</span>
								<span class="tooto-menu-label"><?php echo esc_html( $label ); ?></span>
								<span class="tooto-submenu-toggle-icon">
									<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
										<path d="M2 4L6 8L10 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
								</span>
							</a>
							<ul class="tooto-submenu" style="<?php echo $is_submenu_active ? 'display: block;' : 'display: none;'; ?>">
								<li class="tooto-submenu-item <?php echo ( $current_endpoint === 'store-information' ) ? 'tooto-submenu-item-active' : ''; ?>">
									<a href="<?php echo esc_url( \wc_get_endpoint_url( 'store-information', '', \wc_get_page_permalink( 'myaccount' ) ) ); ?>">
										<?php echo esc_html__( 'Store Information', 'tooto-elementor' ); ?>
									</a>
								</li>
								<li class="tooto-submenu-item <?php echo ( $current_endpoint === 'delivery-address' ) ? 'tooto-submenu-item-active' : ''; ?>">
									<a href="<?php echo esc_url( \wc_get_endpoint_url( 'delivery-address', '', \wc_get_page_permalink( 'myaccount' ) ) ); ?>">
										<?php echo esc_html__( 'Delivery Address', 'tooto-elementor' ); ?>
									</a>
								</li>
								<li class="tooto-submenu-item <?php echo ( $current_endpoint === 'invoice-information' ) ? 'tooto-submenu-item-active' : ''; ?>">
									<a href="<?php echo esc_url( \wc_get_endpoint_url( 'invoice-information', '', \wc_get_page_permalink( 'myaccount' ) ) ); ?>">
										<?php echo esc_html__( 'Invoice Information', 'tooto-elementor' ); ?>
									</a>
								</li>
							</ul>
						</li>
						<?php
					} else {
						?>
						<li class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>">
							<a href="<?php echo esc_url( $url ); ?>">
								<span class="tooto-menu-icon">
									<?php echo $this->get_menu_icon( $endpoint ); ?>
								</span>
								<span class="tooto-menu-label"><?php echo esc_html( $label ); ?></span>
							</a>
						</li>
						<?php
					}
					?>
				<?php endforeach; ?>
			</ul>
		</nav>
		<?php
	}

	/**
	 * 账户导航之前
	 * 可以在这里添加导航前的自定义 HTML
	 */
	public function before_account_navigation(): void {
		// 示例：添加导航前的包装器
		// echo '<div class="tooto-account-nav-wrapper">';
		
		// 示例：添加欢迎信息
		// echo '<div class="tooto-account-welcome">';
		// echo '<p>欢迎回来！</p>';
		// echo '</div>';
	}

	/**
	 * 账户导航之后
	 * 可以在这里添加导航后的自定义 HTML
	 */
	public function after_account_navigation(): void {
		// 示例：关闭导航包装器
		// echo '</div>';
		
		// 示例：添加额外的导航信息
		// echo '<div class="tooto-account-nav-footer">';
		// echo '<p>需要帮助？联系我们</p>';
		// echo '</div>';
	}

	/**
	 * 账户内容之前
	 * 可以在这里添加内容区域前的自定义 HTML
	 */
	public function before_account_content(): void {
		// 示例：添加内容包装器
		// echo '<div class="tooto-account-content-wrapper">';
		
		// 示例：添加自定义横幅
		// echo '<div class="tooto-account-banner">';
		// echo '<h2>我的账户</h2>';
		// echo '</div>';
	}

	/**
	 * 账户内容之后
	 * 可以在这里添加内容区域后的自定义 HTML
	 */
	public function after_account_content(): void {
		// 不在订单详情页显示推荐产品
		global $wp;
		if ( isset( $wp->query_vars['view-order'] ) ) {
			return;
		}
	}

	/**
	 * 替换 dashboard 内容 - 移除欢迎信息，直接显示订单列表
	 */
	public function replace_dashboard_content(): void {
		global $wp;
		
		// 检查是否有端点
		$has_endpoint = false;
		if ( ! empty( $wp->query_vars ) ) {
			foreach ( $wp->query_vars as $key => $value ) {
				// 忽略 pagename 参数
				if ( 'pagename' === $key ) {
					continue;
				}
				// 如果有其他端点，不处理，让 WooCommerce 正常处理
				if ( \has_action( 'woocommerce_account_' . $key . '_endpoint' ) ) {
					$has_endpoint = true;
					break;
				}
			}
		}
		
		// 如果是 dashboard 页面（没有端点），直接输出订单列表并阻止后续执行
		if ( ! $has_endpoint ) {
			// 直接输出订单列表
			$this->customize_dashboard();
			
			// 移除所有后续的 woocommerce_account_content 动作，阻止默认 dashboard 模板加载
			\remove_all_actions( 'woocommerce_account_content' );
		}
	}

	/**
	 * 自定义仪表盘内容 - 显示订单列表
	 */
	public function customize_dashboard(): void {
		// 获取筛选参数
		$status_filter = isset( $_GET['order_status'] ) ? sanitize_text_field( $_GET['order_status'] ) : '';
		$stock_filter  = isset( $_GET['stock_status'] ) ? sanitize_text_field( $_GET['stock_status'] ) : '';
		$current_page  = empty( $_GET['orders-page'] ) ? 1 : absint( $_GET['orders-page'] );
		
		// 1. 获取用户的所有订单（为了在 PHP 层进行准确的 Item 筛选）
		$args = array(
			'customer' => \get_current_user_id(),
			'limit'    => -1, // 获取所有订单以进行筛选
			'status'   => 'all',
			'type'     => 'shop_order',
		);

		// 应用订单状态筛选（WooCommerce 标准状态）
		if ( ! empty( $status_filter ) && 'all' !== $status_filter ) {
			$args['status'] = $status_filter;
		}

		$all_orders = \wc_get_orders( $args );
		
		// 2. 应用产品状态筛选（基于商品名称关键词）
		$filtered_orders = [];
		if ( ! empty( $stock_filter ) && 'all' !== $stock_filter ) {
			foreach ( $all_orders as $order ) {
				$items = $order->get_items();
				$found = false;
				$is_pure_instock = true;

				foreach ( $items as $item ) {
					$product_name = $item->get_name();
					// 检查特殊标记
					$has_preorder   = stripos( $product_name, 'pre-order' ) !== false || stripos( $product_name, 'pre order' ) !== false || stripos( $product_name, '[PRE-ORDER]' ) !== false;
					$has_restocking = stripos( $product_name, 'restocking' ) !== false || stripos( $product_name, '[RESTOCKING]' ) !== false;
					$has_outstock   = stripos( $product_name, 'out of stock' ) !== false || stripos( $product_name, '[OUT OF STOCK]' ) !== false;

					if ( $has_preorder || $has_restocking || $has_outstock ) {
						$is_pure_instock = false;
					}

					if ( 'pre-order' === $stock_filter && $has_preorder ) {
						$found = true;
						break;
					}
					if ( 'restocking' === $stock_filter && $has_restocking ) {
						$found = true;
						break;
					}
					if ( 'out-of-stock' === $stock_filter && $has_outstock ) {
						$found = true;
						break;
					}
				}

				// In Stock 逻辑：不包含任何特殊标记的订单
				if ( 'in-stock' === $stock_filter && $is_pure_instock ) {
					$found = true;
				}

				if ( $found ) {
					$filtered_orders[] = $order;
				}
			}
		} else {
			$filtered_orders = $all_orders;
		}

		// 3. 手动分页
		$orders_per_page = apply_filters( 'woocommerce_my_account_orders_per_page', 5 );
		$total_orders    = count( $filtered_orders );
		$total_pages     = ceil( $total_orders / $orders_per_page );
		
		// 确保当前页面不过界
		if ( $current_page > $total_pages && $total_pages > 0 ) {
			$current_page = $total_pages;
		}
		
		$offset = ( $current_page - 1 ) * $orders_per_page;
		$current_page_orders = array_slice( $filtered_orders, $offset, $orders_per_page );
		
		// 获取所有可用的订单状态用于筛选器
		$order_statuses = \wc_get_order_statuses();
		
		?>
		<div class="tooto-dashboard-orders-wrapper">
			<!-- Header Area: Title & Filters -->
			<div class="tooto-dashboard-header">
				<h3 class="tooto-dashboard-title"><?php esc_html_e( 'Orders', 'tooto-elementor' ); ?></h3>
				
				<!-- Mobile Filter Trigger -->
				<div class="tooto-mobile-filter-trigger">
					<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="33.5" height="33" viewBox="0 0 33.5 33"><path d="M31.558208,8.914534100000001L15.505926,8.9147027C14.861759,6.5981947000000005,12.791974,5.0000000000015214,10.436087,5.0000000000015214C8.0802002,4.999998199454,6.0104151,6.5981929,5.3662491,8.9147027L1.44151,8.9147027C0.64515877,8.9154949,0,9.575644,0,10.389707600000001C0,11.2037706,0.64515835,11.8639235,1.44151,11.8647194L5.3662491,11.8647194C6.0104151,14.1812248,8.0802002,15.779419,10.436087,15.779419C12.791974,15.779419,14.861759,14.1812248,15.505926,11.8647194L31.558208,11.8645511C32.354561,11.8637519,33,11.2036061,33,10.3895426C33,9.575479,32.354557,8.9153264,31.558208,8.914534100000001ZM10.436087,12.8299642C9.1173935,12.8312678,8.0474653,11.7393041,8.0466137,10.391284500000001C8.0457649,9.0432615,9.1143131,7.9498899000000005,10.43301,7.9494541000000005C11.751704,7.9490221000000005,12.820944,9.041688,12.820944,10.3897109C12.819674,11.7359662,11.753053,12.827364,10.436087,12.8299642ZM31.552572,22.13545L24.794527,22.13545C24.150362,19.818943,22.081034,18.220916000000003,19.725149,18.220916000000003C17.369263,18.220916000000003,15.29994,19.818943,14.655769,22.13545L1.4429187,22.13545C0.6460163,22.13545,0,22.795834,0,23.610458C0,24.425083,0.6460163,25.085466,1.4429187,25.085466L5.7401109,25.085466L14.655769,25.085466C15.299935,27.401974,17.369263,29,19.725149,29C22.081039,29,24.150362,27.401974,24.794527,25.085466L31.552572,25.085466C32.349472,25.085466,32.995491,24.425083,32.995491,23.610458C32.995491,22.795834,32.349476,22.13545,31.552572,22.13545ZM19.725149,26.048256C18.406157,26.049559,17.335739,24.95706,17.335314,23.60873C17.33489,22.260399,18.405025,21.16762,19.724022,21.168051C21.043016,21.168488,22.111748,22.262129,22.110474,23.610458C22.109201,24.956331,21.04174,26.046959,19.725149,26.048256Z" fill="#000000" fill-opacity="1"/></svg>
					<span>Filter</span>
				</div>

				<form method="get" class="tooto-dashboard-filters tooto-desktop-filters" style="display: flex; gap: 10px;">
					<!-- 状态筛选 -->
					<div class="tooto-select-wrapper">
						<select name="order_status" onchange="this.form.submit()">
							<option value="all" <?php selected( $status_filter, 'all' ); ?>><?php esc_html_e( 'All Statuses', 'tooto-elementor' ); ?></option>
							<?php foreach ( $order_statuses as $slug => $name ) : ?>
								<option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $status_filter, $slug ); ?>><?php echo esc_html( $name ); ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					
					<!-- 产品状态筛选 -->
					<div class="tooto-select-wrapper">
						<select name="stock_status" onchange="this.form.submit()">
							<option value="all" <?php selected( $stock_filter, 'all' ); ?>><?php esc_html_e( 'All Orders', 'tooto-elementor' ); ?></option>
							<option value="pre-order" <?php selected( $stock_filter, 'pre-order' ); ?>><?php esc_html_e( 'Pre-order', 'tooto-elementor' ); ?></option>
							<option value="in-stock" <?php selected( $stock_filter, 'in-stock' ); ?>><?php esc_html_e( 'In Stock', 'tooto-elementor' ); ?></option>
							<option value="restocking" <?php selected( $stock_filter, 'restocking' ); ?>><?php esc_html_e( 'Restocking', 'tooto-elementor' ); ?></option>
							<option value="out-of-stock" <?php selected( $stock_filter, 'out-of-stock' ); ?>><?php esc_html_e( 'Out of Stock', 'tooto-elementor' ); ?></option>
						</select>
					</div>
				</form>
			</div>

			<!-- Mobile Filter Modal -->
			<div id="tooto-mobile-filter-modal" class="tooto-mobile-filter-modal" style="display: none;">
				<div class="tooto-mobile-filter-overlay"></div>
				<div class="tooto-mobile-filter-content">
					<div class="tooto-mobile-filter-header">
						<h4><?php esc_html_e( 'Filters', 'tooto-elementor' ); ?></h4>
						<span class="tooto-mobile-filter-close">&times;</span>
					</div>
					<form method="get" class="tooto-mobile-filters-form">
						<div class="tooto-mobile-filter-body">
							<!-- 状态筛选 -->
							<div class="tooto-select-wrapper">
								<label><?php esc_html_e( 'Order Status', 'tooto-elementor' ); ?></label>
								<select name="order_status" onchange="this.form.submit()">
									<option value="all" <?php selected( $status_filter, 'all' ); ?>><?php esc_html_e( 'All Statuses', 'tooto-elementor' ); ?></option>
									<?php foreach ( $order_statuses as $slug => $name ) : ?>
										<option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $status_filter, $slug ); ?>><?php echo esc_html( $name ); ?></option>
									<?php endforeach; ?>
								</select>
							</div>
							
							<!-- 产品状态筛选 -->
							<div class="tooto-select-wrapper">
								<label><?php esc_html_e( 'Stock Status', 'tooto-elementor' ); ?></label>
								<select name="stock_status" onchange="this.form.submit()">
									<option value="all" <?php selected( $stock_filter, 'all' ); ?>><?php esc_html_e( 'All Orders', 'tooto-elementor' ); ?></option>
									<option value="pre-order" <?php selected( $stock_filter, 'pre-order' ); ?>><?php esc_html_e( 'Pre-order', 'tooto-elementor' ); ?></option>
									<option value="in-stock" <?php selected( $stock_filter, 'in-stock' ); ?>><?php esc_html_e( 'In Stock', 'tooto-elementor' ); ?></option>
									<option value="restocking" <?php selected( $stock_filter, 'restocking' ); ?>><?php esc_html_e( 'Restocking', 'tooto-elementor' ); ?></option>
									<option value="out-of-stock" <?php selected( $stock_filter, 'out-of-stock' ); ?>><?php esc_html_e( 'Out of Stock', 'tooto-elementor' ); ?></option>
								</select>
							</div>
						</div>
					</form>
				</div>
			</div>

			<!-- Custom Orders Table -->
			<?php if ( ! empty( $current_page_orders ) ) : ?>
				<div class="tooto-orders-list-wrapper">
					<div class="tooto-orders-list">
						<!-- List Header -->
						<div class="tooto-orders-header">
							<div class="tooto-orders-row">
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'Order Number', 'tooto-elementor' ); ?></div>
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'Product', 'tooto-elementor' ); ?></div>
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'Date Of Order', 'tooto-elementor' ); ?></div>
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'State', 'tooto-elementor' ); ?></div>
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'Order Total', 'tooto-elementor' ); ?></div>
								<div class="tooto-orders-col header-col"><?php esc_html_e( 'Action', 'tooto-elementor' ); ?></div>
							</div>
						</div>
						
						<!-- List Body -->
						<div class="tooto-orders-body">
							<?php foreach ( $current_page_orders as $order ) : 
								$items      = $order->get_items();
								$product_names = [];
								foreach ( $items as $item ) {
									$name = $item->get_name();
									$prefix = '';
									
									// Detect and add status prefix based on actual product stock status
									$product = $item->get_product();
									if ( $product ) {
										$stock_status = $product->get_stock_status();
										// Exclude 'instock'
										if ( 'instock' !== $stock_status ) {
											$status_label = '';
											switch ( $stock_status ) {
												case 'outofstock':
													$status_label = 'OUT OF STOCK';
													break;
												case 'onbackorder':
													$status_label = 'PRE-ORDER'; 
													break;
												default:
													$status_label = strtoupper( str_replace( '-', ' ', $stock_status ) );
													break;
											}
											
											if ( ! empty( $status_label ) ) {
												$prefix = '<span style="color: #C1272D; font-weight: 500;">[' . esc_html( $status_label ) . ']</span> ';
											}
										}
									}
									
									$product_names[] = $prefix . esc_html( $name );
								}
								$product_display = implode( ', ', array_slice( $product_names, 0, 2 ) );
								if ( count( $product_names ) > 2 ) {
									$product_display .= '...';
								}
								
								// 状态样式映射
								$status = $order->get_status();
								$status_color = '#464646';
								$status_bg = '#E7E7E7';
								
								switch ( $status ) {
									case 'completed':
										$status_color = '#389E0D'; // Blue/Green
										$status_bg = '#E7FFD6';
										break;
									case 'processing':
										$status_color = '#D48806'; // Orange
										$status_bg = '#FFFBD6';
										break;
									case 'on-hold':
										$status_color = '#FF4D4F'; // Red
										$status_bg = '#FFF1F0';
										break;
									case 'pending':
										$status_color = '#9333ea'; // Purple
										$status_bg = '#f3e8ff';
										break;
								}
							?>
							<div class="tooto-orders-row">
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'Order Number', 'tooto-elementor' ); ?>">
									<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>" style="color: #3E3333;">
										<?php echo esc_html( $order->get_order_number() ); ?>
									</a>
								</div>
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'Product', 'tooto-elementor' ); ?>">
									<div class="tooto-product-display">
										<?php echo wp_kses_post( $product_display ?: __( 'No products', 'tooto-elementor' ) ); ?>
									</div>
								</div>
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'Date Of Order', 'tooto-elementor' ); ?>">
									<?php echo esc_html( wc_format_datetime( $order->get_date_created(), 'F j, Y' ) ); ?>
								</div>
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'State', 'tooto-elementor' ); ?>">
									<span style="display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500; color: <?php echo $status_color; ?>; background-color: <?php echo $status_bg; ?>;">
										<?php echo esc_html( wc_get_order_status_name( $status ) ); ?>
									</span>
								</div>
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'Order Total', 'tooto-elementor' ); ?>">
									<div class="tooto-order-total-display" style="font-weight: 600;">
										<?php echo $order->get_formatted_order_total(); ?>
									</div>
								</div>
								<div class="tooto-orders-col" data-label="<?php esc_attr_e( 'Action', 'tooto-elementor' ); ?>">
									<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>" class="button" style="padding: 6px 16px; font-size: 13px; border-radius: 4px;min-height: 32px;max-width: 82px;width: 100%;">
										<?php esc_html_e( 'View', 'tooto-elementor' ); ?>
									</a>
								</div>
							</div>
							<?php endforeach; ?>
						</div>
					</div>
				</div>

				<!-- Pagination -->
				<?php if ( 1 < $total_pages ) : ?>
					<div class="tooto-dashboard-pagination">
						<?php
						$base_url = add_query_arg( array(
							'orders-page' => '%#%',
							'order_status' => $status_filter,
							'stock_status' => $stock_filter,
						), wc_get_account_endpoint_url( 'dashboard' ) );

						echo paginate_links( array(
							'base'      => $base_url,
							'format'    => '',
							'current'   => $current_page,
							'total'     => $total_pages,
							'prev_text' => '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
							'next_text' => '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
							'type'      => 'list',
							'end_size'  => 1,
							'mid_size'  => 1,
						) );
						?>
					</div>
					<style>
						.tooto-dashboard-pagination {
							margin-top: 16px;
							display: flex;
							justify-content: flex-end;
							padding-right: 24px;
						}
						.tooto-dashboard-pagination ul {
							display: flex;
							gap: 6px;
							list-style: none;
							padding: 0;
							margin: 0;
							border: none;
						}
						.tooto-dashboard-pagination ul li {
							margin: 0;
							border: none;
							overflow: hidden;
						}
						.tooto-dashboard-pagination ul li a,
						.tooto-dashboard-pagination ul li span {
							display: flex;
							align-items: center;
							justify-content: center;
							min-width: 28px;
							height: 28px;
							padding: 0 6px;
							font-size: 13px;
							line-height: 1;
							color: #666;
							background: transparent;
							border: 1px solid #e5e5e5;
							border-radius: 4px;
							text-decoration: none;
							transition: all 0.2s ease;
							font-weight: 500;
						}
						.tooto-dashboard-pagination ul li a:hover,
						.tooto-dashboard-pagination ul li span.current {
							border-color: #C1272D;
							color: #fff;
							background: #C1272D;
						}
						.tooto-dashboard-pagination ul li span.dots {
							border: none;
							background: transparent;
							min-width: auto;
							padding: 0 4px;
						}
						.tooto-dashboard-pagination svg {
							width: 14px;
							height: 14px;
							display: block;
						}
					</style>
				<?php endif; ?>

			<?php else : ?>
				<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
					<a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>">
						<?php esc_html_e( 'Browse products', 'woocommerce' ); ?>
					</a>
					<?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
		$this->render_recommend_products();
	}

	/**
	 * 自定义 View Order 页面
	 * 
	 * @param int $order_id 订单 ID
	 */
	public function customize_view_order( $order_id ): void {
		$order = \wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		// 状态颜色映射
		$status = $order->get_status();
		$status_color = '#777';
		$status_bg = '#eee';
		
		switch ( $status ) {
			case 'completed':
				$status_color = '#15803d'; // Green
				$status_bg = '#dcfce7';
				break;
			case 'processing':
				$status_color = '#d97706'; // Orange
				$status_bg = '#fef3c7';
				break;
			case 'on-hold':
				$status_color = '#dc2626'; // Red
				$status_bg = '#fee2e2';
				break;
			case 'pending':
				$status_color = '#9333ea'; // Purple
				$status_bg = '#f3e8ff';
				break;
		}

		$order_actions = \wc_get_account_orders_actions( $order );
		
		?>
		<div class="tooto-view-order-container">
			<!-- Back Link -->
			<div class="tooto-back-link-wrapper">
				<a href="<?php echo esc_url( \wc_get_account_endpoint_url( 'dashboard' ) ); ?>" class="tooto-back-link">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 4px;"><path d="M19 12H5M5 12L12 19M5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
					<?php esc_html_e( 'Back', 'tooto-elementor' ); ?>
				</a>
			</div>

			<div class="tooto-order-grid-top">
				<!-- Main Content (Order Details) -->
				<div class="tooto-card tooto-order-main-card">
					<div class="tooto-order-header">
						<span class="tooto-order-label"><?php esc_html_e( 'Order Number:', 'tooto-elementor' ); ?></span>
						<span class="tooto-order-number"><?php echo esc_html( $order->get_order_number() ); ?></span>
					</div>

					<div class="tooto-order-items-wrapper">
						<!-- Desktop Header -->
						<div class="tooto-order-items-header">
							<div class="tooto-header-col product-col"><?php esc_html_e( 'Product', 'tooto-elementor' ); ?></div>
							<div class="tooto-header-col cost-col"><?php esc_html_e( 'Cost ($)', 'tooto-elementor' ); ?></div>
							<div class="tooto-header-col qty-col"><?php esc_html_e( 'Qty', 'tooto-elementor' ); ?></div>
							<div class="tooto-header-col total-col"><?php esc_html_e( 'Total ($)', 'tooto-elementor' ); ?></div>
						</div>

						<?php foreach ( $order->get_items() as $item_id => $item ) : 
							$product = $item->get_product();
							$product_permalink = $product ? $product->get_permalink( $item ) : '';
							$thumbnail = $product ? $product->get_image( 'thumbnail' ) : '';
							$prefix_html = '';
							if ( $product ) {
								$stock_status = $product->get_stock_status();
								if ( 'instock' !== $stock_status ) {
									$status_label = '';
									switch ( $stock_status ) {
										case 'outofstock':
											$status_label = 'OUT OF STOCK';
											break;
										case 'onbackorder':
											$status_label = 'PRE-ORDER';
											break;
										default:
											$status_label = strtoupper( str_replace( '-', ' ', $stock_status ) );
											break;
									}
									if ( ! empty( $status_label ) ) {
										$prefix_html = '<span style="color: #C1272D; font-weight: 500;">[' . esc_html( $status_label ) . ']</span> ';
									}
								}
							}
						?>
							<div class="tooto-order-item-card">
								<div class="tooto-order-item-header">
									<span class="label mobile-only"><?php esc_html_e( 'Product', 'tooto-elementor' ); ?></span>
									<div class="value">
										<div class="thumb">
											<?php if ( $product_permalink ) : ?>
												<a href="<?php echo esc_url( $product_permalink ); ?>"><?php echo $thumbnail; ?></a>
											<?php else : ?>
												<?php echo $thumbnail; ?>
											<?php endif; ?>
										</div>
										<span class="product-name">
											<?php echo wp_kses_post( $prefix_html ); ?>
											<?php if ( $product_permalink ) : ?>
												<a href="<?php echo esc_url( $product_permalink ); ?>" style="color: #3E3333;"><?php echo esc_html( $item->get_name() ); ?></a>
											<?php else : ?>
												<?php echo esc_html( $item->get_name() ); ?>
											<?php endif; ?>
										</span>
									</div>
								</div>
								<div class="tooto-order-item-row cost-row">
									<span class="label mobile-only"><?php esc_html_e( 'Cost ($)', 'tooto-elementor' ); ?></span>
									<span class="value"><?php echo \wc_price( $order->get_item_subtotal( $item, false, true ), [ 'currency' => $order->get_currency() ] ); ?></span>
								</div>
								<div class="tooto-order-item-row qty-row">
									<span class="label mobile-only"><?php esc_html_e( 'Qty', 'tooto-elementor' ); ?></span>
									<span class="value"><?php echo esc_html( $item->get_quantity() ); ?></span>
								</div>
								<div class="tooto-order-item-row total-row">
									<span class="label mobile-only"><?php esc_html_e( 'Total ($)', 'tooto-elementor' ); ?></span>
									<span class="value"><?php echo \wc_price( $item->get_total(), [ 'currency' => $order->get_currency() ] ); ?></span>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
					<div style="width: 96%;height: 1px;background-color: #eee;margin: auto;" class="mobile-hidden"></div>
					<div class="tooto-order-totals">
						<div class="tooto-total-row">
							<span class="label"><?php esc_html_e( 'Order Total:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo $order->get_formatted_order_total(); ?></span>
						</div>
						<div class="tooto-total-row">
							<span class="label"><?php esc_html_e( 'Shipping:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo \wc_price( $order->get_shipping_total(), [ 'currency' => $order->get_currency() ] ); ?></span>
						</div>
						<div class="tooto-total-row highlight">
							<span class="label"><?php esc_html_e( 'Amount Paid:', 'tooto-elementor' ); ?></span>
							<span class="value red-text"><?php echo $order->get_formatted_order_total(); ?></span>
						</div>
					</div>
				</div>

				<!-- Sidebar (Logistics Information) -->
				<div class="tooto-card tooto-order-sidebar-card">
					<h3 class="tooto-card-title"><?php esc_html_e( 'Logistics Information', 'tooto-elementor' ); ?></h3>
					<div class="tooto-info-list">
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'State:', 'tooto-elementor' ); ?></span>
							<span class="value-badge" style="color: <?php echo $status_color; ?>; background-color: <?php echo $status_bg; ?>;">
								<?php echo esc_html( \wc_get_order_status_name( $status ) ); ?>
							</span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Order Time:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_date_created()->date_i18n( 'F j, Y, g:i a' ) ); ?></span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Shipping Method:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_shipping_method() ); ?></span>
						</div>
						<!-- Placeholder for Tracking Info (Requires Plugin Support usually) -->
						<?php 
						// 尝试获取常见的跟踪号字段
						$tracking_number = $order->get_meta( '_tracking_number' ) ?: $order->get_meta( 'tracking_number' );
						if ( $tracking_number ) : 
						?>
							<div class="tooto-info-item">
								<span class="label"><?php esc_html_e( 'Tracking Number:', 'tooto-elementor' ); ?></span>
								<span class="value"><?php echo esc_html( $tracking_number ); ?></span>
							</div>
						<?php endif; ?>
						
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Shipment Date:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo $order->get_date_completed() ? esc_html( $order->get_date_completed()->date_i18n( 'F j, Y' ) ) : '-'; ?></span>
						</div>
						
						<!-- Estimated Delivery Date (Placeholder/Meta) -->
						<?php 
						$estimated_delivery = $order->get_meta( '_estimated_delivery' ) ?: $order->get_meta( 'estimated_delivery' );
						if ( $estimated_delivery ) : 
						?>
							<div class="tooto-info-item">
								<span class="label"><?php esc_html_e( 'Estimated Delivery Date:', 'tooto-elementor' ); ?></span>
								<span class="value"><?php echo esc_html( $estimated_delivery ); ?></span>
							</div>
						<?php endif; ?>
					</div>
					<div class="action">
						<?php 
						// Filter out 'view' action first
						$visible_actions = array_filter( $order_actions, function( $key ) {
							return $key !== 'view';
						}, ARRAY_FILTER_USE_KEY );
						
						if ( ! empty( $visible_actions ) ) : 
						?>
							<div class="tooto-info-item">
								<span class="label"><?php esc_html_e( 'Actions:', 'tooto-elementor' ); ?></span>
								<div class="tooto-order-actions-sidebar">
									<?php foreach ( $visible_actions as $key => $action ) : ?>
										<a href="<?php echo esc_url( $action['url'] ); ?>" class="button <?php echo sanitize_html_class( $key ); ?>"><?php echo esc_html( $action['name'] ); ?></a>
									<?php endforeach; ?>
								</div>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div>

			<div class="tooto-order-grid-bottom">
				<!-- Consignee Information -->
				<div class="tooto-card tooto-consignee-card">
					<h3 class="tooto-card-title"><?php esc_html_e( 'Consignee Information', 'tooto-elementor' ); ?></h3>
					<div class="tooto-info-list">
						<?php if ( $order->get_shipping_company() ) : ?>
							<div class="tooto-info-item">
								<span class="label"><?php esc_html_e( 'Company / Store Name:', 'tooto-elementor' ); ?></span>
								<span class="value"><?php echo esc_html( $order->get_shipping_company() ); ?></span>
							</div>
						<?php endif; ?>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Contact Person:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ); ?></span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Telephone:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_billing_phone() ); // Usually phone is in billing ?></span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Shipping Address:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_shipping_address_1() . ' ' . $order->get_shipping_address_2() . ', ' . $order->get_shipping_city() . ' ' . $order->get_shipping_postcode() ); ?></span>
						</div>
					</div>
				</div>

				<!-- Payment Information -->
				<div class="tooto-card tooto-payment-card">
					<h3 class="tooto-card-title"><?php esc_html_e( 'Payment Information', 'tooto-elementor' ); ?></h3>
					<div class="tooto-info-list">
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Amount Paid:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo $order->get_formatted_order_total(); ?></span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Payment Method:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo esc_html( $order->get_payment_method_title() ); ?></span>
						</div>
						<div class="tooto-info-item">
							<span class="label"><?php esc_html_e( 'Payment Time:', 'tooto-elementor' ); ?></span>
							<span class="value"><?php echo $order->get_date_paid() ? esc_html( $order->get_date_paid()->date_i18n( 'F j, Y, g:i a' ) ) : '-'; ?></span>
						</div>
					</div>
				</div>
			</div>
		</div>

		<style>
			.tooto-view-order-container {
				font-family: inherit;
				color: #333;
			}
			.tooto-back-link-wrapper {
				margin-bottom: 20px;
			}
			.tooto-back-link {
				display: inline-flex;
				align-items: center;
				color: #C1272D;
				font-weight: 500;
				text-decoration: none;
				font-size: 14px;
			}
			.tooto-back-link:hover {
				text-decoration: underline;
			}
			
			.tooto-order-grid-top {
				display: grid;
				grid-template-columns: 1fr 350px;
				gap: 20px;
				margin-bottom: 20px;
			}
			.tooto-order-grid-bottom {
				display: grid;
				grid-template-columns: 1fr 1fr;
				gap: 20px;
			}
			
			.tooto-card {
				border: 1px solid #eee;
				border-radius: 8px;
			}
			
			.tooto-card h3.tooto-card-title {
				font-size: 20px;
				padding: 20px 16px;
				line-height: 24px;
				background-color: #f5f5f5;
				font-weight: 600;
				margin: 0;
				color: #000;
			}
			
			/* Order Header */
			.tooto-order-header {
				padding-bottom: 16px;
				line-height: 24px;
				padding: 20px 16px;
				font-size: 20px;
				font-weight: 600;
				background-color: #F5F5F5;
			}
			.tooto-order-actions-sidebar {
				display: flex;
				gap: 10px;
			}
			.tooto-order-actions-sidebar .button {
				padding: 4px 12px;
				font-size: 13px;
				background-color: #C1272D;
				color: #fff;
				border-radius: 4px;
				text-decoration: none;
				font-weight: 500;
				line-height: 1.5;
				border: none;
				cursor: pointer;
				transition: background-color 0.2s;
				display: inline-block;
				min-height: min-content;
			}
			.tooto-order-actions-sidebar .button:hover {
				background-color: #a01f24;
				color: #fff;
			}
			.tooto-order-actions-sidebar .button.pay {
				background-color: #15803d;
			}
			.tooto-order-actions-sidebar .button.pay:hover {
				background-color: #166534;
			}
			.tooto-order-number {
				color: #C1272D;
				margin-left: 10px;
				font-weight: 500;
			}
			.tooto-order-items-wrapper {
				padding: 16px;
			}

			/* Items Table */
			.tooto-order-items-table {
				width: 100%;
				border-collapse: collapse;
				border: none;
			}
			.tooto-order-items-table th {
				text-align: left;
				padding: 10px 0;
				color: #878282;
				font-weight: 500;
				font-size: 14px;
				border: none;
			}
			.tooto-order-items-table td {
				padding: 15px 0;
				vertical-align: middle;
				border: none;
			}
			.tooto-product-item {
				display: flex;
				align-items: center;
				gap: 12px;
			}
			.tooto-product-image {
				width: 64px;
				height: 64px;
				flex-shrink: 0;
				border-radius: 4px;
				overflow: hidden;
				background: #f9f9f9;
			}
			.tooto-product-image img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
			.tooto-product-name {
				font-weight: 500;
			}
			.tooto-product-name a {
				color: #333;
				text-decoration: none;
			}
			
			/* Totals */
			.tooto-order-totals {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				padding: 12px 16px;
			}
			.tooto-total-row {
				display: flex;
				justify-content: flex-end;
				gap: 20px;
				margin-bottom: 8px;
				font-size: 14px;
			}
			.tooto-total-row.highlight {
				font-size: 16px;
				font-weight: 600;
				margin-top: 10px;
				color: #C1272D;
			}
			.red-text {
				color: #C1272D;
			}
			
			/* Info List */
			.tooto-info-list {
				display: flex;
				flex-direction: column;
				gap: 12px;
				padding: 16px;
				flex: 1;
			}
			.action {
				padding: 16px;
			}
			.tooto-info-item {
				display: flex;
				flex-wrap: wrap;
				gap: 10px;
				font-size: 14px;
				align-items: center;
				line-height: 1.5;
			}
			.action .tooto-info-item {
				gap: 12px;
			}
			.tooto-info-item .label {
				font-weight: 500;
				color: #3e333e;
			}
			.tooto-info-item .value {
				color: #878282;
			}
			.tooto-info-item .value-badge {
				padding: 2px 10px;
				border-radius: 12px;
				font-size: 12px;
				font-weight: 500;
			}
			
			@media (max-width: 991px) {
				.tooto-order-grid-top,
				.tooto-order-grid-bottom {
					grid-template-columns: 1fr;
				}
				.tooto-card.tooto-order-main-card{
					border: none;
				}
				.tooto-order-items-wrapper {
					padding-inline: 0;
				}
				.tooto-order-number {
					font-size: 20px;
					display: flex;
					flex-direction: column;
					margin: 0;
				}
				.tooto-order-totals {
					padding-top: 0;
				}
			}
		</style>
		<?php
	}

	/**
	 * 获取菜单图标
	 *
	 * @param string $endpoint 端点名称
	 * @return string 图标 HTML
	 */
	private function get_menu_icon( string $endpoint ): string {
		// 图标文件映射
		$icon_files = [
			'dashboard' => 'icon-dashboad.svg',
			'management' => 'icon-setting.svg',
			'downloads' => 'icon-download.svg',
		];

		// 如果端点有对应的图标文件，尝试读取
		if ( isset( $icon_files[ $endpoint ] ) && defined( 'TOOTO_EA_PATH' ) ) {
			$icon_path = TOOTO_EA_PATH . 'assets/images/' . $icon_files[ $endpoint ];
			if ( \file_exists( $icon_path ) ) {
				$icon_content = \file_get_contents( $icon_path );
				if ( $icon_content !== false ) {
					// 移除 SVG 的 width 和 height 属性，让 CSS 控制大小
					$icon_content = \preg_replace( '/\s+width="[^"]*"/i', '', $icon_content );
					$icon_content = \preg_replace( '/\s+height="[^"]*"/i', '', $icon_content );
					return $icon_content;
				}
			}
		}

		// 默认图标（用于 customer-logout 或其他未定义的端点）
		$default_icons = [
			'customer-logout' => '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 14H3C2.44772 14 2 13.5523 2 13V3C2 2.44772 2.44772 2 3 2H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10 11L14 8L10 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 8H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
		];

		if ( isset( $default_icons[ $endpoint ] ) ) {
			return $default_icons[ $endpoint ];
		}

		// 通用默认图标
		return '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="1.5" fill="none"/></svg>';
	}

	/**
	 * 在管理员后台添加商店信息字段
	 *
	 * @param WP_User $user 用户对象
	 */
	public function add_store_information_fields( $user ): void {
		// 获取保存的数据
		$store_name = \get_user_meta( $user->ID, 'tooto_store_name', true );
		$store_address = \get_user_meta( $user->ID, 'tooto_store_address', true );
		$tax_number = \get_user_meta( $user->ID, 'tooto_tax_number', true );
		$store_type = \get_user_meta( $user->ID, 'tooto_store_type', true );
		$store_website = \get_user_meta( $user->ID, 'tooto_store_website', true );
		$monthly_purchase_amount = \get_user_meta( $user->ID, 'tooto_monthly_purchase_amount', true );
		$profile_picture_id = \get_user_meta( $user->ID, 'tooto_profile_picture', true );
		$profile_picture_url = $profile_picture_id ? \wp_get_attachment_image_url( $profile_picture_id, 'thumbnail' ) : \get_avatar_url( $user->ID, [ 'size' => 150 ] );

		// 商店类型选项
		$store_type_options = [
			'' => __( 'Select Store Type', 'tooto-elementor' ),
			'retail' => __( 'Retail Store', 'tooto-elementor' ),
			'wholesale' => __( 'Wholesale', 'tooto-elementor' ),
			'online' => __( 'Online Store', 'tooto-elementor' ),
			'distributor' => __( 'Distributor', 'tooto-elementor' ),
			'other' => __( 'Other', 'tooto-elementor' ),
		];
		?>
		<h2><?php echo esc_html__( 'Store Information', 'tooto-elementor' ); ?></h2>
		<table class="form-table" id="tooto-store-information-fields">
			<tr>
				<th>
					<label for="tooto_profile_picture"><?php echo esc_html__( 'Profile Picture', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<div class="tooto-admin-profile-picture-wrapper">
						<?php $default_avatar = \get_avatar_url( $user->ID, [ 'size' => 150 ] ); ?>
						<img src="<?php echo esc_url( $profile_picture_url ); ?>" alt="<?php echo esc_attr__( 'Profile Picture', 'tooto-elementor' ); ?>" class="tooto-admin-profile-picture-preview" data-default-avatar="<?php echo esc_url( $default_avatar ); ?>" style="width: 120px; height: 120px; border-radius: 50%; object-fit: cover; border: 2px solid #ddd; margin-bottom: 10px; display: block;" />
						<input type="hidden" name="tooto_profile_picture" id="tooto_profile_picture" value="<?php echo esc_attr( $profile_picture_id ); ?>" />
						<button type="button" class="button tooto-upload-profile-picture"><?php echo esc_html__( 'Upload/Change Picture', 'tooto-elementor' ); ?></button>
						<button type="button" class="button tooto-remove-profile-picture" style="margin-left: 10px;<?php echo $profile_picture_id ? '' : ' display: none;'; ?>"><?php echo esc_html__( 'Remove Picture', 'tooto-elementor' ); ?></button>
					</div>
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_store_name"><?php echo esc_html__( 'Store name / Company name', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<input type="text" name="tooto_store_name" id="tooto_store_name" value="<?php echo esc_attr( $store_name ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_store_address"><?php echo esc_html__( 'Store address', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<textarea name="tooto_store_address" id="tooto_store_address" rows="3" class="large-text"><?php echo esc_textarea( $store_address ); ?></textarea>
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_tax_number"><?php echo esc_html__( 'Tax number', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<input type="text" name="tooto_tax_number" id="tooto_tax_number" value="<?php echo esc_attr( $tax_number ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_store_type"><?php echo esc_html__( 'Store type', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<select name="tooto_store_type" id="tooto_store_type" class="regular-text">
						<?php foreach ( $store_type_options as $value => $label ) : ?>
							<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $store_type, $value ); ?>>
								<?php echo esc_html( $label ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_store_website"><?php echo esc_html__( 'Website', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<input type="url" name="tooto_store_website" id="tooto_store_website" value="<?php echo esc_url( $store_website ); ?>" class="regular-text" placeholder="https://" />
				</td>
			</tr>
			<tr>
				<th>
					<label for="tooto_monthly_purchase_amount"><?php echo esc_html__( 'Estimated Monthly Purchase Amount', 'tooto-elementor' ); ?></label>
				</th>
				<td>
					<input type="text" name="tooto_monthly_purchase_amount" id="tooto_monthly_purchase_amount" value="<?php echo esc_attr( $monthly_purchase_amount ); ?>" class="regular-text" />
				</td>
			</tr>
		</table>
		<?php
	}

	/**
	 * 保存管理员后台的商店信息字段
	 *
	 * @param int $user_id 用户 ID
	 */
	public function save_store_information_fields( int $user_id ): void {
		// 检查权限
		if ( ! \current_user_can( 'edit_user', $user_id ) ) {
			return;
		}

		// 保存各个字段
		$fields = [
			'tooto_store_name' => \sanitize_text_field( $_POST['tooto_store_name'] ?? '' ),
			'tooto_store_address' => \sanitize_textarea_field( $_POST['tooto_store_address'] ?? '' ),
			'tooto_tax_number' => \sanitize_text_field( $_POST['tooto_tax_number'] ?? '' ),
			'tooto_store_type' => \sanitize_text_field( $_POST['tooto_store_type'] ?? '' ),
			'tooto_store_website' => \esc_url_raw( $_POST['tooto_store_website'] ?? '' ),
			'tooto_monthly_purchase_amount' => \sanitize_text_field( $_POST['tooto_monthly_purchase_amount'] ?? '' ),
		];

		foreach ( $fields as $key => $value ) {
			\update_user_meta( $user_id, $key, $value );
		}

		// 处理头像
		if ( isset( $_POST['tooto_profile_picture'] ) ) {
			$profile_picture_id = \intval( $_POST['tooto_profile_picture'] );
			if ( $profile_picture_id > 0 ) {
				\update_user_meta( $user_id, 'tooto_profile_picture', $profile_picture_id );
			} else {
				\delete_user_meta( $user_id, 'tooto_profile_picture' );
			}
		}
	}

	/**
	 * 在管理员后台加载资源文件
	 *
	 * @param string $hook 当前页面钩子
	 */
	public function enqueue_admin_assets( string $hook ): void {
		// 只在用户编辑页面加载
		if ( 'user-edit.php' !== $hook && 'profile.php' !== $hook ) {
			return;
		}

		// 加载样式
		if ( defined( 'TOOTO_EA_URL' ) ) {
			\wp_enqueue_style(
				'tooto-admin-store-information',
				TOOTO_EA_URL . 'assets/css/tooto-admin-store-information.css',
				[],
				TOOTO_EA_VERSION
			);
		}

		// 加载脚本（用于媒体上传器）
		\wp_enqueue_media();
		\wp_enqueue_script(
			'tooto-admin-store-information',
			TOOTO_EA_URL . 'assets/js/tooto-admin-store-information.js',
			[ 'jquery' ],
			TOOTO_EA_VERSION,
			true
		);
	}

	/**
	 * 注册和加载资源文件
	 */
	public function enqueue_assets(): void {
		// 只在 my-account 页面加载
		if ( ! \is_account_page() ) {
			return;
		}

		// 获取主题样式句柄，确保我们的样式在主题之后加载
		$theme_style_handle = 'blocksy-style';
		if ( ! wp_style_is( $theme_style_handle, 'enqueued' ) ) {
			// 如果没有找到 blocksy 样式，尝试其他可能的句柄
			global $wp_styles;
			$theme_style_handle = '';
			foreach ( $wp_styles->queue as $handle ) {
				if ( strpos( $handle, 'blocksy' ) !== false || strpos( $handle, 'theme' ) !== false ) {
					$theme_style_handle = $handle;
					break;
				}
			}
		}

		// 注册样式，依赖主题样式以确保加载顺序
		$dependencies = [];
		if ( ! empty( $theme_style_handle ) && wp_style_is( $theme_style_handle, 'registered' ) ) {
			$dependencies[] = $theme_style_handle;
		}

		wp_register_style(
			'tooto-woocommerce-myaccount',
			TOOTO_EA_URL . 'assets/css/tooto-woocommerce-myaccount.css',
			$dependencies,
			TOOTO_EA_VERSION
		);

		// 注册脚本
		wp_register_script(
			'tooto-woocommerce-myaccount',
			TOOTO_EA_URL . 'assets/js/tooto-woocommerce-myaccount.js',
			[ 'jquery' ],
			TOOTO_EA_VERSION,
			true
		);

		// 加载样式和脚本，使用高优先级确保最后加载
		wp_enqueue_style( 'tooto-woocommerce-myaccount' );
		wp_enqueue_script( 'tooto-woocommerce-myaccount' );

		// 添加内联样式作为备用方案，确保样式能够覆盖主题
		$this->add_inline_styles();
		
		// 同时在页面头部直接输出样式，确保最高优先级
		add_action( 'wp_head', [ $this, 'output_head_styles' ], 999 );
	}

	/**
	 * 加载 Checkout 页面资源
	 */
	public function enqueue_checkout_assets(): void {
		if ( ! \is_checkout() ) {
			return;
		}

		if ( defined( 'TOOTO_EA_URL' ) ) {
			wp_enqueue_script(
				'tooto-checkout-lock',
				TOOTO_EA_URL . 'assets/js/tooto-checkout-lock.js',
				[ 'jquery' ],
				TOOTO_EA_VERSION,
				true
			);

			// 传递参数
			$is_locked = true;
			
			// 1. 管理员不锁定
			if ( current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) {
				$is_locked = false;
			}
			
			// 2. 如果用户没有保存的配送地址，不锁定 (允许首次填写)
			$user_id = get_current_user_id();
			if ( $user_id ) {
				$customer = new \WC_Customer( $user_id );
				if ( empty( $customer->get_shipping_address_1() ) ) {
					$is_locked = false;
				}
			} else {
				// 未登录用户不锁定
				$is_locked = false;
			}

			wp_localize_script( 'tooto-checkout-lock', 'tooto_checkout_params', [
				'is_address_locked' => $is_locked,
			] );
		}
	}

	/**
	 * 输出 Checkout 页面自定义样式
	 * 用于隐藏 Billing 区域和 Ship to different address 开关
	 */
	public function output_checkout_styles(): void {
		if ( ! \is_checkout() ) {
			return;
		}

		// 检查权限，管理员可能需要看到所有内容
		if ( current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) {
			return;
		}

		?>
		<style type="text/css" id="tooto-checkout-custom-styles">
			/* 隐藏 "Ship to a different address" 标题和复选框容器 */
			#ship-to-different-address {
				display: none !important;
			}
			
			/* 强制显示配送地址区域 */
			.shipping_address {
				display: block !important;
			}

			/* 调整布局：Billing 在 Shipping 下方 */
			#customer_details {
				display: flex;
				flex-direction: column;
			}
			
			/* Shipping (col-2) 在上 */
			#customer_details .col-2 {
				order: 1;
				width: 100%;
				float: none;
				max-width: 100%;
			}

			/* Billing (col-1) 在下 */
			#customer_details .col-1 {
				order: 2;
				width: 100%;
				float: none;
				max-width: 100%;
				margin-top: 30px; /* 添加一些间距 */
			}
		</style>
		<?php
	}

	/**
	 * 添加内联样式，确保能够覆盖主题样式
	 */
	private function add_inline_styles(): void {
		$custom_css = "
		/* Tooto My Account 自定义样式 - 内联样式确保优先级 */
		.tooto-my-account-page .ct-acount-nav {
			/* 可以在这里添加需要高优先级的样式 */
		}
		";

		wp_add_inline_style( 'tooto-woocommerce-myaccount', $custom_css );
	}

	/**
	 * 在页面头部直接输出样式
	 * 使用最高优先级确保能够覆盖主题样式
	 */
	public function output_head_styles(): void {
		if ( ! \is_account_page() ) {
			return;
		}

		?>
		<style type="text/css" id="tooto-myaccount-custom-styles">
		.tooto-profile-picture-container {
			position: relative;
			width: 80px;
			height: 80px;
			border-radius: 50%;
			overflow: hidden;
			cursor: pointer;
		}
		.tooto-profile-picture-overlay {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			justify-content: center;
			opacity: 0;
			transition: opacity 0.3s;
		}
		.tooto-profile-picture-container:hover .tooto-profile-picture-overlay {
			opacity: 1;
		}
		.tooto-profile-picture-preview {
			width: 100%;
			height: 100%;
			object-fit: cover;
			display: block;
		}
		.tooto-profile-picture-input {
			display: none;
		}
		@media (max-width: 768px) {
			.tooto-profile-picture-container {
				width: 66px;
				height: 66px;
			}
		}
		</style>
		<?php
	}

	/**
	 * 调试：输出加载状态信息
	 */
	public function debug_info(): void {
		if ( ! \is_account_page() || ! \current_user_can( 'manage_options' ) ) {
			return;
		}

		$info = [
			'class_loaded' => class_exists( __CLASS__ ),
			'css_enqueued' => wp_style_is( 'tooto-woocommerce-myaccount', 'enqueued' ),
			'js_enqueued' => wp_script_is( 'tooto-woocommerce-myaccount', 'enqueued' ),
			'body_class' => in_array( 'tooto-my-account-page', get_body_class(), true ),
		];

		echo '<!-- Tooto My Account Debug Info: ' . esc_html( wp_json_encode( $info ) ) . ' -->' . "\n";
	}

	/**
	 * 添加自定义 body 类
	 *
	 * @param array $classes 现有的 body 类
	 * @return array 修改后的 body 类
	 */
	public function add_body_classes( array $classes ): array {
		if ( \is_account_page() ) {
			$classes[] = 'tooto-my-account-page';
		}

		return $classes;
	}

	/**
	 * 在 my-account 页面禁用页脚渲染
	 *
	 * @param bool $enabled 页脚是否启用
	 * @return bool 修改后的状态
	 */
	public function disable_footer_on_account_page( bool $enabled ): bool {
		if ( \is_account_page() ) {
			return false;
		}

		return $enabled;
	}

	/**
	 * 添加重写端点
	 */
	public function add_rewrite_endpoints(): void {
		$endpoints = [ 'store-information', 'delivery-address', 'invoice-information' ];
		$mask = \EP_PAGES;

		foreach ( $endpoints as $endpoint ) {
			\add_rewrite_endpoint( $endpoint, $mask );
		}
	}

	/**
	 * 添加查询变量到 WordPress
	 *
	 * @param array $vars 查询变量数组
	 * @return array 修改后的查询变量数组
	 */
	public function add_query_vars( array $vars ): array {
		$vars[] = 'store-information';
		$vars[] = 'delivery-address';
		$vars[] = 'invoice-information';
		return $vars;
	}

	/**
	 * 添加自定义查询变量到 WooCommerce
	 *
	 * @param array $vars 查询变量数组
	 * @return array 修改后的查询变量数组
	 */
	public function add_custom_query_vars( array $vars ): array {
		$vars['store-information'] = 'store-information';
		$vars['delivery-address'] = 'delivery-address';
		$vars['invoice-information'] = 'invoice-information';
		return $vars;
	}

	/**
	 * 处理 Store Information 表单提交
	 */
	public function handle_store_information_submit(): void {
		if ( ! \is_account_page() || ! isset( $_POST['tooto_store_information_nonce'] ) ) {
			return;
		}

		// 验证 nonce
		if ( ! \wp_verify_nonce( $_POST['tooto_store_information_nonce'], 'tooto_store_information_save' ) ) {
			\wc_add_notice( __( 'Security check failed. Please try again.', 'tooto-elementor' ), 'error' );
			return;
		}

		// 检查用户权限
		if ( ! \is_user_logged_in() ) {
			\wc_add_notice( __( 'You must be logged in to save store information.', 'tooto-elementor' ), 'error' );
			return;
		}

		$user_id = \get_current_user_id();
		$updated = false;

		// 保存各个字段
		$fields = [
			'store_name' => \sanitize_text_field( $_POST['store_name'] ?? '' ),
			'store_address' => \sanitize_textarea_field( $_POST['store_address'] ?? '' ),
			'tax_number' => \sanitize_text_field( $_POST['tax_number'] ?? '' ),
			'store_type' => \sanitize_text_field( $_POST['store_type'] ?? '' ),
			'store_website' => \esc_url_raw( $_POST['store_website'] ?? '' ),
			'monthly_purchase_amount' => \sanitize_text_field( $_POST['monthly_purchase_amount'] ?? '' ),
		];

		foreach ( $fields as $key => $value ) {
			$meta_key = 'tooto_' . $key;
			if ( \update_user_meta( $user_id, $meta_key, $value ) ) {
				$updated = true;
			}
		}

		// 处理头像上传
		if ( ! empty( $_FILES['profile_picture']['name'] ) ) {
			require_once( \ABSPATH . 'wp-admin/includes/file.php' );
			require_once( \ABSPATH . 'wp-admin/includes/media.php' );
			require_once( \ABSPATH . 'wp-admin/includes/image.php' );

			$upload = \wp_handle_upload( $_FILES['profile_picture'], [ 'test_form' => false ] );
			if ( ! isset( $upload['error'] ) ) {
				$attachment_id = \wp_insert_attachment(
					[
						'post_mime_type' => $upload['type'],
						'post_title' => \preg_replace( '/\.[^.]+$/', '', \basename( $upload['file'] ) ),
						'post_content' => '',
						'post_status' => 'inherit',
					],
					$upload['file']
				);

				if ( ! \is_wp_error( $attachment_id ) ) {
					\wp_generate_attachment_metadata( $attachment_id, $upload['file'] );
					\update_user_meta( $user_id, 'tooto_profile_picture', $attachment_id );
					$updated = true;
				}
			}
		}

		if ( $updated ) {
			\wc_add_notice( __( 'Store information updated successfully.', 'tooto-elementor' ), 'success' );
		}

		// 重定向到同一页面，避免重复提交
		\wp_safe_redirect( \wc_get_endpoint_url( 'store-information', '', \wc_get_page_permalink( 'myaccount' ) ) );
		exit;
	}

	/**
	 * 渲染 Management 子菜单的 Tab 导航
	 */
	private function render_management_tabs(): void {
		$tabs = [
			'store-information' => __( 'Store Information', 'tooto-elementor' ),
			'delivery-address' => __( 'Delivery Address', 'tooto-elementor' ),
			'invoice-information' => __( 'Invoice Information', 'tooto-elementor' ),
		];

		// 获取当前端点
		global $wp_query;
		$current_tab = '';
		foreach ( array_keys( $tabs ) as $slug ) {
			if ( isset( $wp_query->query_vars[ $slug ] ) ) {
				$current_tab = $slug;
				break;
			}
		}

		?>
		<div class="tooto-management-tabs">
			<?php foreach ( $tabs as $slug => $label ) : ?>
				<a href="<?php echo esc_url( \wc_get_endpoint_url( $slug, '', \wc_get_page_permalink( 'myaccount' ) ) ); ?>" class="tooto-management-tab <?php echo ( $current_tab === $slug ) ? 'active' : ''; ?>">
					<?php echo esc_html( $label ); ?>
				</a>
			<?php endforeach; ?>
		</div>
		<?php
	}

	/**
	 * Store Information 端点内容 - 显示和编辑商店信息
	 */
	public function store_information_endpoint(): void {
		$this->render_management_tabs();
		$current_user = \wp_get_current_user();
		$user_id = $current_user->ID;

		// 获取保存的数据
		$store_name = \get_user_meta( $user_id, 'tooto_store_name', true );
		$store_address = \get_user_meta( $user_id, 'tooto_store_address', true );
		$tax_number = \get_user_meta( $user_id, 'tooto_tax_number', true );
		$store_type = \get_user_meta( $user_id, 'tooto_store_type', true );
		$store_website = \get_user_meta( $user_id, 'tooto_store_website', true );
		$monthly_purchase_amount = \get_user_meta( $user_id, 'tooto_monthly_purchase_amount', true );
		$profile_picture_id = \get_user_meta( $user_id, 'tooto_profile_picture', true );
		$profile_picture_url = $profile_picture_id ? \wp_get_attachment_image_url( $profile_picture_id, 'thumbnail' ) : \get_avatar_url( $user_id, [ 'size' => 150 ] );

		// 商店类型选项
		$store_type_options = [
			'' => __( 'Select Store Type', 'tooto-elementor' ),
			'retail' => __( 'Retail Store', 'tooto-elementor' ),
			'wholesale' => __( 'Wholesale', 'tooto-elementor' ),
			'online' => __( 'Online Store', 'tooto-elementor' ),
			'distributor' => __( 'Distributor', 'tooto-elementor' ),
			'other' => __( 'Other', 'tooto-elementor' ),
		];
		// 获取上传的文件 ID
		$application_form_id = get_user_meta( $user_id, 'tooto_application_form', true );
		$reseller_certificate_id = get_user_meta( $user_id, 'tooto_reseller_certificate', true );

		// 获取文件 URL
		$application_form_url = $application_form_id ? wp_get_attachment_url( $application_form_id ) : '#';
		$reseller_certificate_url = $reseller_certificate_id ? wp_get_attachment_url( $reseller_certificate_id ) : '#';

		// 准备 Application Document 数据
		$application_documents = [
			[
				'name' => __( 'Application Form', 'tooto-elementor' ),
				'url' => $application_form_url,
				'type' => 'application_form',
				'has_file' => ! empty( $application_form_id ),
			],
			[
				'name' => __( 'Reseller Certificate', 'tooto-elementor' ),
				'url' => $reseller_certificate_url,
				'type' => 'reseller_certificate',
				'has_file' => ! empty( $reseller_certificate_id ),
			]
		];
		?>
		<div class="tooto-endpoint-content tooto-store-information">
			
			<div class="tooto-store-information-wrapper">
				<!-- 左侧：表单 -->
				<div class="tooto-store-information-form-wrapper">
					<form method="post" enctype="multipart/form-data" class="tooto-store-information-form">
						<?php \wp_nonce_field( 'tooto_store_information_save', 'tooto_store_information_nonce' ); ?>
						
						<div class="tooto-form-fields">
							<!-- Profile Picture -->
							<div class="tooto-form-field tooto-profile-picture-field">
								<label><?php echo esc_html__( 'Profile Picture', 'tooto-elementor' ); ?></label>
								<div class="tooto-profile-picture-wrapper">
									<div class="tooto-profile-picture-container">
										<img src="<?php echo esc_url( $profile_picture_url ); ?>" alt="<?php echo esc_attr__( 'Profile Picture', 'tooto-elementor' ); ?>" class="tooto-profile-picture-preview" />
										<div class="tooto-profile-picture-overlay">
											<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
												<path d="M12 20H5C4.44772 20 4 19.5523 4 19V5C4 4.44772 4.44772 4 5 4H19C19.5523 4 20 4.44772 20 5V12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M13.5 10.5L16.5 13.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M16 8L20 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M8 16L12 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M21 21H16V16H21V21Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M18.5 18.5H18.51" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											</svg>
										</div>
									</div>
									<input type="file" name="profile_picture" id="profile_picture" accept="image/*" class="tooto-profile-picture-input" />
								</div>
							</div>

							<!-- Store name / Company name -->
							<div class="tooto-form-field">
								<label for="store_name"><?php echo esc_html__( 'Store name / Company name', 'tooto-elementor' ); ?></label>
								<input type="text" id="store_name" name="store_name" value="<?php echo esc_attr( $store_name ); ?>" class="input-text" />
							</div>

							<!-- Store address -->
							<div class="tooto-form-field">
								<label for="store_address"><?php echo esc_html__( 'Store address', 'tooto-elementor' ); ?></label>
								<input type="text" id="store_address" name="store_address" class="input-text" value="<?php echo esc_attr( $store_address ); ?>" />
							</div>

							<!-- Tax number -->
							<div class="tooto-form-field">
								<label for="tax_number"><?php echo esc_html__( 'Tax number', 'tooto-elementor' ); ?></label>
								<input type="text" id="tax_number" name="tax_number" value="<?php echo esc_attr( $tax_number ); ?>" class="input-text" />
							</div>

							<!-- Store type -->
							<div class="tooto-form-field">
								<label for="store_type"><?php echo esc_html__( 'Store type', 'tooto-elementor' ); ?></label>
								<!-- 隐藏的原始 select，用于表单提交 -->
								<select id="store_type" name="store_type" class="tooto-select-hidden" style="display: none;">
									<?php foreach ( $store_type_options as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $store_type, $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<!-- 自定义下拉选择器 -->
								<div class="tooto-custom-select" data-target="store_type">
									<div class="tooto-custom-select-trigger">
										<span class="tooto-custom-select-value">
											<?php 
											$selected_label = $store_type && isset( $store_type_options[ $store_type ] ) 
												? $store_type_options[ $store_type ] 
												: $store_type_options[''];
											echo esc_html( $selected_label ); 
											?>
										</span>
										<svg class="tooto-custom-select-arrow" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
											<path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
									</div>
									<ul class="tooto-custom-select-options">
										<?php foreach ( $store_type_options as $value => $label ) : ?>
											<li class="tooto-custom-select-option <?php echo ( $store_type === $value ) ? 'selected' : ''; ?>" data-value="<?php echo esc_attr( $value ); ?>">
												<?php echo esc_html( $label ); ?>
											</li>
										<?php endforeach; ?>
									</ul>
								</div>
							</div>

							<!-- Website -->
							<div class="tooto-form-field">
								<label for="store_website"><?php echo esc_html__( 'Website', 'tooto-elementor' ); ?></label>
								<input type="url" id="store_website" name="store_website" value="<?php echo esc_url( $store_website ); ?>" class="input-text" placeholder="https://" />
							</div>

							<!-- Estimated Monthly Purchase Amount -->
							<div class="tooto-form-field">
								<label for="monthly_purchase_amount"><?php echo esc_html__( 'Estimated Monthly Purchase Amount', 'tooto-elementor' ); ?></label>
								<input type="text" id="monthly_purchase_amount" name="monthly_purchase_amount" value="<?php echo esc_attr( $monthly_purchase_amount ); ?>" class="input-text" />
							</div>
						</div>

						<p class="form-row">
							<button type="submit" name="update_store_information" class="button tooto-update-button">
								<?php echo esc_html__( 'Update', 'tooto-elementor' ); ?>
							</button>
						</p>
					</form>
				</div>

				<!-- 右侧：Application Document -->
				<div class="tooto-application-document-wrapper">
					<h3 class="tooto-application-document-title"><?php echo esc_html__( 'Application Document', 'tooto-elementor' ); ?></h3>
					<ul class="tooto-application-document-list">
						<?php foreach ( $application_documents as $index => $document ) : ?>
							<li class="tooto-application-document-item">
								<span class="tooto-document-name"><?php echo esc_html( $document['name'] ); ?></span>
								<?php if ( ! empty( $document['has_file'] ) ) : ?>
									<a href="<?php echo esc_url( $document['url'] ); ?>" class="tooto-document-view-link" target="_blank">
										<?php echo esc_html__( 'View', 'tooto-elementor' ); ?>
									</a>
								<?php else : ?>
									<span class="tooto-document-no-file" style="color: #999; font-size: 14px;"><?php echo esc_html__( 'Not Uploaded', 'tooto-elementor' ); ?></span>
								<?php endif; ?>
							</li>
						<?php endforeach; ?>
					</ul>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Delivery Address 端点内容 - 显示收货地址
	 */
	public function delivery_address_endpoint(): void {
		$this->render_management_tabs();
		$customer = \WC()->customer;
		
		// 获取元数据
		$address_type = $customer->get_meta( 'shipping_address_type' );
		$phone = $customer->get_shipping_phone(); // WooCommerce 5.6+ 支持 shipping_phone
		
		// 处理 Address Type 显示文本
		$address_type_label = '-';
		if ( $address_type === 'residential' ) {
			$address_type_label = __( 'Residential Address', 'tooto-elementor' );
		} elseif ( $address_type === 'commercial' ) {
			$address_type_label = __( 'Commercial Address', 'tooto-elementor' );
		}
		
		// 获取完整的 Full Name
		$full_name = trim( $customer->get_shipping_first_name() . ' ' . $customer->get_shipping_last_name() );
		?>
		<div class="tooto-endpoint-content tooto-delivery-address">
			<div class="woocommerce-address-fields">
				<div class="woocommerce-address-fields__field-wrapper">
					<!-- Row 1: Full Name | Phone Number -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Full Name', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $full_name ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Phone Number', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $phone ?: '-' ); ?></strong>
					</p>

					<!-- Row 2: Country/Region | State/Province -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Country / Region', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_shipping_country() ? \WC()->countries->countries[ $customer->get_shipping_country() ] : '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'State / Province', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_shipping_state() ?: '-' ); ?></strong>
					</p>

					<!-- Row 3: Town/City | Street Address -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Town / City', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_shipping_city() ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Street Address', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_shipping_address_1() ?: '-' ); ?></strong>
					</p>

					<!-- Row 4: ZIP/Postal Code | Address Type -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Postcode / ZIP', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_shipping_postcode() ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Address Type', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $address_type_label ); ?></strong>
					</p>
				</div>
			</div>
			
			<?php 
			// Check if shipping address is already set
			$has_shipping_address = ! empty( $customer->get_shipping_address_1() );
			
			// Show update button only if address is not set or user is admin
			if ( ! $has_shipping_address || current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) : 
			?>
				<div class="tooto-address-actions" style="margin-top: 20px;">
					<a href="<?php echo esc_url( wc_get_endpoint_url( 'edit-address', 'shipping' ) ); ?>" class="button tooto-update-button">
						<?php echo esc_html__( 'Update', 'tooto-elementor' ); ?>
					</a>
				</div>
			<?php endif; ?>
			
			<?php 
			if ( $has_shipping_address && ! ( current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) ) : 
			?>
				<p class="tooto-address-hint">
					<?php echo esc_html__( '*To update your address, please contact the administrator.', 'tooto-elementor' ); ?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * 限制 Checkout 页面地址字段修改
	 */
	public function restrict_checkout_address_fields( $fields ) {
		// 管理员不限制
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return $fields;
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return $fields;
		}

		$customer = new \WC_Customer( $user_id );
		
		// 如果已设置收货地址（以 shipping_address_1 为准）
		if ( ! empty( $customer->get_shipping_address_1() ) ) {
			// 锁定所有 shipping 字段
			if ( isset( $fields['shipping'] ) ) {
				foreach ( $fields['shipping'] as $key => $field ) {
					$fields['shipping'][ $key ]['custom_attributes']['readonly'] = 'readonly';
					$fields['shipping'][ $key ]['class'][] = 'address-locked';
					
					// 移除必填标记，视觉上更友好（可选，但通常保留好点）
					// $fields['shipping'][ $key ]['required'] = false; 
				}
			}
		}

		return $fields;
	}

	/**
	 * 如果已有地址，强制展开并选中“配送到不同的地址”
	 */
	public function force_ship_to_different_address( $checked ) {
		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return $checked;
		}

		$customer = new \WC_Customer( $user_id );
		if ( ! empty( $customer->get_shipping_address_1() ) ) {
			return true;
		}

		return $checked;
	}

	/**
	 * 防止直接访问地址编辑页面
	 */
	public function prevent_address_editing() {
		// 仅在我的账户页面生效
		if ( ! is_account_page() ) {
			return;
		}

		// 如果是管理员，不限制
		if ( current_user_can( 'manage_options' ) || current_user_can( 'edit_users' ) ) {
			return;
		}

		global $wp;

		// 检查是否访问了 edit-address 端点
		if ( isset( $wp->query_vars['edit-address'] ) ) {
			$edit_type = $wp->query_vars['edit-address'];
			
			// 如果尝试编辑 shipping 地址，或者不带参数（默认列表页也包含编辑链接，虽然后者通常只是列表）
			// 但这里主要拦截具体的编辑动作 'shipping'
			if ( 'shipping' === $edit_type ) {
				$user_id = get_current_user_id();
				$customer = new \WC_Customer( $user_id );

				// 如果已存在地址，则拦截
				if ( ! empty( $customer->get_shipping_address_1() ) ) {
					// 重定向回自定义的 delivery-address 页面或 My Account 首页
					// 这里假设使用你的 delivery-address 端点
					$redirect_url = wc_get_account_endpoint_url( 'delivery-address' );
					if ( ! $redirect_url ) {
						$redirect_url = wc_get_account_endpoint_url( 'dashboard' );
					}
					
					wp_safe_redirect( $redirect_url );
					exit;
				}
			}
		}
	}

	/**
	 * 地址编辑表单前输出容器开始标签
	 */
	public function before_edit_address_form() {
		$load_address = get_query_var( 'edit-address' );
		$class = 'tooto-edit-address-wrapper';
		if ( ! empty( $load_address ) ) {
			$class .= ' tooto-edit-address-' . esc_attr( $load_address );
		}
		echo '<div class="' . $class . '">';
	}

	/**
	 * 地址编辑表单后输出容器结束标签
	 */
	public function after_edit_address_form() {
		echo '</div>';
	}

	/**
	 * Invoice Information 端点内容 - 显示发票地址
	 */
	public function invoice_information_endpoint(): void {
		$this->render_management_tabs();
		$customer = \WC()->customer;
		
		// 获取自定义字段数据
		$tax_id = $customer->get_meta( 'billing_tax_id' ) ?: $customer->get_meta( 'vat_number' ); // 兼容旧数据
		$billing_city = $customer->get_billing_city();
		$billing_postcode = $customer->get_billing_postcode();
		$billing_country_code = $customer->get_billing_country();
		$billing_state_code = $customer->get_billing_state();
		$billing_country_name = isset( \WC()->countries->countries[ $billing_country_code ] ) ? \WC()->countries->countries[ $billing_country_code ] : $billing_country_code;
		$states = \WC()->countries->get_states( $billing_country_code );
		$billing_state_name = ( is_array( $states ) && isset( $states[ $billing_state_code ] ) ) ? $states[ $billing_state_code ] : $billing_state_code;
		
		?>
		<div class="tooto-endpoint-content tooto-invoice-information">
			<div class="woocommerce-address-fields">
				<div class="woocommerce-address-fields__field-wrapper">
					<!-- Row 1: Legal Company Name | Tax ID / EIN -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Legal Company Name', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_billing_company() ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Tax ID / EIN', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $tax_id ?: '-' ); ?></strong>
					</p>

					<!-- Row 2: Country / Region | Town / City -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Country / Region', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $billing_country_name ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Town / City', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $billing_city ?: '-' ); ?></strong>
					</p>

					<!-- Row 3: State / County | Postcode / ZIP -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'State / County', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $billing_state_name ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Postcode / ZIP', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $billing_postcode ?: '-' ); ?></strong>
					</p>

					<!-- Row 4: Business Address | (empty) -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Business Address', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_billing_address_1() ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Phone', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_billing_phone() ?: '-' ); ?></strong>
					</p>
					<!-- Row 5: Contact Person | Email -->
					<p class="form-row form-row-first">
						<label><?php echo esc_html__( 'Contact Person', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_billing_first_name() ?: '-' ); ?></strong>
					</p>
					<p class="form-row form-row-last">
						<label><?php echo esc_html__( 'Email', 'tooto-elementor' ); ?></label>
						<strong><?php echo esc_html( $customer->get_billing_email() ?: '-' ); ?></strong>
					</p>
				</div>
			</div>
			
			<div class="tooto-address-actions" style="margin-top: 20px;">
				<a href="<?php echo esc_url( wc_get_endpoint_url( 'edit-address', 'billing' ) ); ?>" class="button tooto-update-button">
					<?php echo esc_html__( 'Update', 'tooto-elementor' ); ?>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * 添加自定义端点
	 * 
	 * 使用示例：
	 * $this->add_custom_endpoint( 'my-custom-page', __( '我的自定义页面', 'tooto-elementor' ) );
	 *
	 * @param string $endpoint 端点 slug
	 * @param string $label 菜单标签
	 * @param int    $position 菜单位置（可选）
	 */
	public function add_custom_endpoint( string $endpoint, string $label, int $position = null ): void {
		// 添加查询变量
		add_filter( 'woocommerce_get_query_vars', function( $vars ) use ( $endpoint ) {
			$vars[ $endpoint ] = $endpoint;
			return $vars;
		} );

		// 添加菜单项 - 使用高优先级
		add_filter( 'woocommerce_account_menu_items', function( $items ) use ( $endpoint, $label, $position ) {
			if ( null !== $position ) {
				$items = array_slice( $items, 0, $position, true ) +
				         [ $endpoint => $label ] +
				         array_slice( $items, $position, null, true );
			} else {
				$items[ $endpoint ] = $label;
			}
			return $items;
		}, 999 );

		// 注册端点内容
		add_action( 'woocommerce_account_' . $endpoint . '_endpoint', function() use ( $endpoint ) {
			// 可以在这里加载自定义模板或输出内容
			// 例如：require_once TOOTO_EA_PATH . 'templates/myaccount/' . $endpoint . '.php';
			echo '<div class="tooto-custom-endpoint-' . esc_attr( $endpoint ) . '">';
			echo '<p>' . esc_html__( '这是自定义端点内容', 'tooto-elementor' ) . '</p>';
			echo '</div>';
		} );
	}

	/**
	 * 添加 WooCommerce 账户设置
	 *
	 * @param array $settings 设置数组
	 * @return array 修改后的设置数组
	 */
	public function add_account_settings( array $settings ): array {
		$settings[] = [
			'title' => __( 'My Account Recommendations', 'tooto-elementor' ),
			'type'  => 'title',
			'desc'  => '',
			'id'    => 'tooto_myaccount_recommend_options',
		];
		
		$settings[] = [
			'title'    => __( 'Recommend Product IDs', 'tooto-elementor' ),
			'desc'     => __( 'Enter product IDs separated by comma (e.g. 123, 456). These products will be displayed at the bottom of My Account content.', 'tooto-elementor' ),
			'id'       => 'tooto_myaccount_recommend_ids',
			'type'     => 'text',
			'default'  => '',
			'desc_tip' => true,
		];
		
		$settings[] = [
			'type' => 'sectionend',
			'id'   => 'tooto_myaccount_recommend_options',
		];

		// Registration Form Settings
		$settings[] = [
			'title' => __( 'Registration Form Settings', 'tooto-elementor' ),
			'type'  => 'title',
			'desc'  => '',
			'id'    => 'tooto_registration_form_options',
		];
		
		$settings[] = [
			'title'    => __( 'Application Form Example URL', 'tooto-elementor' ),
			'desc'     => __( 'Enter the URL for the Application Form example file (e.g. PDF). Users can download this file from the registration modal.', 'tooto-elementor' ),
			'id'       => 'tooto_application_form_example_url',
			'type'     => 'text',
			'default'  => '',
			'desc_tip' => true,
		];
		
		$settings[] = [
			'type' => 'sectionend',
			'id'   => 'tooto_registration_form_options',
		];
		
		return $settings;
	}

	/**
	 * 渲染推荐产品
	 */
	public function render_recommend_products(): void {
		$product_ids_str = \get_option( 'tooto_myaccount_recommend_ids', '' );
		$is_admin = \current_user_can( 'manage_options' );
		$settings_url = \admin_url( 'admin.php?page=wc-settings&tab=account' );

		if ( empty( $product_ids_str ) ) {
			if ( $is_admin ) {
				?>
				<div class="tooto-recommend-products tooto-admin-notice">
					<h3 class="tooto-recommend-title">
						<?php esc_html_e( 'Recommend Products', 'tooto-elementor' ); ?>
						<span class="tooto-admin-badge"><?php esc_html_e( 'Admin Only', 'tooto-elementor' ); ?></span>
					</h3>
					<p>
						<?php esc_html_e( 'No products configured yet. Please go to WooCommerce Settings to add recommend product IDs.', 'tooto-elementor' ); ?>
					</p>
					<a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary" target="_blank">
						<?php esc_html_e( 'Configure Recommendations', 'tooto-elementor' ); ?>
					</a>
				</div>
				<style>
					.tooto-admin-notice {
						border: 1px dashed #ccc;
						padding: 20px;
						background: #f9f9f9;
						margin-top: 40px;
					}
					.tooto-admin-badge {
						background: #d63638;
						color: #fff;
						font-size: 10px;
						padding: 2px 6px;
						border-radius: 3px;
						vertical-align: middle;
						margin-left: 10px;
						font-weight: normal;
					}
				</style>
				<?php
			}
			return;
		}

		$product_ids = array_map( 'trim', explode( ',', $product_ids_str ) );
		$product_ids = array_filter( $product_ids, 'is_numeric' );
		
		if ( empty( $product_ids ) ) {
			return;
		}

		$args = [
			'post_type'      => 'product',
			'post__in'       => $product_ids,
			'posts_per_page' => 4,
			'orderby'        => 'post__in',
		];

		$query = new \WP_Query( $args );

		if ( $query->have_posts() ) {
			?>
			<div class="tooto-recommend-products">
				<h3 class="tooto-recommend-title">
					<?php esc_html_e( 'Recommend Products', 'tooto-elementor' ); ?>
					<?php if ( $is_admin ) : ?>
						<a href="<?php echo esc_url( $settings_url ); ?>" class="tooto-admin-edit-link" title="<?php esc_attr_e( 'Edit Recommendations', 'tooto-elementor' ); ?>" target="_blank">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
						</a>
					<?php endif; ?>
				</h3>
				<div class="tooto-recommend-grid">
					<?php while ( $query->have_posts() ) : $query->the_post(); global $product; ?>
						<div class="tooto-recommend-item">
							<div class="tooto-recommend-image">
								<?php echo $product->get_image( 'woocommerce_thumbnail' ); ?>
							</div>
							<h4 class="tooto-recommend-name">
								<?php the_title(); ?>
							</h4>
							<a href="<?php the_permalink(); ?>" class="tooto-recommend-link">
								<?php esc_html_e( 'View', 'tooto-elementor' ); ?>
							</a>
						</div>
					<?php endwhile; ?>
				</div>
			</div>
			<style>
				.tooto-recommend-products {
					margin-top: 18px;
					padding: 24px;
					border: 1px solid #EDEDED;
					border-radius: 8px 8px 0 0;
				}
				.tooto-recommend-products h3.tooto-recommend-title {
					font-size: 24px;
					font-weight: 600;
					margin-bottom: 16px;
					color: #000;
					display: flex;
					align-items: center;
				}
				.tooto-admin-edit-link {
					margin-left: 10px;
					opacity: 0.5;
					color: inherit;
					display: inline-flex;
				}
				.tooto-admin-edit-link:hover {
					opacity: 1;
					color: #007cba;
				}
				.tooto-recommend-grid {
					display: grid;
					grid-template-columns: repeat(4, 1fr);
					gap: 20px;
				}
				.tooto-recommend-item {
					display: flex;
					flex-direction: column;
				}
				.tooto-recommend-image {
					background-color: #FAFAFA;
					margin-bottom: 10px;
				}
				.tooto-recommend-image img {
					width: 100%;
					height: auto;
					border-radius: 8px;
					aspect-ratio: 1/1;
					object-fit: cover;
				}
				.tooto-recommend-name {
					font-size: 16px;
					font-weight: 500;
					margin: 0 0 12px;
					line-height: 1.4;
				}
				.tooto-recommend-link {
					font-size: 14px;
					color: #d83030;
					text-decoration: underline;
					margin-top: auto;
					text-underline-offset: 3px;
				}
				@media (max-width: 768px) {
					.tooto-recommend-grid {
						grid-template-columns: repeat(2, 1fr);
					}
					.tooto-recommend-products h3.tooto-recommend-title {
						font-size: 20px;
					}
					.tooto-recommend-products {
						padding: 0;
						border: none;
					}
				}
			</style>
			<?php
			\wp_reset_postdata();
		}
	}
}
