<?php
namespace Tooto_Elementor\Widgets;

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Plugin;

class Product_Content extends Widget_Base {

	public function get_name() {
		return 'tooto-product-content';
	}

	public function get_title() {
		return esc_html__( 'Tooto Product Content', 'tooto-elementor' );
	}

	public function get_icon() {
		return 'eicon-single-product';
	}

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

	protected function register_controls() {
		$this->start_controls_section(
			'section_content',
			[
				'label' => esc_html__( 'Settings', 'tooto-elementor' ),
			]
		);

		// Get latest 100 products for selection
		$products = get_posts( [
			'post_type' => 'product',
			'posts_per_page' => 100,
			'post_status' => 'publish',
			'fields' => 'ids',
		] );

		$product_options = [];
		if ( ! empty( $products ) ) {
			foreach ( $products as $pid ) {
				$title = get_the_title( $pid );
				$product_options[ $pid ] = $title . ' (ID: ' . $pid . ')';
			}
		}

		$this->add_control(
			'product_id',
			[
				'label' => esc_html__( 'Select Product', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT2,
				'options' => $product_options,
				'label_block' => true,
				'description' => esc_html__( 'Select the product whose data/content you want to display.', 'tooto-elementor' ),
			]
		);
		
		$this->add_control(
			'manual_product_id',
			[
				'label' => esc_html__( 'Or Enter Product ID Manually', 'tooto-elementor' ),
				'type' => Controls_Manager::TEXT,
				'placeholder' => '123',
				'condition' => [
					'product_id' => '',
				],
			]
		);

		$this->add_control(
			'source_type',
			[
				'label' => esc_html__( 'Content Source', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'template' => esc_html__( 'Elementor Template', 'tooto-elementor' ),
					'product_content' => esc_html__( 'Product Content (The Content)', 'tooto-elementor' ),
				],
				'default' => 'template',
				'description' => esc_html__( 'Choose "Elementor Template" to apply a saved design (e.g. Single Product Template) to the product. Choose "Product Content" to show the product\'s own content (if you designed the product page directly).', 'tooto-elementor' ),
			]
		);

		// Get Elementor Templates
		$lib_posts = get_posts( [
			'post_type' => 'elementor_library',
			'posts_per_page' => -1,
			'post_status' => 'publish',
		] );

		$template_options = [];
		if ( ! empty( $lib_posts ) ) {
			foreach ( $lib_posts as $t ) {
				$type = get_post_meta( $t->ID, '_elementor_template_type', true );
				$template_options[ $t->ID ] = $t->post_title . ' (' . $type . ')';
			}
		}

		$this->add_control(
			'template_id',
			[
				'label' => esc_html__( 'Select Template', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'options' => $template_options,
				'label_block' => true,
				'description' => esc_html__( 'Choose the template you want to use (e.g. your "Single Product" template).', 'tooto-elementor' ),
				'condition' => [
					'source_type' => 'template',
				],
			]
		);

		$this->end_controls_section();
	}

	protected function render() {
		$settings = $this->get_settings_for_display();
		
		$product_id = ! empty( $settings['product_id'] ) ? $settings['product_id'] : $settings['manual_product_id'];
		$source_type = isset( $settings['source_type'] ) ? $settings['source_type'] : 'template';
		$template_id = $settings['template_id'];

		if ( empty( $product_id ) ) {
			if ( Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-warning">';
				echo esc_html__( 'Please select a product.', 'tooto-elementor' );
				echo '</div>';
			}
			return;
		}

		if ( 'template' === $source_type && empty( $template_id ) ) {
			if ( Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-warning">';
				echo esc_html__( 'Please select a template.', 'tooto-elementor' );
				echo '</div>';
			}
			return;
		}

		// Context Switching Logic
		global $post;
		global $product;
		global $wp_query;

		$original_post = $post;
		$original_product = $product;
		$original_query = $wp_query;

		$post = get_post( $product_id );
		
		if ( ! $post || 'product' !== $post->post_type ) {
			if ( Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-danger">';
				echo esc_html__( 'Invalid Product ID or not a product.', 'tooto-elementor' );
				echo '</div>';
			}
			$post = $original_post;
			return;
		}

		setup_postdata( $post );
		$product = wc_get_product( $product_id );

		// Mock Main Query for SCF/ACF and Dynamic Tags compatibility
		// This tricks plugins into thinking we are on the single product page
		$wp_query = new \WP_Query( [
			'post_type' => 'product',
			'p' => $product_id,
		] );
		
		// Render content
		echo '<div class="tooto-product-content-wrapper" id="tooto-product-content-' . esc_attr( $this->get_id() ) . '">';
		
		if ( 'template' === $source_type ) {
			echo Plugin::$instance->frontend->get_builder_content_for_display( $template_id );
		} else {
			// Product Content Mode
			if ( Plugin::$instance->documents->get( $product_id )->is_built_with_elementor() ) {
				echo Plugin::$instance->frontend->get_builder_content_for_display( $product_id );
			} else {
				$content = $post->post_content;
				echo apply_filters( 'the_content', $content );
			}
		}

		echo '</div>';

		// Inline JS to force global layout update (Resize Event)
		// This fixes issues where this widget's rendering might affect or race with other Swiper/Carousel widgets on the page.
		// By triggering a window resize, we force all Swiper instances on the page to recalculate their dimensions.
		?>
		<script>
		(function($) {
			const wrapper = document.getElementById('tooto-product-content-<?php echo esc_attr( $this->get_id() ); ?>');
			if (!wrapper) return;

			const triggerGlobalResize = () => {
				window.dispatchEvent(new Event('resize'));
			};

			// Solution A: Wait for full page load to avoid conflicts with top components (e.g. Swiper)
			if (document.readyState === 'complete') {
				triggerGlobalResize();
			} else {
				window.addEventListener('load', triggerGlobalResize);
			}

			// Run on image load within this widget
			$(wrapper).find('img').on('load', triggerGlobalResize);
		})(jQuery);
		</script>
		<?php

		// Restore original context
		$post = $original_post;
		$product = $original_product;
		$wp_query = $original_query;
		
		if ( $post ) {
			setup_postdata( $post );
		} else {
			wp_reset_postdata();
		}
	}
}
