<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Typography;
use \Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Core_Text_Style;

class Sifency_Widget_Posttagcat extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Core_Text_Style;

    public function get_name() {
        return 'post-tag-category';
    }

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

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

    public function get_categories() {
        return ['sifency-post-components'];
    }
    public function get_keywords() {
        return ['faq', 'accordion', 'toggle', 'question', 'answer', 'terms', 'category', 'tag'];
    }
    
    public function get_style_depends() {
	    return [ 'sifency-frontend-style', 'sifency-post-single-style' ];
    }
    protected function register_controls() {
        $this->start_controls_section(
            'section_content',
            [ 'label' => esc_html__('Content', 'sifency-addons') ]
        );
        $this->add_control(
            'taxonomy',
            [
                'label' => esc_html__('Taxonomy', 'sifency-addons'),
                'type' => Controls_Manager::SELECT,
                'options' => [ 'category' => 'Categories', 'post_tag' => 'Tags' ],
                'default' => 'category',
            ]
        );
        $this->add_control(
            'prefix',
            [ 
                'label' => esc_html__('Prefix', 'sifency-addons'), 
                'type' => Controls_Manager::TEXT,
                'placeholder' => esc_html__('e.g. Categories:', 'sifency-addons'),
            ]
        );
        $this->add_control(
            'separator',
            [
                'label' => esc_html__('Separator', 'sifency-addons'),
                'type' => Controls_Manager::TEXT,
                'default' => ',',
                'placeholder' => ',',
            ]
        );
        $this->end_controls_section();

        // --- Style Section ---
        $this->start_controls_section(
            'section_style',
            [ 'label' => esc_html__('Style', 'sifency-addons'), 'tab' => Controls_Manager::TAB_STYLE ]
        );
        $this->add_responsive_control(
			'align',
			[
				'label' => esc_html__('Alignment', 'sifency-addons'), 'type' => Controls_Manager::CHOOSE,
				'options' => [
					'flex-start' => [ 'title' => 'Left', 'icon' => 'eicon-h-align-left' ],
					'center' => [ 'title' => 'Center', 'icon' => 'eicon-h-align-center' ],
					'flex-end' => [ 'title' => 'Right', 'icon' => 'eicon-h-align-right' ],
				],
				'selectors' => [ '{{WRAPPER}} .sifency-post-terms' => 'justify-content: {{VALUE}};' ],
			]
		);
        $this->add_responsive_control(
            'gap',
            [ 'label' => esc_html__('Gap', 'sifency-addons'), 'type' => Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'max' => 50 ] ], 'selectors' => [ '{{WRAPPER}} .sifency-post-terms, {{WRAPPER}} .sifency-post-terms-list' => 'gap: {{SIZE}}px;' ] ]
        );
        $this->add_control( 'heading_prefix', [ 'label' => esc_html__('Prefix', 'sifency-addons'), 'type' => Controls_Manager::HEADING, 'separator' => 'before' ] );
        $this->add_control( 'prefix_color', [ 'label' => esc_html__('Color', 'sifency-addons'), 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-post-terms__prefix' => 'color: {{VALUE}};' ] ]);
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'prefix_typography', 'selector' => '{{WRAPPER}} .sifency-post-terms__prefix' ] );
        
        $this->add_control(
			'heading_separator',
			[
				'label' => esc_html__( 'Separator', 'sifency-addons' ),
				'type' => Controls_Manager::HEADING,
				'separator' => 'before',
			]
		);
        $this->add_control( 'separator_color', [ 'label' => esc_html__('Color', 'sifency-addons'), 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-post-terms__separator' => 'color: {{VALUE}};' ] ]);

        $this->end_controls_section();

        $this->add_sifency_advanced_text_style([
            'prefix'   => 'content_style',
            'label'    => 'Content Style',
            'selector' => '.sifency-content-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'meta_style',
            'label'    => 'Meta Style',
            'selector' => '.sifency-meta-style',
            'target_children' => false,
        ]);

        $this->add_sifency_animation_controls();
        $this->update_control(
            'content_style_section',
            [
                'label' => __( 'Terms Style', 'sifency-addons' ),
            ]
        );
        $this->update_control(
            'meta_style_section',
            [
                'label' => __( 'Separator Style', 'sifency-addons' ),
            ]
        );

        $this->update_control(
            'content_align',
            [
                'type' => Controls_Manager::HIDDEN,
            ]
        );
        $this->update_control(
            'meta_align',
            [
                'type' => Controls_Manager::HIDDEN,
            ]
        );
        $this->update_control(
            'sifency_animation_target',
            [
                'type' => Controls_Manager::HIDDEN,
                'default' => 'wrapper',
            ]
        );

    }
    /**
     * Render the widget output on the frontend.
     *
     * @since 1.0.4
     * @access protected
     */
    protected function render() {
        $settings = $this->get_settings_for_display();
        $taxonomy = $settings['taxonomy'];

        $terms = get_the_terms( get_the_ID(), $taxonomy );
        if ( ( empty($terms) || is_wp_error($terms) ) && \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
            $terms = [
                (object)[ 'name' => esc_html__('Technology', 'sifency-addons'), 'link' => '#' ],
                (object)[ 'name' => esc_html__('WordPress', 'sifency-addons'), 'link' => '#' ],
                (object)[ 'name' => esc_html__('Web Design', 'sifency-addons'), 'link' => '#' ],
            ];
            foreach( $terms as $term ) {
                $term->link = '#';
            }
        }
        
        if ( empty($terms) || is_wp_error($terms) ) {
            return;
        }

        $animation_manager = new Sifency_Animation_Manager($settings);
        $wrapper_classes = ['sifency-post-terms'];
        $wrapper_attrs_string = $animation_manager->get_wrapper_attributes($wrapper_classes);
        ?>
        <div <?php echo wp_kses_post ( $wrapper_attrs_string ); ?><?php  ?>>
            <?php if ( ! empty($settings['prefix']) ) : ?>
                <span class="sifency-post-terms__prefix">
                    <?php echo esc_html($settings['prefix']); ?>
                </span>
            <?php endif; ?>

            <div class="sifency-post-terms-list">
                <?php 
                if ( ! empty( $terms ) && is_array( $terms ) ) {

                    $separator_text = $settings['separator'] ?? ', ';
                    $separator = '<span class="sifency-post-terms__separator sifency-meta-style">' . esc_html( $separator_text ) . '</span>';

                    $term_links = [];
                    foreach ( $terms as $term ) {
                        $link = ( isset( $term->link ) && $term->link === '#' ) ? '#' : esc_url( get_term_link( $term ) );
                        $term_links[] = '<a href="' . $link . '" class="sifency-content-style">' . esc_html( $term->name ) . '</a>';
                    }

                    $allowed_tags = [
                        'a' => [
                            'href'  => [],
                            'class' => [],
                        ],
                        'span' => [
                            'class' => [],
                        ],
                    ];

                    echo wp_kses( implode( $separator, $term_links ), $allowed_tags );
                }
                ?>
            </div>

        </div>
        <?php
    }

    /**
	 * Render the widget output in the editor.
	 *
	 * Written as a Backbone JavaScript template and used to generate the live preview.
	 *
	 * @since 1.0.4
	 * @access protected
	 */
	protected function _content_template() {
		?>
		<#
		var demoTerms = [ 'Technology', 'WordPress', 'Web Design' ];
		var term_links = [];

        view.addRenderAttribute( 'wrapper', 'class', 'sifency-post-terms' );

		var separator = '<span class="sifency-post-terms__separator">' + ( settings.separator || ',' ) + '</span>';

		_.each( demoTerms, function( term ) {
			term_links.push( '<a href="#">' + term + '</a>' );
		} );
		
		#>
		<div {{{ view.getRenderAttributeString( 'wrapper' ) }}}>
			<# if ( settings.prefix ) { #>
				<span class="sifency-post-terms__prefix">
					{{{ settings.prefix }}}
				</span>
			<# } #>

			<div class="sifency-post-terms-list sifency-content-style">
				{{{ term_links.join( separator ) }}}
			</div>
		</div>
		<?php
	}
}