<?php
/**
 * Tooto Case Add to Cart 组件：支持按箱销售的添加到购物车功能
 */

namespace Tooto_Elementor\Widgets;

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

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Widget_Base;

class Case_Add_To_Cart extends Widget_Base {
	public function get_name(): string {
		return 'tooto-case-add-to-cart';
	}

	public function get_title(): string {
		return __( 'Case Add to Cart', 'tooto-elementor' );
	}

	public function get_icon(): string {
		return 'eicon-cart';
	}

	public function get_categories(): array {
		return [ 'tooto' ];
	}

	public function get_keywords(): array {
		return [ 'cart', 'add to cart', 'case', 'quantity', '购物车', '添加到购物车', '箱', 'tooto' ];
	}

	public function get_style_depends(): array {
		return [ 'tooto-elementor' ];
	}

	public function get_script_depends(): array {
		return [ 'tooto-elementor' ];
	}

	protected function register_controls(): void {
		// 内容部分
		$this->start_controls_section(
			'section_content',
			[
				'label' => __( '内容', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'units_per_case',
			[
				'label'       => __( '每箱单位数', 'tooto-elementor' ),
				'type'        => Controls_Manager::NUMBER,
				'default'     => 16,
				'min'         => 1,
				'step'        => 1,
				'description' => __( '每箱包含的单位数量。此组件会自动使用当前产品详情页的产品。', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'cart_quantity_rule',
			[
				'label'   => __( '购物车数量规则', 'tooto-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'total_units',
				'options' => [
					'total_units'   => __( '总单位数 (箱数 × 每箱单位数)', 'tooto-elementor' ),
					'case_quantity' => __( '仅箱数 (直接添加选择的数量)', 'tooto-elementor' ),
				],
				'description' => __( '如果您的 WooCommerce 产品是以“单个单位”定价但按箱出售，请选择“总单位数”。如果产品本身就是“一箱”，请选择“仅箱数”。', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'quantity_label',
			[
				'label'       => __( '数量标签', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'Quantity', 'tooto-elementor' ),
				'placeholder' => __( 'Quantity', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'case_label',
			[
				'label'       => __( '箱装说明', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'Case', 'tooto-elementor' ),
				'placeholder' => __( 'Case', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'units_label',
			[
				'label'       => __( '单位标签', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'units', 'tooto-elementor' ),
				'placeholder' => __( 'units', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'disclaimer_text',
			[
				'label'       => __( '说明文字', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXTAREA,
				'default'     => __( '*Sold by case. 1 case contains **{units}** units.', 'tooto-elementor' ),
				'placeholder' => __( '*Sold by case. 1 case contains **{units}** units.', 'tooto-elementor' ),
				'description' => __( '使用 {units} 作为单位数的占位符', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'button_text',
			[
				'label'       => __( '按钮文字', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'Add to cart', 'tooto-elementor' ),
				'placeholder' => __( 'Add to cart', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'out_of_stock_text',
			[
				'label'       => __( '缺货按钮文字', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'Out of stock', 'tooto-elementor' ),
				'placeholder' => __( 'Out of stock', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'login_button_text',
			[
				'label'       => __( '登录按钮文字', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'Please Login', 'tooto-elementor' ),
				'placeholder' => __( 'Please Login', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'show_more_details',
			[
				'label'        => __( '显示更多详情按钮', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( '显示', 'tooto-elementor' ),
				'label_off'    => __( '隐藏', 'tooto-elementor' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->add_control(
			'more_details_text',
			[
				'label'       => __( '更多详情文字', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( 'More Details &rarr;', 'tooto-elementor' ),
				'placeholder' => __( 'More Details &rarr;', 'tooto-elementor' ),
				'condition'   => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->end_controls_section();

		// 样式部分
		$this->start_controls_section(
			'section_style',
			[
				'label' => __( '样式', 'tooto-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		// 数量选择器样式
		$this->add_control(
			'quantity_selector_heading',
			[
				'label' => __( '数量选择器', 'tooto-elementor' ),
				'type'  => Controls_Manager::HEADING,
			]
		);

		$this->add_control(
			'quantity_selector_bg',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__quantity-selector' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'quantity_selector_border_color',
			[
				'label'     => __( '边框颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#e0e0e0',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__quantity-selector' => 'border-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'quantity_selector_border_radius',
			[
				'label'      => __( '圆角', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [
					'px' => [
						'min' => 0,
						'max' => 20,
					],
				],
				'default'    => [
					'size' => 4,
					'unit' => 'px',
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-case-add-to-cart__quantity-selector' => 'border-radius: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_control(
			'quantity_number_color',
			[
				'label'     => __( '数量文字颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#8B4513',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__quantity-input' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'quantity_button_color',
			[
				'label'     => __( '按钮颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#666666',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__quantity-btn' => 'color: {{VALUE}};',
				],
			]
		);

		// 按钮样式
		$this->add_control(
			'button_heading',
			[
				'label'     => __( '添加到购物车按钮', 'tooto-elementor' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			]
		);

		$this->add_control(
			'button_bg',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#C41E3A',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__button' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'button_text_color',
			[
				'label'     => __( '文字颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__button' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'button_border_radius',
			[
				'label'      => __( '圆角', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [
					'px' => [
						'min' => 0,
						'max' => 20,
					],
				],
				'default'    => [
					'size' => 4,
					'unit' => 'px',
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-case-add-to-cart__button' => 'border-radius: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'button_typography',
				'label'    => __( '按钮字体', 'tooto-elementor' ),
				'selector' => '{{WRAPPER}} .tooto-case-add-to-cart__button',
			]
		);

		// 更多详情按钮样式
		$this->add_control(
			'more_details_heading',
			[
				'label'     => __( '更多详情按钮', 'tooto-elementor' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->add_control(
			'more_details_color',
			[
				'label'     => __( '文字颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#C41E3A',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__more-details' => 'color: {{VALUE}};',
				],
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->add_control(
			'more_details_bg_color',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => 'transparent',
				'selectors' => [
					'{{WRAPPER}} .tooto-case-add-to-cart__more-details' => 'background-color: {{VALUE}};',
				],
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->add_group_control(
			\Elementor\Group_Control_Border::get_type(),
			[
				'name'      => 'more_details_border',
				'selector'  => '{{WRAPPER}} .tooto-case-add-to-cart__more-details',
				'condition' => [
					'show_more_details' => 'yes',
				],
				'fields_options' => [
					'border' => [
						'default' => 'solid',
					],
					'width'  => [
						'default' => [
							'top'    => 1,
							'right'  => 1,
							'bottom' => 1,
							'left'   => 1,
							'isLinked' => true,
						],
					],
					'color'  => [
						'default' => '#C41E3A',
					],
				],
			]
		);

		$this->add_control(
			'more_details_border_radius',
			[
				'label'      => __( '圆角', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [
					'px' => [
						'min' => 0,
						'max' => 20,
					],
				],
				'default'    => [
					'size' => 4,
					'unit' => 'px',
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-case-add-to-cart__more-details' => 'border-radius: {{SIZE}}{{UNIT}};',
				],
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'more_details_typography',
				'label'    => __( '字体', 'tooto-elementor' ),
				'selector' => '{{WRAPPER}} .tooto-case-add-to-cart__more-details',
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->add_control(
			'buttons_gap',
			[
				'label'      => __( '按钮间距', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range'      => [
					'px' => [
						'min' => 0,
						'max' => 50,
					],
				],
				'default'    => [
					'size' => 10,
					'unit' => 'px',
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-case-add-to-cart__actions' => 'gap: {{SIZE}}{{UNIT}};',
				],
				'condition' => [
					'show_more_details' => 'yes',
				],
			]
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();

		// 自动获取当前产品
		$product = null;
		$product_id = 0;

		// 方法1：从全局 $product 对象获取
		global $product;
		if ( isset( $product ) && $product && is_a( $product, 'WC_Product' ) ) {
			$product_id = $product->get_id();
		} else {
			// 方法2：从当前页面获取
			if ( is_product() ) {
				global $post;
				if ( $post ) {
					$product = wc_get_product( $post->ID );
					if ( $product ) {
						$product_id = $product->get_id();
					}
				}
			}
		}

		// 如果仍然没有产品，尝试从 URL 参数获取
		if ( ! $product && isset( $_GET['product_id'] ) ) {
			$product_id = absint( $_GET['product_id'] );
			$product = wc_get_product( $product_id );
		}

		if ( ! $product || ! $product_id ) {
			echo '<div class="tooto-case-add-to-cart__empty">' . esc_html__( '此组件只能在产品详情页使用', 'tooto-elementor' ) . '</div>';
			return;
		}

		// 检查产品是否可以购买
		if ( ! $product->is_purchasable() ) {
			echo '<div class="tooto-case-add-to-cart__empty">' . esc_html__( '该产品无法购买', 'tooto-elementor' ) . '</div>';
			return;
		}

		$is_in_stock = $product->is_in_stock();
		$is_user_logged_in = is_user_logged_in();

		$units_per_case = isset( $settings['units_per_case'] ) ? max( 1, (int) $settings['units_per_case'] ) : 16;
		$quantity_label = ! empty( $settings['quantity_label'] ) ? $settings['quantity_label'] : __( 'Quantity', 'tooto-elementor' );
		$case_label     = ! empty( $settings['case_label'] ) ? $settings['case_label'] : __( 'Case', 'tooto-elementor' );
		$units_label    = ! empty( $settings['units_label'] ) ? $settings['units_label'] : __( 'units', 'tooto-elementor' );
		$disclaimer     = ! empty( $settings['disclaimer_text'] ) ? $settings['disclaimer_text'] : __( '*Sold by case. 1 case contains **{units}** units.', 'tooto-elementor' );
		
		$button_text = ! empty( $settings['button_text'] ) ? $settings['button_text'] : __( 'Add to cart', 'tooto-elementor' );
		
		if ( ! $is_user_logged_in ) {
			$button_text = ! empty( $settings['login_button_text'] ) ? $settings['login_button_text'] : __( 'Please Login', 'tooto-elementor' );
		} elseif ( ! $is_in_stock ) {
			$button_text = ! empty( $settings['out_of_stock_text'] ) ? $settings['out_of_stock_text'] : __( 'Out of stock', 'tooto-elementor' );
		}

		// 替换占位符
		$disclaimer = str_replace( '{units}', $units_per_case, $disclaimer );
		// 处理 Markdown 格式的加粗
		$disclaimer = preg_replace( '/\*\*(.*?)\*\*/', '<strong>$1</strong>', $disclaimer );

		$cart_quantity_rule = ! empty( $settings['cart_quantity_rule'] ) ? $settings['cart_quantity_rule'] : 'total_units';

		?>
		<div class="tooto-case-add-to-cart" data-product-id="<?php echo esc_attr( $product_id ); ?>" data-units-per-case="<?php echo esc_attr( $units_per_case ); ?>" data-cart-quantity-rule="<?php echo esc_attr( $cart_quantity_rule ); ?>">
			<?php if ( ! empty( $quantity_label ) ) : ?>
				<div class="tooto-case-add-to-cart__quantity-label"><?php echo esc_html( $quantity_label ); ?></div>
			<?php endif; ?>
			
			<div class="tooto-case-add-to-cart__wrapper">
				<div class="tooto-case-add-to-cart__quantity-selector">
					<button type="button" class="tooto-case-add-to-cart__quantity-btn tooto-case-add-to-cart__quantity-btn--minus" aria-label="<?php esc_attr_e( '减少数量', 'tooto-elementor' ); ?>" <?php disabled( ! $is_in_stock ); ?>>-</button>
					<input type="number" class="tooto-case-add-to-cart__quantity-input" value="1" min="1" step="1" aria-label="<?php esc_attr_e( 'Quantity', 'tooto-elementor' ); ?>" <?php disabled( ! $is_in_stock ); ?>>
					<button type="button" class="tooto-case-add-to-cart__quantity-btn tooto-case-add-to-cart__quantity-btn--plus" aria-label="<?php esc_attr_e( '增加数量', 'tooto-elementor' ); ?>" <?php disabled( ! $is_in_stock ); ?>>+</button>
				</div>
				
				<div class="tooto-case-add-to-cart__case-info">
					<?php echo esc_html( $case_label ); ?> (<?php echo esc_html( $units_per_case ); ?> <?php echo esc_html( $units_label ); ?>)
				</div>
			</div>

			<?php if ( ! empty( $disclaimer ) ) : ?>
				<div class="tooto-case-add-to-cart__disclaimer"><?php echo wp_kses_post( $disclaimer ); ?></div>
			<?php endif; ?>

			<div class="tooto-case-add-to-cart__actions" style="display: flex; align-items: center; flex-wrap: wrap;">
				<button type="button" class="tooto-case-add-to-cart__button <?php echo ! $is_in_stock ? 'tooto-case-add-to-cart__button--disabled' : ''; ?>" data-product-id="<?php echo esc_attr( $product_id ); ?>" <?php disabled( ! $is_in_stock && $is_user_logged_in ); ?> <?php echo ! $is_user_logged_in ? 'data-login-required="yes"' : ''; ?>>
					<?php echo esc_html( $button_text ); ?>
				</button>

				<?php if ( 'yes' === $settings['show_more_details'] && $product ) : ?>
					<a href="<?php echo esc_url( $product->get_permalink() ); ?>" class="tooto-case-add-to-cart__more-details" style="text-decoration: none;border-width: 1px;border-style: solid;display: flex;justify-content: center; flex: 1;height: 46px;align-items: center;">
						<?php echo esc_html( $settings['more_details_text'] ); ?>
					</a>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}
}
