<?php
/**
 * Elementor Dynamic Content
 * 
 * A class to add dynamic content capabilities to Elementor widgets
 */
class kavehdynamiccontent
{
    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('admin_init', array($this, 'check_and_modify_elementor_cache_ttl'));
        add_action('elementor/element/image/section_image/before_section_end', array($this, 'extend_image_widget'), 10, 2);
        add_action('elementor/element/text-editor/section_editor/before_section_end', array($this, 'extend_text_editor_widget'), 10, 2);
        add_action('elementor/element/heading/section_title/before_section_end', array($this, 'extend_heading_widget'), 10, 2);
        add_action('elementor/frontend/widget/before_render', array($this, 'process_dynamic_widgets'));
        add_action('init', array($this, 'register_loop_builder_post_type'));
        add_action('admin_menu', array($this, 'add_loop_builder_submenu'));
        add_action('init', array($this, 'register_mega_menu_post_type'));
        add_action('admin_menu', array($this, 'add_Mega_menu_submenu'));

    }

  
    public function register_mega_menu_post_type()
    {
        $args = array(
            'labels' => array(
                'name' => __('Mega Menu', 'kavehTheme'),
                'singular_name' => __('Mega Menu', 'kavehTheme'),
                'menu_name' => __('Mega Menu', 'kavehTheme'),
                'name_admin_bar' => __('Mega Menu', 'kavehTheme'),
                'add_new' => __('Add New', 'kavehTheme'),
                'add_new_item' => __('Add New Mega Menu', 'kavehTheme'),
                'new_item' => __('New Mega Menu', 'kavehTheme'),
                'edit_item' => __('Edit Mega Menu', 'kavehTheme'),
                'view_item' => __('View Mega Menu', 'kavehTheme'),
                'all_items' => __('All Mega Menus', 'kavehTheme'),
                'search_items' => __('Search Mega Menus', 'kavehTheme'),
                'parent_item_colon' => __('Parent Mega Menus:', 'kavehTheme'),
                'not_found' => __('No Mega Menu found.', 'kavehTheme'),
                'not_found_in_trash' => __('No Mega Menu found in Trash.', 'kavehTheme')
            ),
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => false, 
            'query_var' => true,
            'rewrite' => array('slug' => 'c-mega-menu'),
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'supports' => array('title', 'elementor')
        );

        register_post_type('c-mega-menu', $args);
    }

    public function add_Mega_menu_submenu()
    {
        add_submenu_page(
            'edit.php?post_type=ag-themer',    // Parent slug (ag-themer post type)
            __('Mega Menu', 'kavehTheme'),                     // Page title
            __('Mega Menu', 'kavehTheme'),                     // Menu title
            'manage_options',                   // Capability
            'edit.php?post_type=c-mega-menu'   // Menu slug (linking to c-loop-builder post type)
        );
    }


    /**
     * Register the 'Loop Builder' post type and add it as submenu to 'ag-themer'
     */
    public function register_loop_builder_post_type()
    {
        // Register the Loop Builder post type
        $args = array(
            'labels' => array(
                'name' => __('Loops', 'kavehTheme'),
                'singular_name' => __('Loop', 'kavehTheme'),
                'menu_name' => __('Loop Builder', 'kavehTheme'),
                'name_admin_bar' => __('Loop Builder', 'kavehTheme'),
                'add_new' => __('Add New', 'kavehTheme'),
                'add_new_item' => __('Add New Loop', 'kavehTheme'),
                'new_item' => __('New Loop', 'kavehTheme'),
                'edit_item' => __('Edit Loop', 'kavehTheme'),
                'view_item' => __('View Loop', 'kavehTheme'),
                'all_items' => __('All Loops', 'kavehTheme'),
                'search_items' => __('Search Loops', 'kavehTheme'),
                'parent_item_colon' => __('Parent Loops:', 'kavehTheme'),
                'not_found' => __('No loop found.', 'kavehTheme'),
                'not_found_in_trash' => __('No loop found in Trash.', 'kavehTheme')
            ),
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => false, // Don't show in main menu
            'query_var' => true,
            'rewrite' => array('slug' => 'c-loop-builder'),
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'supports' => array('title', 'elementor')
        );

        register_post_type('c-loop-builder', $args);
    }

    /**
     * Add the Loop Builder as a submenu to ag-themer
     */
    public function add_loop_builder_submenu()
    {
        // Add Loop Builder as submenu under ag-themer
        add_submenu_page(
            'edit.php?post_type=ag-themer',    // Parent slug (ag-themer post type)
            __('Loop Builder', 'kavehTheme'),                     // Page title
            __('Loop Builder', 'kavehTheme'),                     // Menu title
            'manage_options',                   // Capability
            'edit.php?post_type=c-loop-builder'   // Menu slug (linking to c-loop-builder post type)
        );
    }




    /**
     * Check and modify Elementor cache TTL
     */
    public function check_and_modify_elementor_cache_ttl()
    {
        // Get the current TTL value
        $element_cache_ttl = get_option('elementor_element_cache_ttl', 'disable');
        // If TTL is set (not 0 or empty) and not already set to your desired value
        if ($element_cache_ttl && $element_cache_ttl !== 'disable') {
            // Disable caching by setting TTL to 'disable'
            update_option('elementor_element_cache_ttl', 'disable');
        }
    }

    /**
     * Get current post ID in context
     * 
     * @param object $widget The Elementor widget
     * @return int Post ID
     */
    private function get_current_post_id($widget)
    {
        $post_id = get_the_ID();

        // If we're in a posts widget or archive, get the correct post ID
        if (\Elementor\Plugin::instance()->editor->is_edit_mode()) {
            // In editor mode, use the preview post
            $post_id = $widget->get_post_id();
        } else {
            $post_id = get_the_ID();
        }

        return $post_id;
    }

    /**
     * Extend Image widget with dynamic content controls
     * 
     * @param object $element The Elementor element
     * @param array $args Additional arguments
     */
    public function extend_image_widget($element, $args)
    {
        $element->add_control(
            'use_dynamic_image',
            [
                'label' => __('Use Dynamic Image', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $element->add_control(
            'dynamic_image_source',
            [
                'label' => __('Image Source', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'featured' => __('Featured Image', 'kavehTheme'),
                    'custom_field' => __('Custom Field', 'kavehTheme'),
                    'author' => __('Author Avatar', 'kavehTheme'),
                ],
                'default' => 'featured',
                'condition' => [
                    'use_dynamic_image' => 'yes',
                ],
            ]
        );

        $element->add_control(
            'custom_field_name',
            [
                'label' => __('Custom Field Name', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => [
                    'use_dynamic_image' => 'yes',
                    'dynamic_image_source' => 'custom_field',
                ],
            ]
        );
    }

    /**
     * Extend Text Editor widget with dynamic content controls
     * 
     * @param object $element The Elementor element
     * @param array $args Additional arguments
     */
    public function extend_text_editor_widget($element, $args)
    {
        $element->add_control(
            'use_dynamic_text',
            [
                'label' => __('Use Dynamic Content', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $element->add_control(
            'dynamic_text_source',
            [
                'label' => __('Content Source', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'custom_field' => __('Custom Field', 'kavehTheme'),
                    'post_content' => __('Post Content', 'kavehTheme'),
                    'excerpt' => __('Post Excerpt', 'kavehTheme'),
                    'archive_description' => __('Archive Description', 'kavehTheme'),
                ],
                'default' => 'custom_field',
                'condition' => [
                    'use_dynamic_text' => 'yes',
                ],
            ]
        );

        $element->add_control(
            'text_custom_field',
            [
                'label' => __('Custom Field Name', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => [
                    'use_dynamic_text' => 'yes',
                    'dynamic_text_source' => 'custom_field',
                ],
            ]
        );
    }

    /**
     * Extend Heading widget with dynamic content controls
     * 
     * @param object $element The Elementor element
     * @param array $args Additional arguments
     */
    public function extend_heading_widget($element, $args)
    {
        $element->add_control(
            'use_dynamic_heading',
            [
                'label' => __('Use Dynamic Content', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );

        $element->add_control(
            'dynamic_heading_source',
            [
                'label' => __('Content Source', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'post_title' => __('Post Title', 'kavehTheme'),
                    'custom_field' => __('Custom Field', 'kavehTheme'),
                    'author_meta' => __('Author Meta', 'kavehTheme'),
                    'site_title' => __('Site Title', 'kavehTheme'),
                    'post_date' => __('Post Date', 'kavehTheme'),
                    'archive_title' => __('Archive Title', 'kavehTheme'),
                    'taxonomy_terms' => __('Taxonomy Terms', 'kavehTheme'),
                ],
                'default' => 'post_title',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                ],
            ]
        );

        $author_meta_fields = apply_filters('kaveh/author_meta_fields', [
            'display_name' => __('Display Name', 'kavehTheme'),
            'user_login' => __('Username', 'kavehTheme'),
            'first_name' => __('First Name', 'kavehTheme'),
            'last_name' => __('Last Name', 'kavehTheme'),
            'nickname' => __('Nickname', 'kavehTheme'),
            'description' => __('Biographical Info', 'kavehTheme'),
        ]);
        
        $element->add_control(
            'author_meta_field',
            [
                'label' => __('Author Meta Field', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => $author_meta_fields,
                'default' => 'display_name',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'author_meta',
                ],
            ]
        );

        $element->add_control(
            'heading_custom_field',
            [
                'label' => __('Custom Field Name', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'custom_field',
                ],
            ]
        );

        // Add control for taxonomy selection
        $element->add_control(
            'taxonomy_type',
            [
                'label' => __('Taxonomy Type', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'options' => $this->get_registered_taxonomies(),
                'default' => 'category',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'taxonomy_terms',
                ],
            ]
        );

        // Add control for term separator
        $element->add_control(
            'term_separator',
            [
                'label' => __('Term Separator', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => ', ',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'taxonomy_terms',
                ],
            ]
        );

        // Add control for max terms to display
        $element->add_control(
            'max_terms',
            [
                'label' => __('Max Terms to Display', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'min' => 1,
                'max' => 30,
                'default' => 5,
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'taxonomy_terms',
                ],
            ]
        );

        // Add control for term links (always enabled by default)
        $element->add_control(
            'link_terms',
            [
                'label' => __('Link Terms to Archives', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => 'yes', // Changed to 'yes' by default
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source' => 'taxonomy_terms',
                ],
                'description' => __('Each term will link to its archive page', 'kavehTheme'),
            ]
        );

        // Add dynamic link controls
        $element->add_control(
            'use_dynamic_link',
            [
                'label' => __('Use Dynamic Link', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
                'separator' => 'before',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'dynamic_heading_source!' => 'taxonomy_terms', // Hide when taxonomy_terms is selected
                ],
            ]
        );

        $element->add_control(
            'dynamic_link_source',
            [
                'label' => __('Link Source', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'post_url' => __('Post URL', 'kavehTheme'),
                    'custom_field' => __('Custom Field', 'kavehTheme'),
                    'author_url' => __('Author URL', 'kavehTheme'),
                    'home_url' => __('Home URL', 'kavehTheme'),
                    'term_url' => __('Term/Archive URL', 'kavehTheme'),
                    'taxonomy_term' => __('First Taxonomy Term URL', 'kavehTheme'),
                ],
                'default' => 'post_url',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'use_dynamic_link' => 'yes',
                ],
            ]
        );

        $element->add_control(
            'link_custom_field',
            [
                'label' => __('Link Custom Field', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'use_dynamic_link' => 'yes',
                    'dynamic_link_source' => 'custom_field',
                ],
            ]
        );

        $element->add_control(
            'taxonomy_link_source',
            [
                'label' => __('Link Taxonomy Source', 'kavehTheme'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'options' => $this->get_registered_taxonomies(),
                'default' => 'category',
                'condition' => [
                    'use_dynamic_heading' => 'yes',
                    'use_dynamic_link' => 'yes',
                    'dynamic_link_source' => 'taxonomy_term',
                ],
                'description' => __('Select taxonomy to get the first term link from', 'kavehTheme'),
            ]
        );
    }

    /**
     * Process dynamic content for widgets before rendering
     * 
     * @param object $widget The Elementor widget
     */
    public function process_dynamic_widgets($widget)
    {
        $widget_name = $widget->get_name();
        $settings = $widget->get_settings();

        switch ($widget_name) {
            case 'image':
                $this->process_dynamic_image($widget, $settings);
                break;

            case 'text-editor':
                $this->process_dynamic_text_editor($widget, $settings);
                break;

            case 'heading':
                $this->process_dynamic_heading($widget, $settings);
                break;
        }
    }

    /**
     * Process dynamic image content
     * 
     * @param object $widget The Elementor widget
     * @param array $settings Widget settings
     */
    private function process_dynamic_image($widget, $settings)
    {
        if (empty($settings['use_dynamic_image']) || 'yes' !== $settings['use_dynamic_image']) {
            return;
        }

        // Get the current post ID in the loop
        $post_id = $this->get_current_post_id($widget);
        $author_id = null;

        // Get author ID if available
        global $post;
        if (isset($post->post_author)) {
            $author_id = $post->post_author;
        }

        $image_url = '';

        switch ($settings['dynamic_image_source']) {
            case 'featured':
                $image_url = get_the_post_thumbnail_url($post_id, 'full');
                break;

            case 'custom_field':
                if (!empty($settings['custom_field_name'])) {
                    $field_value = get_post_meta($post_id, $settings['custom_field_name'], true);

                    if (is_numeric($field_value)) {
                        $image_url = wp_get_attachment_image_url($field_value, 'full');
                    } else {
                        $image_url = esc_url($field_value);
                    }
                }
                break;

            case 'author':
                if ($author_id) {
                    $image_url = get_avatar_url($author_id);
                } else {
                    $image_url = get_avatar_url(get_the_author_meta('ID'));
                }
                break;
        }

        if (!empty($image_url)) {
            $widget->set_settings('image', [
                'url' => $image_url,
                'id' => attachment_url_to_postid($image_url) // This helps with Elementor's lightbox
            ]);
        }
    }

    /**
     * Process dynamic text editor content
     * 
     * @param object $widget The Elementor widget
     * @param array $settings Widget settings
     */
    private function process_dynamic_text_editor($widget, $settings)
    {
        if (empty($settings['use_dynamic_text']) || 'yes' !== $settings['use_dynamic_text']) {
            return;
        }

        // Get the current post ID in the loop
        $post_id = $this->get_current_post_id($widget);
        $editor_text = '';

        switch ($settings['dynamic_text_source']) {
            case 'custom_field':
                if (!empty($settings['text_custom_field'])) {
                    $editor_text = get_post_meta($post_id, $settings['text_custom_field'], true);
                }
                break;

            case 'post_content':
                $editor_text = get_post_field('post_content', $post_id);
                break;

            case 'excerpt':
                $editor_text = get_post_field('post_excerpt', $post_id);
                break;

            case 'archive_description':
                $editor_text = $this->get_archive_description();
                break;
        }

        if (!empty($editor_text)) {
            $widget->set_settings('editor', wp_kses_post($editor_text));
        }
    }

    /**
     * Get smart archive title based on current archive context
     * 
     * @return string The appropriate archive title
     */
    /**
     * Get the first term link for a post from a specific taxonomy
     * 
     * @param int $post_id The post ID
     * @param string $taxonomy The taxonomy name
     * @return string URL to the first term
     */
    private function get_first_term_link($post_id, $taxonomy)
    {
        $terms = get_the_terms($post_id, $taxonomy);

        if (!$terms || is_wp_error($terms)) {
            return '';
        }

        // Get the first term
        $term = reset($terms);

        return get_term_link($term);
    }

    /**
     * Get taxonomy terms for a post as a formatted list
     * 
     * @param int $post_id The post ID
     * @param array $settings Widget settings
     * @return string Formatted list of terms
     */
    private function get_taxonomy_terms_list($post_id, $settings)
    {
        // Get the selected taxonomy
        $taxonomy = isset($settings['taxonomy_type']) ? $settings['taxonomy_type'] : 'category';

        // Get separator
        $separator = isset($settings['term_separator']) ? $settings['term_separator'] : ', ';

        // Get max terms
        $max_terms = isset($settings['max_terms']) ? intval($settings['max_terms']) : 5;

        // Get link terms setting - always link them individually if selected
        $link_terms = isset($settings['link_terms']) && 'yes' === $settings['link_terms'];

        // Get the terms
        $terms = get_the_terms($post_id, $taxonomy);

        if (!$terms || is_wp_error($terms)) {
            return '';
        }

        // Limit number of terms to display
        $terms = array_slice($terms, 0, $max_terms);

        $term_list = [];

        foreach ($terms as $term) {
            if ($link_terms) {
                $term_list[] = '<a href="' . get_term_link($term) . '">' . $term->name . '</a>';
            } else {
                $term_list[] = $term->name;
            }
        }

        return implode($separator, $term_list);
    }

    /**
     * Get all registered taxonomies as options
     * 
     * @return array Array of taxonomies
     */
    private function get_registered_taxonomies()
    {
        $options = [];

        // Get all taxonomies
        $taxonomies = get_taxonomies(['public' => true], 'objects');

        foreach ($taxonomies as $taxonomy) {
            $options[$taxonomy->name] = $taxonomy->label;
        }

        return $options;
    }

    /**
     * Get the archive description for the current archive
     * 
     * @return string The archive description
     */
    private function get_archive_description()
    {
        $description = '';

        // WooCommerce Shop Page
        if (function_exists('is_shop') && is_shop()) {
            // Get the shop page description
            $shop_page_id = wc_get_page_id('shop');
            $description = get_post_field('post_content', $shop_page_id);
        }
        // Product Category
        elseif (function_exists('is_product_category') && is_product_category()) {
            $description = term_description();
        }
        // Product Tag
        elseif (function_exists('is_product_tag') && is_product_tag()) {
            $description = term_description();
        }
        // Regular Category Archive
        elseif (is_category()) {
            $description = category_description();
        }
        // Regular Tag Archive
        elseif (is_tag()) {
            $description = tag_description();
        }
        // Custom Taxonomy
        elseif (is_tax()) {
            $description = term_description();
        }
        // Author Archive
        elseif (is_author()) {
            $author_id = get_queried_object_id();
            $description = get_the_author_meta('description', $author_id);
        }
        // Post Type Archive
        elseif (is_post_type_archive()) {
            // Try to get post type description if available
            $post_type = get_queried_object();
            if ($post_type && isset($post_type->description)) {
                $description = $post_type->description;
            }
        }

        return $description;
    }

    /**
     * Get the current term/taxonomy URL
     * 
     * @return string URL for the current term or archive
     */
    private function get_current_term_url()
    {
        $url = '';

        // WooCommerce Shop Page
        if (function_exists('is_shop') && is_shop()) {
            $url = get_permalink(wc_get_page_id('shop'));
        }
        // Product Category
        elseif (function_exists('is_product_category') && is_product_category()) {
            $url = get_term_link(get_queried_object());
        }
        // Product Tag
        elseif (function_exists('is_product_tag') && is_product_tag()) {
            $url = get_term_link(get_queried_object());
        }
        // Regular Category Archive
        elseif (is_category()) {
            $url = get_category_link(get_queried_object_id());
        }
        // Regular Tag Archive
        elseif (is_tag()) {
            $url = get_tag_link(get_queried_object_id());
        }
        // Custom Taxonomy
        elseif (is_tax()) {
            $url = get_term_link(get_queried_object());
        }
        // Author Archive
        elseif (is_author()) {
            $url = get_author_posts_url(get_queried_object_id());
        }
        // Date Archive
        elseif (is_date()) {
            $url = get_permalink();
        }
        // Search Results
        elseif (is_search()) {
            $url = get_search_link(get_search_query());
        }
        // Post Type Archive
        elseif (is_post_type_archive()) {
            $url = get_post_type_archive_link(get_queried_object()->name);
        }
        // Default Archive (fallback)
        else {
            $url = get_permalink();
        }

        return $url;
    }

    /**
     * Get smart archive title based on current archive context
     * 
     * @return string The appropriate archive title
     */
    private function get_smart_archive_title()
    {
        $title = '';

        // WooCommerce Shop Page
        if (function_exists('is_shop') && is_shop()) {
            $title = get_the_title(wc_get_page_id('shop'));
        }
        // Product Category
        elseif (function_exists('is_product_category') && is_product_category()) {
            $title = single_term_title('', false);
        }
        // Product Tag
        elseif (function_exists('is_product_tag') && is_product_tag()) {
            $title = single_term_title('', false);
        }
        // Regular Category Archive
        elseif (is_category()) {
            $title = single_cat_title('', false);
        }
        // Regular Tag Archive
        elseif (is_tag()) {
            $title = single_tag_title('', false);
        }
        // Custom Taxonomy
        elseif (is_tax()) {
            $title = single_term_title('', false);
        }
        // Author Archive
        elseif (is_author()) {
            $title = get_the_author();
        }
        // Date Archive
        elseif (is_date()) {
            if (is_day()) {
                $title = get_the_date();
            } elseif (is_month()) {
                $title = get_the_date('F Y');
            } elseif (is_year()) {
                $title = get_the_date('Y');
            }
        }
        // Search Results
        elseif (is_search()) {
            $title = sprintf(__('Search Results for: %s', 'kavehTheme'), get_search_query());
        }
        // Post Type Archive
        elseif (is_post_type_archive()) {
            $title = post_type_archive_title('', false);
        }
        // Default Archive (fallback)
        else {
            $title = get_the_archive_title();
        }

        return $title;
    }

    /**
     * Process dynamic heading content
     * 
     * @param object $widget The Elementor widget
     * @param array $settings Widget settings
     */
    private function process_dynamic_heading($widget, $settings)
    {
        if (empty($settings['use_dynamic_heading']) || 'yes' !== $settings['use_dynamic_heading']) {
            return;
        }

        // Get the current post ID in the loop
        $post_id = $this->get_current_post_id($widget);
        $heading_text = '';
        $dynamic_link = '';

        // Get author ID
        global $post;
        $author_id = isset($post->post_author) ? $post->post_author : 0;

        // Process heading text
        switch ($settings['dynamic_heading_source']) {
            case 'post_title':
                $heading_text = get_the_title($post_id);
                break;

            case 'custom_field':
                if (!empty($settings['heading_custom_field'])) {
                    $heading_text = get_post_meta($post_id, $settings['heading_custom_field'], true);
                }
                break;

            case 'author_meta':
                if (!empty($settings['author_meta_field']) && $author_id) {
                    $heading_text = get_the_author_meta($settings['author_meta_field'], $author_id);
                }
                break;

            case 'site_title':
                $heading_text = get_bloginfo('name');
                break;

            case 'post_date':
                $heading_text = get_the_date();
                break;

            case 'archive_title':
                // Smart archive title detection
                $heading_text = $this->get_smart_archive_title();
                break;

            case 'taxonomy_terms':
                // Get taxonomy terms - always with their links by default
                $heading_text = $this->get_taxonomy_terms_list($post_id, $settings);
                // Since each term has its own link, disable global link for the heading
                $widget->set_settings('link', ['url' => '']);
                // Set the title with HTML links included
                $widget->set_settings('title', $heading_text);
                // Enable HTML in the title
                $widget->add_render_attribute('title', 'class', 'elementor-inline-editing');
                break;
        }

        // Process dynamic link if enabled and not taxonomy_terms source (which handles its own links)
        if (
            !empty($settings['use_dynamic_link']) && 'yes' === $settings['use_dynamic_link'] &&
            $settings['dynamic_heading_source'] !== 'taxonomy_terms'
        ) {

            switch ($settings['dynamic_link_source']) {
                case 'post_url':
                    $dynamic_link = get_permalink($post_id);
                    break;

                case 'custom_field':
                    if (!empty($settings['link_custom_field'])) {
                        $dynamic_link = get_post_meta($post_id, $settings['link_custom_field'], true);
                    }
                    break;

                case 'author_url':
                    $dynamic_link = get_author_posts_url($author_id);
                    break;

                case 'home_url':
                    $dynamic_link = home_url();
                    break;

                case 'term_url':
                    $dynamic_link = $this->get_current_term_url();
                    break;

                case 'taxonomy_term':
                    $taxonomy = isset($settings['taxonomy_link_source']) ? $settings['taxonomy_link_source'] : 'category';
                    $dynamic_link = $this->get_first_term_link($post_id, $taxonomy);
                    break;
            }
        }

        // Update heading text and link
        if (!empty($heading_text)) {
            // For taxonomy terms, the heading_text already contains HTML links
            // and the title has already been set in the switch statement above
            if ($settings['dynamic_heading_source'] !== 'taxonomy_terms') {
                // Set regular title
                $widget->set_settings('title', $heading_text);

                // Update link if dynamic link is enabled and not empty
                if (!empty($dynamic_link)) {
                    $widget->set_settings('link', [
                        'url' => $dynamic_link,
                        'is_external' => false,
                        'nofollow' => false,
                    ]);
                }
            }
        }
    }
}