<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use Sifency\Traits\Sifency_Core_Text_Style;
use \Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;

class Sifency_Widget_Posttitle extends Widget_Base {
	use Sifency_Animation_Controls;
	use Sifency_Core_Text_Style;

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

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

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

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

    public function get_keywords() {
        return [ 'heading', 'title', 'text', 'dynamic', 'sifency' ];
    }
    public function get_style_depends() {
	    return [ 'sifency-typo-style' , 'sifency-frontend-style' ];
    }

	protected function register_controls() {
		$this->start_controls_section(
			'section_content',
			[ 'label' => esc_html__( 'Content', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_CONTENT ]
		);
		$this->add_control(
			'title_source',
			[
				'label'   => esc_html__( 'Source', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [
                    'post_title'   => esc_html__( 'Post Title', 'sifency-addons' ),
                    'custom'       => esc_html__( 'Custom Text', 'sifency-addons' ),
                    'the_excerpt'  => esc_html__( 'Post Excerpt', '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' ),
                    'acf_field'    => esc_html__( 'ACF Field', 'sifency-addons' ),
                ],
				'default' => 'post_title',
			]
		);
		$this->add_control(
			'heading_text',
			[ 'label' => esc_html__( 'Custom Text', 'sifency-addons' ), 'type' => Controls_Manager::TEXTAREA, 'default' => esc_html__( 'This is the heading', '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' ], ]
		);
		$this->add_control(
			'link',
			[ 'label' => esc_html__( 'Link', 'sifency-addons' ), 'type' => Controls_Manager::URL, 'dynamic' => [ 'active' => true ], 'default' => [ 'url' => get_permalink() ] ]
		);
		$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' => 'h2', ]
		);
		$this->end_controls_section();
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'heading_style',
            'label'    => 'Title Style',
            'selector' => '.sifency-heading-style',
            'target_children' => false,
        ]);
		$this->add_sifency_animation_controls();
		$this->update_control(
            'sifency_animation_target',
            [
                'type' => Controls_Manager::HIDDEN,
                'default' => 'wrapper',
            ]
        );
	}

	/**
	 * Render the widget output on the frontend.
	 */
	protected function render() {
		$settings = $this->get_settings_for_display();
		$animation_manager = new Sifency_Animation_Manager($settings);

		$text = $this->get_sifency_dynamic_title($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, true) ? $settings['html_tag'] : 'h2';
		$wrapper_classes = ['sifency-advanced-heading-wrapper'];
		
		if ( ! empty($settings['text_fill_background']) && 'gradient' === $settings['text_fill_background'] ) {
			$wrapper_classes[] = 'sifency-heading--gradient-fill';
		}

		if ( ! empty($settings['enable_text_stroke']) && 'yes' === $settings['enable_text_stroke'] ) {
			$wrapper_classes[] = 'sifency-heading--stroke';
			if ( ! empty($settings['stroke_hollow']) ) {
				$wrapper_classes[] = 'sifency-heading--stroke-hollow';
			}
			$stroke_width = $settings['stroke_width']['size'] ?? 1;
			$stroke_color = $settings['stroke_color'] ?? '#000';
			$this->add_render_attribute('wrapper_style', 'style', "--sifency-heading-stroke-width: {$stroke_width}px; --sifency-heading-stroke-color: {$stroke_color};");
		}
		
		$wrapper_attrs = $animation_manager->get_wrapper_attributes($wrapper_classes);

		$this->add_render_attribute('heading', 'class', 'sifency-dynamic-heading sifency-heading-style');
		if ( ! empty($settings['link']['url']) ) {
			$this->add_link_attributes('link_wrapper', $settings['link']);
		}
		?>
		
		<div <?php echo wp_kses_post( $wrapper_attrs ); ?> <?php echo wp_kses_post ($this->get_render_attribute_string('wrapper_style')); ?>>
			<?php if ( ! empty($settings['link']['url']) ) : ?>
				<a <?php echo wp_kses_post ($this->get_render_attribute_string('link_wrapper')); ?><?php  ?>>
			<?php endif; ?>

			<<?php  ?><?php echo esc_html($html_tag); ?> <?php echo wp_kses_post ($this->get_render_attribute_string('heading')); ?>>
				<?php echo wp_kses_post($text); ?>
			</<?php echo esc_html($html_tag); ?>>

			<?php if ( ! empty($settings['link']['url']) ) : ?>
				</a>
			<?php endif; ?>
		</div>
		<?php
	}
    /**
     *
     * @return int|false The post ID or false if not found.
     */
    private function get_current_post_id() {
        if ( function_exists('get_the_ID') ) {
            return get_the_ID();
        }
        if ( isset( $GLOBALS['post'] ) ) {
            return $GLOBALS['post']->ID;
        }
        return false;
    }

	protected function get_sifency_dynamic_title( $settings ) {
		$source = $settings['title_source'] ?? 'post_title';
		$text   = '';
        
        $post_id = $this->get_current_post_id();

		switch ( $source ) {
			case 'post_title':
				$text = $post_id ? get_the_title($post_id) : '';
				break;
			case 'the_excerpt':
				$text = $post_id ? get_the_excerpt($post_id) : '';
				break;
			case 'archive':
				if ( is_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'] ) && $post_id ) {
					$text = get_field( $settings['acf_field_name'], $post_id );
				}
				break;
			case 'custom':
			default:
				$text = $settings['heading_text'] ?? '';
				break;
		}
		return $text;
	}
}