<?php
final class kavehTheme
{

    public $options;

    public function __construct()
    {

        $this->options = kaveh_get_options();
        add_action('after_setup_theme', array($this, 'kaveh_setup'));
        add_action('init', array($this, 'kaveh_pr_tax_brand'));
        add_action('admin_init', array($this, 'kaveh_load_translations'));
        add_action('admin_enqueue_scripts', array($this, 'kaveh_admin_styles'));
        add_action('elementor/editor/after_enqueue_styles', array($this, 'kaveh_admin_styles'));
        add_action('login_enqueue_scripts', array($this, 'kaveh_login_styles'));
        add_action('login_enqueue_scripts', array($this, 'kaveh_login_logo'));
        add_filter('excerpt_length', array($this, 'my_excerpt_length'));
        add_action('wp_nav_menu_item_custom_fields', array($this, 'menu_item_desc'), 10, 2);
        add_action('wp_update_nav_menu_item', array($this, 'save_menu_item_desc'), 10, 2);
        add_action('wp_logout', array($this, 'auto_redirect_after_logout'));
        add_action('kelementor_inline_scripts', [$this, 'kelementor_inline_scripts']);
        add_filter('wp_lazy_loading_enabled', '__return_false');
        add_filter('wp_get_attachment_image_attributes', [$this, 'disable_lazy_load_featured_images']);
        add_action('kaveh_before_header', [$this, 'kaveh_announcement_banner']);
        add_action('admin_head', [$this, 'custom_admin_styles']);
        add_action('wp_head', [$this, 'kaveh_header_code']);
        add_action('wp_footer', [$this, 'kaveh_footer_code']);
        add_action('template_redirect', [$this, 'kaveh_ag_themer_preview']);
        add_filter('comment_form_default_fields', [$this, 'custom_comment_form_fields']);

        if (class_exists('woocommerce')) {
            if (is_product()) {
                add_action('wp_enqueue_scripts', [$this, 'enqueue_gutenberg_styles']);
            }

        }
        if (is_single()) {
            add_action('wp_enqueue_scripts', [$this, 'enqueue_gutenberg_styles']);
        }

        add_action( 'tgmpa_register',  [$this , 'kaveh_register_required_plugins'] );
        add_action('wp_footer', [$this ,'show_nav_responsive']);
    }

    public function show_nav_responsive()
    {
        get_template_part('template-part/nav-responsive');
        get_template_part('template-part/footer-mobile');

    }


    public function kaveh_register_required_plugins() {
        /*
        * Array of plugin arrays. Required keys are name and slug.
        * If the source is NOT from the .org repo, then source is also required.
        */
        $plugins = array(
            array(
                'name'     => esc_html__( 'Kaveh Demo Importer', 'kavehTheme' ),
                'slug'     => 'easy-demo-importer',
                'required' => false,
            ),
         
            array(
                'name'     => esc_html__( 'WooCommerce Plugin', 'kavehTheme' ),
                'slug'     => 'woocommerce',
                'required' => false,
            ),
            array(
                'name'     => esc_html__( 'Elementor Plugin', 'kavehTheme' ),
                'slug'     => 'elementor',
                'required' => false,
            ),
            array(
                'name'     => esc_html__( 'Kaveh Elementor Mega Menu Builder', 'kavehTheme' ),
                'slug'     => 'boostify-header-footer-builder',
                'required' => false,
            ),
       

        );

        tgmpa( $plugins );
    }

    public function enqueue_gutenberg_styles()
    {
        // Enqueue the main Gutenberg CSS
        wp_enqueue_style(
            'kaveh-gutenberg-style',
            get_theme_file_uri('/assets/css/gutenberg.css'),
            array(),
            wp_get_theme()->get('Version')
        );

        // Enqueue the default WordPress block styles
        wp_enqueue_style('wp-block-library');
        wp_enqueue_style('wp-block-library-theme');
    }


    public static function custom_comment_template($comment, $args, $depth)
    {
        // Get the rating value from the comment metadata
        $rating = get_comment_meta($comment->comment_ID, 'rating', true);
        $rating = !empty($rating) ? intval($rating) : 0; // Ensure the rating is an integer

        ?>
        <li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
            <div class="content">
                <div class="info d-flex align-items-center flex-column flex-sm-row">
                    <?php echo get_avatar($comment, 64, '', '', array('class' => 'rounded-circle text-center mb-3 mb-sm-0')); ?>
                    <div class="detail d-flex align-items-center justify-content-between flex-column flex-sm-row">
                        <div class="author-date text-center text-sm-right">
                            <div class="author"><?php comment_author(); ?></div>
                            <div class="date">
                                <?php
                                $date = get_comment_date('Y/n/j');
                                $persian_numbers = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'); // Keep Persian numbers for conversion
                                $english_numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
                                echo str_replace($english_numbers, $persian_numbers, $date);
                                ?>
                            </div>
                        </div>
                        <div class="star-position d-flex align-items-center flex-column flex-sm-row">
                            <div class="star d-flex align-items-center">
                                <?php
                                // Render stars based on the rating value
                                for ($i = 1; $i <= 5; $i++) {
                                    $star_class = ($i <= $rating) ? 'active' : '';
                                    echo '<i class="icon-star ' . $star_class . '"></i>';
                                }
                                ?>
                            </div>
                            <?php
                            comment_reply_link(array_merge($args, array(
                                'reply_text' => esc_html__('Reply', 'kavehTheme'), // Text for the reply link
                                'depth' => $depth, // Current depth of the comment
                                'max_depth' => $args['max_depth'], // Maximum depth allowed
                                'add_below' => 'comment', // ID prefix for the reply form
                                'before' => '<div class="position rounded-pill">', // HTML before the link
                                'after' => '</div>', // HTML after the link
                            )));
                            ?>
                        </div>
                    </div>
                </div>
                <div class="box">
                    <?php comment_text(); ?>
                </div>
            </div>
            <?php
    }


    public function custom_comment_form_fields($fields)
    {
        // Check if WooCommerce is active and if the current page is a product page
        if (class_exists('WooCommerce') && is_product()) {
            // Add the rating field
            $fields['rating'] = '<div class="col-12">
                                <div class="form-group position-relative">
                                    <label for="rating">' . esc_html__('Your Rating', 'kavehTheme') . '</label>
                                    <select name="rating" id="rating" class="form-control rounded-pill">
                                        <option value="">' . esc_html__('Rate&hellip;', 'kavehTheme') . '</option>
                                        <option value="5">' . esc_html__('Perfect', 'kavehTheme') . '</option>
                                        <option value="4">' . esc_html__('Good', 'kavehTheme') . '</option>
                                        <option value="3">' . esc_html__('Average', 'kavehTheme') . '</option>
                                        <option value="2">' . esc_html__('Not that bad', 'kavehTheme') . '</option>
                                        <option value="1">' . esc_html__('Very poor', 'kavehTheme') . '</option>
                                    </select>
                                </div>
                            </div>';
        }

        // Add the default fields
        $fields['author'] = '<div class="col-12">
                            <div class="form-group position-relative">
                                <label for="author">' . esc_html__('Your Name', 'kavehTheme') . '</label>
                                <input type="text" name="author" id="author" class="form-control rounded-pill" />
                            </div>
                        </div>';

        $fields['email'] = '<div class="col-12">
                            <div class="form-group position-relative">
                                <label for="email">' . esc_html__('Your Email', 'kavehTheme') . '</label>
                                <input type="email" name="email" id="email" class="form-control rounded-pill" />
                            </div>
                        </div>';

        $fields['url'] = '<div class="col-12">
                        <div class="form-group position-relative">
                            <label for="url">' . esc_html__('Your Website', 'kavehTheme') . '</label>
                            <input type="url" name="url" id="url" class="form-control rounded-pill" />
                        </div>
                    </div>';

        return $fields;
    }
    public function kaveh_ag_themer_preview()
    {
        // Check if it's Elementor preview mode
        if ((isset($_GET['preview'])) && ($_GET['preview'] === 'true') && (isset($_GET['post_type']) && ($_GET['post_type'] === 'ag-themer'))) {
            // Get the latest WooCommerce product
            $latest_product = wc_get_products([
                'limit' => 1,
                'orderby' => 'date',
                'order' => 'DESC',
            ]);

            // Redirect to the latest product URL if a product exists
            if (!empty($latest_product)) {
                wp_redirect(get_permalink($latest_product[0]->get_id()));
                exit;
            }
        }
    }


    public function custom_admin_styles()
    {
        echo '<style>
            body.wp-admin.toplevel_page_kaveh-options{
                background: linear-gradient(90deg, #ff9966 0%, #ff5e62 100%) !important;
            }
        </style>';
    }


    public static function kaveh_has_sub_menu(array $menu_items, int $id): bool
    {
        foreach ($menu_items as $menu_item) {
            if ((int) $menu_item->menu_item_parent === $id) {
                return true;
            }
        }
        return false;
    }

    public static function render_menu_items($items, $parent_id = 0, $level = 1, $render_callback)
    {
        foreach ($items as $item) {
            if ($item->menu_item_parent == $parent_id) {
                $render_callback($item, $items, $level);
            }
        }
    }


    public static function render_menu_item_type_1($menu_item, $menu_items, $level)
    {
        $nav_meta = get_post_meta($menu_item->ID);
        $icon_class = isset($nav_meta['_menu_item_desc'][0]) ? $nav_meta['_menu_item_desc'][0] : '';
        $has_children = self::kaveh_has_sub_menu($menu_items, $menu_item->ID);

        echo '<li' . ($has_children ? ' class="has-child"' : '') . '>';
        echo '<a href="' . $menu_item->url . '" class="d-block rounded-pill">';
        echo '<i class="' . $icon_class . '"></i>' . $menu_item->title;
        if ($has_children) {
            echo '<i class="icon-angle-left position-absolute top-50 translate-middle-y m-0"></i>';
        }
        echo '</a>';
        if ($has_children) {
            echo '<div class="children position-fixed top-0 start-0 w-100 h-100 bg-white">';
            echo '<div class="heading px-3 py-4 d-flex align-items-center justify-content-between">';
            echo $menu_item->title;
            echo '<button type="button" class="nav-responsive-back rounded-circle d-flex align-items-center justify-content-center text-white mb-0">';
            echo '<i class="icon-arrow-left-2"></i>';
            echo '</button>';
            echo '</div>';
            echo '<ul>';
            self::render_menu_items($menu_items, $menu_item->ID, $level + 1, ['kavehTheme', 'render_menu_item_type_1']);
            echo '</ul>';
            echo '</div>';
        }
        echo '</li>';
    }

    public static function render_menu_item_type_2($menu_item, $menu_items, $level)
    {
        $nav_meta = get_post_meta($menu_item->ID);
        $icon_class = isset($nav_meta['_menu_item_desc'][0]) ? $nav_meta['_menu_item_desc'][0] : '';
        $has_children = self::kaveh_has_sub_menu($menu_items, $menu_item->ID);

        echo '<li' . ($has_children ? ' class="has-child arrow-left"' : '') . '>';
        echo '<a href="' . $menu_item->url . '" class="d-flex align-items-center">';
        echo '<i class="' . $icon_class . '"></i>' . $menu_item->title;
        echo '</a>';
        if ($has_children) {
            echo '<ul class="position-absolute top-0 left-0 bg-white">';
            echo '<li class="back d-flex align-items-center justify-content-between">';
            echo esc_html__('Back', 'kavehTheme');
            echo '<i class="icon-arrow-left-5 d-flex align-items-center justify-content-center text-white"></i>';
            echo '</li>';
            self::render_menu_items($menu_items, $menu_item->ID, $level + 1, ['kavehTheme', 'render_menu_item_type_2']);
            echo '</ul>';
        }
        echo '</li>';
    }


    public function kaveh_announcement_banner()
    {
        if (class_exists('woocommerce')) {

            if (is_cart() || is_checkout()) {
                return;
            }
        }
        ?>
            <?php if ($this->options['kaveh_announcement_banner'] === '1'): ?>
                <?php if (wp_is_mobile()): ?>
                    <a href="<?php echo $this->options['kaveh_announcement_banner_link']; ?>">
                        <img src="<?php echo $this->options['kaveh_announcement_banner_image_mobile']; ?>" alt="announcement">
                    </a>
                <?php else: ?>
                    <a href="<?php echo $this->options['kaveh_announcement_banner_link']; ?>">
                        <img src="<?php echo $this->options['kaveh_announcement_banner_image']; ?>" alt="announcement">
                    </a>
                <?php endif; ?>
            <?php endif; ?>
            <?php
    }

    public function disable_lazy_load_featured_images($attr, $attachment = null)
    {
        $attr['loading'] = 'eager';
        return $attr;
    }


    public function kelementor_inline_scripts()
    {
        if (\Elementor\Plugin::$instance->editor->is_edit_mode()):
            ?>
                <script>
                    jQuery(document).ready(function () {
                        // call init function
                        initSwipers();
                        function initSwipers(selector = "[data-swiper]") {
                            let swipers = document.querySelectorAll(selector);
                            swipers.forEach((swiper) => {
                                // get options
                                let optionsData = swiper.dataset.swiper
                                    ? JSON.parse(swiper.dataset.swiper)
                                    : {};
                                // init
                                new Swiper(swiper, optionsData);
                            });
                        }
                        const tabs = document.querySelectorAll('[data-bs-toggle="tab"]')
                        tabs.forEach(tab => {
                            tab.addEventListener('click', (ev) => {
                                setTimeout(() => {
                                    initSwipers();
                                }, 10);
                            })
                        })
                    })
                </script>
                <?php
        endif;
    }


    public function kaveh_setup()
    {
        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         */

        //boostify support
        add_theme_support('boostify-header-footer');

        // Add default posts and comments RSS feed links to head.
        add_theme_support('automatic-feed-links');

        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support('title-tag');

        /*
         * Enable support for Post Thumbnails on posts and pages.
         *
         * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
         */
        add_theme_support('post-thumbnails');

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support(
            'html5',
            array(
                'search-form',
                'comment-form',
                'comment-list',
                'gallery',
                'caption',
                'style',
                'script',
            )
        );

        add_theme_support('woocommerce');
        add_theme_support('wp-block-styles');
        add_editor_style('style.css');
        add_theme_support('editor-styles');


        // Add support for Gutenberg wide and full-width blocks
        add_theme_support('align-wide');

        // Add support for responsive embeds
        add_theme_support('responsive-embeds');

        // Add support for custom line heights
        add_theme_support('custom-line-height');

        // Add support for custom units
        add_theme_support('custom-units');

        // Add support for editor font sizes
        add_theme_support('editor-font-sizes', array(
            array(
                'name' => __('Small', 'kavehTheme'),
                'size' => 12,
                'slug' => 'small'
            ),
            array(
                'name' => __('Normal', 'kavehTheme'),
                'size' => 16,
                'slug' => 'normal'
            ),
            array(
                'name' => __('Medium', 'kavehTheme'),
                'size' => 20,
                'slug' => 'medium'
            ),
            array(
                'name' => __('Large', 'kavehTheme'),
                'size' => 36,
                'slug' => 'large'
            ),
            array(
                'name' => __('Huge', 'kavehTheme'),
                'size' => 48,
                'slug' => 'huge'
            )
        ));


        // Register Store Sidebar
        register_sidebar(
            array(
                'name' => __('Shop Sidebar', 'kavehTheme'),
                'id' => 'shop',
            )
        );

        // Register Blog Sidebar
        register_sidebar(
            array(
                'name' => __('Blog Sidebar', 'kavehTheme'),
                'id' => 'blog',
            )
        );

        // Register Menus
        register_nav_menus(
            array(
                'primary' => __('Primary Menu', 'kavehTheme'),
                'social' => __('Social Links Menu', 'kavehTheme'),
            )
        );

    }

    public function kaveh_pr_tax_brand()
    {

        register_taxonomy(
            'brands',
            'product',
            array(
                'label' => __('Brand', 'kavehTheme'),
                'hierarchical' => true,
            )
        );

    }

    public function my_excerpt_length($length)
    {
        return 50;
    }

    public static function get_breadcrumb()
    {
        // Check for RankMath SEO breadcrumbs first
        if (function_exists('rank_math_the_breadcrumbs')) {
            return rank_math_the_breadcrumbs();
        }
        
        // Check for Yoast SEO breadcrumbs
        if (function_exists('yoast_breadcrumb')) {
            return yoast_breadcrumb('<ul class="breadcrumb"><li>', '</li></ul>', false);
        }
        
        // Check for Breadcrumb NavXT
        if (function_exists('bcn_display')) {
            return '<ul class="breadcrumb">' . bcn_display(true) . '</ul>';
        }
        
        // Fallback to custom breadcrumb implementation
        return self::generate_custom_breadcrumb();
    }
    
    private static function generate_custom_breadcrumb()
    {
        $breadcrumb_items = [];
        $separator = ' / ';
        
        // Always add home link (except on front page)
        if (!is_front_page()) {
            $breadcrumb_items[] = [
                'url' => home_url('/'),
                'text' => esc_html__('Home', 'kavehTheme'),
            ];
        }
        
        // Handle different page types
        if (is_front_page()) {
            // Front page - just show "Home"
            $breadcrumb_items[] = [
                'text' => esc_html__('Home', 'kavehTheme'),
            ];
        } elseif (is_home() && !is_front_page()) {
            // Blog page
            $blog_page_id = get_option('page_for_posts');
            if ($blog_page_id) {
                $breadcrumb_items[] = [
                    'text' => get_the_title($blog_page_id),
                ];
            } else {
                $breadcrumb_items[] = [
                    'text' => esc_html__('Blog', 'kavehTheme'),
                ];
            }
        } elseif (function_exists('is_shop') && is_shop()) {
            // WooCommerce shop page
            $breadcrumb_items[] = [
                'text' => esc_html__('Shop', 'kavehTheme'),
            ];
        } elseif (is_product_category() || is_product_tag()) {
            // WooCommerce product category/tag
            if (function_exists('wc_get_page_id')) {
                $shop_page_id = wc_get_page_id('shop');
                if ($shop_page_id && $shop_page_id > 0) {
                    $breadcrumb_items[] = [
                        'url' => get_permalink($shop_page_id),
                        'text' => get_the_title($shop_page_id),
                    ];
                }
            }
            
            $current_term = get_queried_object();
            if ($current_term && !is_wp_error($current_term)) {
                // Add parent categories
                $taxonomy = is_product_category() ? 'product_cat' : 'product_tag';
                $ancestors = get_ancestors($current_term->term_id, $taxonomy);
                $ancestors = array_reverse($ancestors);
                
                foreach ($ancestors as $ancestor_id) {
                    $ancestor_term = get_term($ancestor_id, $taxonomy);
                    if ($ancestor_term && !is_wp_error($ancestor_term)) {
                        $breadcrumb_items[] = [
                            'url' => get_term_link($ancestor_term),
                            'text' => $ancestor_term->name,
                        ];
                    }
                }
                
                // Add current term
                $breadcrumb_items[] = [
                    'text' => $current_term->name,
                ];
            }
        } elseif (is_single() && get_post_type() === 'product') {
            // Single product page
            if (function_exists('wc_get_page_id')) {
                $shop_page_id = wc_get_page_id('shop');
                if ($shop_page_id && $shop_page_id > 0) {
                    $breadcrumb_items[] = [
                        'url' => get_permalink($shop_page_id),
                        'text' => get_the_title($shop_page_id),
                    ];
                }
            }
            
            // Add product categories
            $terms = wp_get_post_terms(get_the_ID(), 'product_cat');
            if (!empty($terms) && !is_wp_error($terms)) {
                $main_term = $terms[0]; // Use first category
                
                // Add parent categories
                $ancestors = get_ancestors($main_term->term_id, 'product_cat');
                $ancestors = array_reverse($ancestors);
                
                foreach ($ancestors as $ancestor_id) {
                    $ancestor_term = get_term($ancestor_id, 'product_cat');
                    if ($ancestor_term && !is_wp_error($ancestor_term)) {
                        $breadcrumb_items[] = [
                            'url' => get_term_link($ancestor_term),
                            'text' => $ancestor_term->name,
                        ];
                    }
                }
                
                // Add main category
                $breadcrumb_items[] = [
                    'url' => get_term_link($main_term),
                    'text' => $main_term->name,
                ];
            }
            
            // Add product title
            $breadcrumb_items[] = [
                'text' => get_the_title(),
            ];
        } elseif (is_single()) {
            // Single post
            $post_type = get_post_type();
            
            if ($post_type === 'post') {
                // Regular blog post
                $blog_page_id = get_option('page_for_posts');
                if ($blog_page_id) {
                    $breadcrumb_items[] = [
                        'url' => get_permalink($blog_page_id),
                        'text' => get_the_title($blog_page_id),
                    ];
                }
                
                // Add categories
                $categories = get_the_category();
                if (!empty($categories)) {
                    $main_category = $categories[0];
                    
                    // Add parent categories
                    $ancestors = get_ancestors($main_category->term_id, 'category');
                    $ancestors = array_reverse($ancestors);
                    
                    foreach ($ancestors as $ancestor_id) {
                        $ancestor_term = get_term($ancestor_id, 'category');
                        if ($ancestor_term && !is_wp_error($ancestor_term)) {
                            $breadcrumb_items[] = [
                                'url' => get_category_link($ancestor_term->term_id),
                                'text' => $ancestor_term->name,
                            ];
                        }
                    }
                    
                    $breadcrumb_items[] = [
                        'url' => get_category_link($main_category->term_id),
                        'text' => $main_category->name,
                    ];
                }
            } else {
                // Custom post type
                $post_type_object = get_post_type_object($post_type);
                if ($post_type_object && $post_type_object->public) {
                    $breadcrumb_items[] = [
                        'url' => get_post_type_archive_link($post_type),
                        'text' => $post_type_object->labels->name,
                    ];
                }
            }
            
            // Add post title
            $breadcrumb_items[] = [
                'text' => get_the_title(),
            ];
        } elseif (is_page()) {
            // Static page
            $post_id = get_the_ID();
            $post = get_post($post_id);
            
            if ($post && $post->post_parent) {
                $ancestors = get_post_ancestors($post_id);
                $ancestors = array_reverse($ancestors);
                
                foreach ($ancestors as $ancestor_id) {
                    $breadcrumb_items[] = [
                        'url' => get_permalink($ancestor_id),
                        'text' => get_the_title($ancestor_id),
                    ];
                }
            }
            
            $breadcrumb_items[] = [
                'text' => get_the_title(),
            ];
        } elseif (is_category()) {
            // Category archive
            $current_category = get_queried_object();
            
            if ($current_category) {
                // Add parent categories
                $ancestors = get_ancestors($current_category->term_id, 'category');
                $ancestors = array_reverse($ancestors);
                
                foreach ($ancestors as $ancestor_id) {
                    $ancestor_term = get_term($ancestor_id, 'category');
                    if ($ancestor_term && !is_wp_error($ancestor_term)) {
                        $breadcrumb_items[] = [
                            'url' => get_category_link($ancestor_term->term_id),
                            'text' => $ancestor_term->name,
                        ];
                    }
                }
                
                $breadcrumb_items[] = [
                    'text' => $current_category->name,
                ];
            }
        } elseif (is_tag()) {
            // Tag archive
            $current_tag = get_queried_object();
            if ($current_tag) {
                $breadcrumb_items[] = [
                    /* translators: %s: tag name */
                    'text' => sprintf(esc_html__('Tag: %s', 'kavehTheme'), $current_tag->name),
                ];
            }
        } elseif (is_author()) {
            // Author archive
            $author = get_queried_object();
            if ($author) {
                $breadcrumb_items[] = [
                    /* translators: %s: author display name */
                    'text' => sprintf(esc_html__('Author: %s', 'kavehTheme'), $author->display_name),
                ];
            }
        } elseif (is_date()) {
            // Date archive
            if (is_year()) {
                $breadcrumb_items[] = [
                    'text' => get_the_date('Y'),
                ];
            } elseif (is_month()) {
                $breadcrumb_items[] = [
                    'url' => get_year_link(get_the_date('Y')),
                    'text' => get_the_date('Y'),
                ];
                $breadcrumb_items[] = [
                    'text' => get_the_date('F'),
                ];
            } elseif (is_day()) {
                $breadcrumb_items[] = [
                    'url' => get_year_link(get_the_date('Y')),
                    'text' => get_the_date('Y'),
                ];
                $breadcrumb_items[] = [
                    'url' => get_month_link(get_the_date('Y'), get_the_date('m')),
                    'text' => get_the_date('F'),
                ];
                $breadcrumb_items[] = [
                    'text' => get_the_date('j'),
                ];
            }
        } elseif (is_search()) {
            // Search results
            $breadcrumb_items[] = [
                /* translators: %s: search query */
                'text' => sprintf(esc_html__('Search Results for: %s', 'kavehTheme'), get_search_query()),
            ];
        } elseif (is_404()) {
            // 404 page
            $breadcrumb_items[] = [
                'text' => esc_html__('404 Not Found', 'kavehTheme'),
            ];
        }
        
        // Generate HTML output
        if (!empty($breadcrumb_items)) {
            $output = '<ul class="breadcrumb">';
            
            foreach ($breadcrumb_items as $index => $item) {
                $text = esc_html($item['text']);
                
                if (isset($item['url']) && !empty($item['url'])) {
                    $url = esc_url($item['url']);
                    $output .= '<li><a href="' . $url . '">' . $text . '</a></li>';
                } else {
                    $output .= '<li>' . $text . '</li>';
                }
            }
            
            $output .= '</ul>';
            return $output;
        }
        
        return '';
    }

    public function save_menu_item_desc($menu_id, $menu_item_db_id)
    {
        if (isset($_POST['menu_item_desc'][$menu_item_db_id])) {
            $sanitized_data = sanitize_text_field($_POST['menu_item_desc'][$menu_item_db_id]);
            update_post_meta($menu_item_db_id, '_menu_item_desc', $sanitized_data);
        } else {
            delete_post_meta($menu_item_db_id, '_menu_item_desc');
        }
    }

    public function menu_item_desc($item_id, $item)
    {
        $menu_item_desc = get_post_meta($item_id, '_menu_item_desc', true);
        ?>
            <div style="clear: both;">
                <span class="description"><?php _e("Mobile Menu Icon Code", 'kavehTheme'); ?></span><br />
                <input type="hidden" class="nav-menu-id" value="<?php echo $item_id; ?>" />
                <div class="logged-input-holder">
                    <input class="widefat" type="text" name="menu_item_desc[<?php echo $item_id; ?>]"
                        id="menu-item-desc-<?php echo $item_id; ?>" value="<?php echo esc_attr($menu_item_desc); ?>" />
                </div>
            </div>
            <?php
    }

    public function kaveh_load_translations()
    {
        if (!is_admin()) {
            return;
        }
        if (is_rtl()) {
            // Handle plugin translations
            $plugin_text_domain = 'easy-demo-importer';
            $plugin_translation_file = KAVEH_TEMPLATE_PATH . "/inc/plugins/languages/{$plugin_text_domain}-fa_IR.mo";
            $plugin_destination_path = WP_LANG_DIR . '/plugins/';
            
            // Create the destination directory if it doesn't exist
            if (!is_dir($plugin_destination_path)) {
                wp_mkdir_p($plugin_destination_path);
            }
            
            // Copy the plugin translation file
            if (file_exists($plugin_translation_file)) {
                $plugin_destination_file = $plugin_destination_path . basename($plugin_translation_file);
                // Check if destination file doesn't exist or source file is newer
                if (!file_exists($plugin_destination_file) || filemtime($plugin_translation_file) > filemtime($plugin_destination_file)) {
                    copy($plugin_translation_file, $plugin_destination_file);
                }
            }
            
            // Handle theme translations
            $theme_text_domain = 'kavehTheme';
            $theme_translation_file = KAVEH_TEMPLATE_PATH . "/languages/{$theme_text_domain}-fa_IR.mo";
            $theme_destination_path = WP_LANG_DIR . '/themes/';
            
            // Create the destination directory if it doesn't exist
            if (!is_dir($theme_destination_path)) {
                wp_mkdir_p($theme_destination_path);
            }
            
            // Copy the theme translation file
            if (file_exists($theme_translation_file)) {
                $theme_destination_file = $theme_destination_path . basename($theme_translation_file);
                // Check if destination file doesn't exist or source file is newer
                if (!file_exists($theme_destination_file) || filemtime($theme_translation_file) > filemtime($theme_destination_file)) {
                    copy($theme_translation_file, $theme_destination_file);
                }
            }
        }
    }

    public function kaveh_admin_styles()
    {
        if (is_rtl()) {
            wp_enqueue_style('kaveh-admin-styles', KAVEH_TEMPLATE_URI . '/assets/css/rtl/kaveh-admin-styles.css');
        } else {
            wp_enqueue_style('kaveh-admin-styles', KAVEH_TEMPLATE_URI . '/assets/css/ltr/kaveh-admin-styles.css');
        }
    }

    public function kaveh_login_styles()
    {
        if (is_rtl()) {
            wp_enqueue_style('kaveh-login-styles', KAVEH_TEMPLATE_URI . '/assets/css/rtl/kaveh-login-styles.css');
        } else {
            wp_enqueue_style('kaveh-login-styles', KAVEH_TEMPLATE_URI . '/assets/css/ltr/kaveh-login-styles.css');
        }

    }

    public function kaveh_login_logo()
    {
        $logo = $this->options['kaveh_logo_up'];
        $color = $this->options['opt-color-5'];
        $bglogin = $this->options['bglogin'];
        ?>
            <style type="text/css">
                body {
                    <?php if (empty($bglogin)): ?>
                        background-image: url("<?php echo KAVEH_TEMPLATE_URI . '/assets/images/bglogink.jpg'; ?>") !important;
                    <?php else: ?>
                        background-image: url("<?php echo $bglogin; ?>") !important;
                    <?php endif; ?>
                    overflow-y: hidden !important;
                    background-size: cover !important;
                }

                #login h1 a,
                .login h1 a {
                    background-image: url('<?php echo $logo; ?>');
                    max-height: 90px;
                    width: 150px;
                    background-size: contain;
                }

                .wp-core-ui .button-primary {
                    background:
                        <?php echo $color; ?>
                        !important;
                    border-color:
                        <?php echo $color; ?>
                        !important;
                }
            </style>;
            <?php
    }

    public function auto_redirect_after_logout()
    {
        wp_redirect(home_url());
        exit();
    }

    public function kaveh_header_code()
    {
        if (!empty($this->options['kaveh_header_code'])) {
            echo $this->options['kaveh_header_code'];
        }
    }

    public function kaveh_footer_code()
    {
        if (!empty($this->options['kaveh_footer_code'])) {
            echo $this->options['kaveh_footer_code'];
        }
        ?>
            <style>
                <?php
                if (!empty($this->options['kaveh_css_code'])) {
                    echo $this->options['kaveh_css_code'];
                }
                ?>
            </style>
            <script>
                <?php
                if (!empty($this->options['kaveh_js_code'])) {
                    echo $this->options['kaveh_js_code'];
                }
                ?>
            </script>
            <?php
    }

}