<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Typography;
use \Elementor\Group_Control_Border;
use \Elementor\Plugin as ElementorPlugin;
use \Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;

class Sifency_Widget_Product_Meta extends Widget_Base {
    use Sifency_Animation_Controls;

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

    public function get_title() {
        return __('Sifency Product Meta', 'sifency-addons');
    }

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

    public function get_categories() {
        return ['sifency-addons-woo-widgets'];
    }

    public function get_keywords() {
        return ['product', 'meta', 'sku', 'category', 'tag', 'woocommerce'];
    }

    public function get_style_depends() {
        return [ 'sifency-product-single-style' ];
    }
    
    protected function register_controls() {
        if ( ! class_exists('woocommerce') ) {
            $this->start_controls_section('woo_notice', [ 'label' => 'Notice' ]);
            $this->add_control('woo_notice_control', [ 'type' => Controls_Manager::RAW_HTML, 'raw' => '<div class="elementor-panel-alert elementor-panel-alert-warning">' . esc_html__('WooCommerce is not installed or active.', 'sifency-addons') . '</div>' ]);
            $this->end_controls_section();
            return;
        }

        // --- Content Section: Elements ---
        $this->start_controls_section(
            'section_content_elements',
            [
                'label' => __( 'Elements', 'sifency-addons' ),
            ]
        );

        $this->add_control(
            'show_sku',
            [
                'label' => __( 'Show SKU', 'sifency-addons' ),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __( 'Show', 'sifency-addons' ),
                'label_off' => __( 'Hide', 'sifency-addons' ),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_category',
            [
                'label' => __( 'Show Categories', 'sifency-addons' ),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __( 'Show', 'sifency-addons' ),
                'label_off' => __( 'Hide', 'sifency-addons' ),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_tags',
            [
                'label' => __( 'Show Tags', 'sifency-addons' ),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __( 'Show', 'sifency-addons' ),
                'label_off' => __( 'Hide', 'sifency-addons' ),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );
        
        $this->end_controls_section();


        // --- Content Section: Layout ---
        $this->start_controls_section( 'section_content_layout', [ 'label' => 'Layout' ] );
		$this->add_control(
			'view',
			[ 'label' => 'View', 'type' => Controls_Manager::SELECT, 'options' => [ 'stacked' => 'Stacked', 'inline' => 'Inline' ], 'default' => 'stacked', 'prefix_class' => 'sifency-product-meta-view-' ]
		);
        $this->add_responsive_control(
            'space_between',
            [
                'label' => __('Space Between', 'sifency-addons'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [ 'px' => [ 'min' => 0, 'max' => 100 ] ],
                'default' => [ 'unit' => 'px', 'size' => 10 ],
                'selectors' => [
                    '{{WRAPPER}}.sifency-product-meta-view-inline' => '--sifency-space-between: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}}.sifency-product-meta-view-stacked .product_meta > span:not(:last-child)' => 'padding-bottom: {{SIZE}}{{UNIT}}; margin-bottom: {{SIZE}}{{UNIT}};',
                ],
            ]
        );
        $this->end_controls_section();

        // --- Style Section ---
        $this->start_controls_section( 'section_style_meta', [ 'label' => 'General Style', 'tab' => Controls_Manager::TAB_STYLE ] );
        $this->add_responsive_control(
            'alignment',
            [ 
                'label' => 'Alignment', 
                'type' => Controls_Manager::CHOOSE, 
                'options' => [ 
                    'left' => [ 'title' => 'Left', 'icon' => 'eicon-text-align-left' ], 
                    'center' => [ 'title' => 'Center', 'icon' => 'eicon-text-align-center' ], 
                    'right' => [ 'title' => 'Right', 'icon' => 'eicon-text-align-right' ] 
                ], 
                'selectors' => [ 
                    '{{WRAPPER}} .product_meta' => 'text-align: {{VALUE}};',
                    '{{WRAPPER}}.sifency-product-meta-view-inline .product_meta' => 'justify-content: {{VALUE}};'
                ],
                'selectors_dictionary' => [
					'left' => 'flex-start',
					'right' => 'flex-end',
				],
            ]
        );
        $this->add_control( 'label_heading', [ 'label' => 'Labels (e.g., "SKU:")', 'type' => Controls_Manager::HEADING, 'separator' => 'before' ] );
        $this->add_control( 'label_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .product_meta > span' => 'color: {{VALUE}};' ] ]);
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'label_typography', 'selector' => '{{WRAPPER}} .product_meta > span' ] );
        
        $this->add_control( 'links_heading', [ 'label' => 'Links & Text (Categories, SKU)', 'type' => Controls_Manager::HEADING, 'separator' => 'before' ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'text_typography', 'selector' => '{{WRAPPER}} .product_meta .sku, {{WRAPPER}} .product_meta .posted_in a' ] );
        $this->start_controls_tabs('text_style_tabs');
        $this->start_controls_tab( 'text_normal_tab', ['label' => 'Normal'] );
        $this->add_control( 'text_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .product_meta .sku, {{WRAPPER}} .product_meta .posted_in a' => 'color: {{VALUE}};' ] ]);
        $this->end_controls_tab();
        $this->start_controls_tab( 'text_hover_tab', ['label' => 'Hover'] );
        $this->add_control( 'text_hover_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .product_meta .posted_in a:hover' => 'color: {{VALUE}};' ] ]);
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->end_controls_section();

        // --- Tag Style Section ---
        $this->start_controls_section( 'section_style_tags', [ 'label' => 'Tags Style', 'tab' => Controls_Manager::TAB_STYLE ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'tags_typography', 'selector' => '{{WRAPPER}} .tagged_as a' ] );
        $this->add_responsive_control('tags_padding', [ 'label' => 'Padding', 'type' => Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', 'em', '%' ], 'selectors' => [ '{{WRAPPER}} .tagged_as a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ]);
        $this->add_control('tags_border_radius', [ 'label' => 'Border Radius', 'type' => Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%' ], 'selectors' => [ '{{WRAPPER}} .tagged_as a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ]);
        
        $this->start_controls_tabs('tags_style_tabs');
        $this->start_controls_tab( 'tags_normal_tab', ['label' => 'Normal'] );
        $this->add_control( 'tags_text_color', [ 'label' => 'Text Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .tagged_as a' => 'color: {{VALUE}};' ] ]);
        $this->add_control( 'tags_bg_color', [ 'label' => 'Background Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .tagged_as a' => 'background-color: {{VALUE}};' ] ]);
        $this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'tags_border', 'selector' => '{{WRAPPER}} .tagged_as a' ] );
        $this->end_controls_tab();

        $this->start_controls_tab( 'tags_hover_tab', ['label' => 'Hover'] );
        $this->add_control( 'tags_text_hover_color', [ 'label' => 'Text Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .tagged_as a:hover' => 'color: {{VALUE}};' ] ]);
        $this->add_control( 'tags_bg_hover_color', [ 'label' => 'Background Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .tagged_as a:hover' => 'background-color: {{VALUE}};' ] ]);
        $this->add_control( 'tags_border_hover_color', [ 'label' => 'Border Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .tagged_as a:hover' => 'border-color: {{VALUE}};' ] ]);
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->end_controls_section();

        // --- Separator Style Section ---
        $this->start_controls_section( 'section_style_separators', [ 'label' => 'Separators', 'tab' => Controls_Manager::TAB_STYLE ] );
        
        $this->add_control('stacked_separator_heading', [ 'label' => 'Stacked View Separator', 'type' => Controls_Manager::HEADING, 'condition' => [ 'view' => 'stacked' ] ]);
        $this->add_control(
            'show_stacked_separator',
            [
                'label' => __( 'Show Separator', 'sifency-addons' ),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'prefix_class' => 'sifency-stacked-sep-',
                'condition' => [ 'view' => 'stacked' ],
            ]
        );
        $this->add_control('stacked_separator_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}}.sifency-product-meta-view-stacked .product_meta > span:not(:last-child)' => 'border-bottom-color: {{VALUE}}' ], 'condition' => [ 'view' => 'stacked', 'show_stacked_separator' => 'yes' ] ]);
        $this->add_control('stacked_separator_style', [ 'label' => 'Style', 'type' => Controls_Manager::SELECT, 'options' => [ 'solid' => 'Solid', 'dotted' => 'Dotted', 'dashed' => 'Dashed' ], 'default' => 'solid', 'selectors' => [ '{{WRAPPER}}.sifency-product-meta-view-stacked .product_meta > span:not(:last-child)' => 'border-bottom-style: {{VALUE}}' ], 'condition' => [ 'view' => 'stacked', 'show_stacked_separator' => 'yes' ] ]);
        $this->add_control('stacked_separator_width', [ 'label' => 'Width', 'type' => Controls_Manager::SLIDER, 'size_units' => ['px'], 'range' => [ 'px' => [ 'min' => 1, 'max' => 10 ] ], 'selectors' => [ '{{WRAPPER}}.sifency-product-meta-view-stacked .product_meta > span:not(:last-child)' => 'border-bottom-width: {{SIZE}}{{UNIT}}' ], 'condition' => [ 'view' => 'stacked', 'show_stacked_separator' => 'yes' ] ]);

        $this->add_control('inline_separator_heading', [ 'label' => 'Inline View Separator', 'type' => Controls_Manager::HEADING, 'separator' => 'before', 'condition' => [ 'view' => 'inline' ] ]);
        $this->add_control(
            'show_inline_separator',
            [
                'label' => __( 'Show Separator', 'sifency-addons' ),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'prefix_class' => 'sifency-inline-sep-show-',
                'condition' => [ 'view' => 'inline' ],
            ]
        );
        $this->add_control('inline_separator_symbol', [ 'label' => 'Separator Symbol', 'type' => Controls_Manager::TEXT, 'default' => '·', 'selectors' => [ '{{WRAPPER}}.sifency-product-meta-view-inline .product_meta > span:not(:last-child)::after' => 'content: "{{VALUE}}"' ], 'condition' => [ 'view' => 'inline', 'show_inline_separator' => 'yes' ] ]);
        $this->add_control('inline_separator_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}}.sifency-product-meta-view-inline .product_meta > span:not(:last-child)::after' => 'color: {{VALUE}}' ], 'condition' => [ 'view' => 'inline', 'show_inline_separator' => 'yes' ] ]);
        $this->end_controls_section();


        $this->add_sifency_animation_controls();
        $this->update_control( 'sifency_animation_target', [ 'type' => \Elementor\Controls_Manager::HIDDEN, 'default' => 'wrapper' ] );
    }

    private function get_editor_preview_product() {
        $document = ElementorPlugin::$instance->documents->get_current();
        if ( $document && 'product' === get_post_type( $document->get_main_id() ) ) {
            return wc_get_product( $document->get_main_id() );
        }
        
        $latest_products = get_posts([ 'post_type' => 'product', 'posts_per_page' => 1 ]);
        if ( ! empty($latest_products) ) {
            return wc_get_product( $latest_products[0]->ID );
        }

        return false;
    }

    protected function render() {
        // Accessing the global $product object from WooCommerce.
        global $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
        if ( \Elementor\Plugin::$instance->editor->is_edit_mode() && ! $product ) {
            if ( method_exists( $this, 'get_editor_preview_product' ) ) {
                $product = $this->get_editor_preview_product();// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
            }
        }
        
        if ( ! is_a( $product, 'WC_Product' ) ) {
            if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
                $this->render_editor_placeholder();
            }
            return;
        }

        $settings = $this->get_settings_for_display();

        $animation_manager = new Sifency_Animation_Manager($settings);
        $wrapper_classes = ['sifency-product-meta-wrapper'];
        $wrapper_attrs = $animation_manager->get_wrapper_attributes($wrapper_classes);
        ?>
        <div <?php echo wp_kses_post( $wrapper_attrs ); ?>>
            <div class="product_meta">
            <?php do_action( 'woocommerce_product_meta_start' ); ?>

            <?php if ( 'yes' === $settings['show_sku'] && wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : 
                $sku = $product->get_sku();
                ?>
                <span class="sku_wrapper">
                    <?php esc_html_e( 'SKU:', 'sifency-addons' ); ?> 
                    <span class="sku">
                        <?php echo $sku ? esc_html( $sku ) : esc_html__( 'N/A', 'sifency-addons' ); ?>
                    </span>
                </span>
            <?php endif; ?>

            <?php if ( 'yes' === $settings['show_category'] ) : ?>
                <?php  ?>
                <?php echo wp_kses_post (wc_get_product_category_list( $product->get_id()), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'sifency-addons' ) . ' ', '</span>' ); ?>
            <?php endif; ?>

            <?php if ( 'yes' === $settings['show_tags'] ) : ?>
                <?php  ?>
                <?php echo wp_kses_post(wc_get_product_tag_list( $product->get_id()), ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'sifency-addons' ) . ' ', '</span>' ); ?>
            <?php endif; ?>

            <?php do_action( 'woocommerce_product_meta_end' ); ?>
            </div>
        </div>
        <?php
    }

    private function render_editor_placeholder() {
        echo '<div class="sifency-placeholder product_meta">';
        echo '<span class="sku_wrapper">SKU: <span class="sku">N/A</span></span>';
        echo '<span class="posted_in">Category: <a href="#">Music</a></span>';
        echo '<span class="tagged_as">Tag: <a href="#">Rock</a></span>';
        echo '</div>';
    }
}