<?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_Text_Shadow;
use Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Core_Text_Style;

class Sifency_Widget_Postexcerpt extends Widget_Base {
	use Sifency_Animation_Controls;
	use Sifency_Core_Text_Style;

	public function get_name() {
		return 'sifency-post-excerpt';
	}

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

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

	public function get_categories() {
		return [ 'sifency-post-components' ];
	}

    public function get_keywords() {
        return [ 'heading', 'title', 'text', 'dynamic', 'sifency', 'excerpt', 'content' ];
    }

    public function get_style_depends() {
	    return [ 'sifency-typo-style' ];
	}
    
	protected function register_controls() {
		$this->start_controls_section(
			'section_content',
			[ 'label' => esc_html__( 'Content', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_CONTENT ]
		);
		$source_options = [
			'the_excerpt' => esc_html__( 'Post Excerpt', 'sifency-addons' ),
			'custom'      => esc_html__( 'Custom Text', 'sifency-addons' ),
			'post_title'  => esc_html__( 'Post Title', 'sifency-addons' ),
			'the_content' => esc_html__( 'Post Content (Limited)', 'sifency-addons' ),
			'archive'     => esc_html__( 'Archive Title', 'sifency-addons' ),
			'site_title'  => esc_html__( 'Site Title', 'sifency-addons' ),
			'site_tagline'=> esc_html__( 'Site Tagline', 'sifency-addons' ),
		];
        if ( function_exists('get_field') ) {
            $source_options['acf_field'] = esc_html__( 'ACF Field', 'sifency-addons' );
        }

		$this->add_control(
			'title_source',
			[
				'label'   => esc_html__( 'Source', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => $source_options,
				'default' => 'the_excerpt',
			]
		);
		$this->add_control(
			'heading_text',
			[
				'label'       => esc_html__( 'Text', 'sifency-addons' ),
				'label_block' => true,
				'type'        => Controls_Manager::TEXTAREA,
				'default'     => esc_html__( 'This is the post excerpt.', 'sifency-addons' ),
				'placeholder' => esc_html__( 'Enter your text', 'sifency-addons' ),
				'condition'   => [ 'title_source' => 'custom' ],
				'dynamic'     => [ 'active' => true ],
			]
		);
        $this->add_control(
			'acf_field_name',
			[
				'label'       => esc_html__( 'ACF Field Name', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'condition'   => [ 'title_source' => 'acf_field' ],
                'description' => esc_html__( 'Enter the ACF field key (e.g., my_custom_field).', 'sifency-addons' ),
			]
		);
        $this->add_control(
			'excerpt_length',
			[
				'label'       => esc_html__( 'Excerpt Length (Words)', 'sifency-addons' ),
				'type'        => Controls_Manager::NUMBER,
                'default'     => 55,
				'condition'   => [ 'title_source' => 'the_content' ],
                'description' => esc_html__( 'Controls the number of words shown when "Post Content" is the source.', 'sifency-addons' ),
			]
		);
		$this->add_control(
			'link',
			[
				'label'       => esc_html__( 'Link', 'sifency-addons' ),
				'type'        => Controls_Manager::URL,
				'placeholder' => esc_html__( 'https://your-link.com', 'sifency-addons' ),
				'dynamic'     => [ 'active' => true ],
			]
		);
		$this->add_control(
			'html_tag',
			[
				'label'   => esc_html__( 'HTML Tag', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [ 'h1' => 'H1', 'h2' => 'H2', 'h3' => 'H3', 'h4' => 'H4', 'h5' => 'H5', 'h6' => 'H6', 'div' => 'div', 'span' => 'span', 'p' => 'p' ],
				'default' => 'p',
			]
		);
		$this->end_controls_section();

        $this->add_sifency_advanced_text_style([
            'prefix'   => 'content_style',
            'label'    => 'Excerpt',
            'selector' => '.sifency-content-style',
            'target_children' => false,
        ]);
	}

	/**
	 * Render the widget output on the frontend.
	 *
	 * @since 1.0.4
	 * @access protected
	 */
	protected function render() {
		$settings = $this->get_settings_for_display();
		$animation_manager = new Sifency_Animation_Manager($settings);
		$text = $this->get_sifency_dynamic_text( $settings );
		if ( empty( $text ) ) {
			return;
		}
		
		$allowed_tags = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span', 'p' ];
		$html_tag = in_array( $settings['html_tag'], $allowed_tags ) ? $settings['html_tag'] : 'p';
		$this->add_render_attribute( 'heading', 'class', 'sifency-content-widget sifency-content-style' );
		$animation_attrs_string = $animation_manager->get_wrapper_attributes([]);
		if ( ! empty($animation_attrs_string) ) {
			preg_match('/class="([^"]+)"/', $animation_attrs_string, $class_matches);
			if (isset($class_matches[1])) {
				$this->add_render_attribute('heading', 'class', $class_matches[1]);
			}
			preg_match_all('/(data-[^=]+="[^"]+")/', $animation_attrs_string, $data_matches);
			if (isset($data_matches[1])) {
				foreach($data_matches[1] as $attr) {
					list($key, $value) = explode('=', $attr);
					$this->add_render_attribute('heading', $key, trim($value, '"'));
				}
			}
		}
		
		if ( ! empty( $settings['link']['url'] ) ) {
			$this->add_link_attributes( 'link', $settings['link'] );
			$text = sprintf( '<a %1$s>%2$s</a>', $this->get_render_attribute_string( 'link' ), $text );
		}
		
		printf(
			'<%1$s %2$s>%3$s</%1$s>',
			esc_html( $html_tag ),
			wp_kses_post ( $this->get_render_attribute_string( 'heading' )),
			wp_kses_post( $text )
		);
	}

	protected function get_sifency_dynamic_text( $settings ) {
		$source = $settings['title_source'];
		$text   = '';
		switch ( $source ) {
			case 'post_title': $text = get_the_title(); break;
			case 'the_excerpt': $text = get_the_excerpt(); break;
            case 'the_content':
                $content = get_the_content();
                $content = apply_filters('the_content', $content);
                $content = str_replace(']]>', ']]&gt;', $content);
                $text = wp_trim_words( $content, (int) $settings['excerpt_length'], '...' );
                break;
			case 'archive': $text = get_the_archive_title(); break;
			case 'site_title': $text = get_bloginfo( 'name' ); break;
			case 'site_tagline': $text = get_bloginfo( 'description' ); break;
			case 'acf_field':
				if ( function_exists( 'get_field' ) && ! empty( $settings['acf_field_name'] ) ) {
					$text = get_field( $settings['acf_field_name'] );
				}
				break;
			case 'custom':
			default:
				$text = $settings['heading_text'];
				break;
		}
		return $text;
	}
}