<?php
final class kavehTheme {

    public $options;

    public function __construct() {

        $this->options = get_option('kaveh_frame');
        add_action('after_setup_theme', array($this, 'kaveh_setup'));
        add_action('wp_head', array($this, 'kaveh_pingback_header'));
        add_action('init', array($this, 'kaveh_pr_tax_brand'));
        add_action('init', array($this, 'kaveh_load_translations'));
        add_action('admin_enqueue_scripts', 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']);

    }

    public function kaveh_announcement_banner(){
        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.
        */
        load_theme_textdomain( 'kavehTheme', get_template_directory() . '/languages' );
        
        // 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',
          )
        );
        
        //boostify support
        add_theme_support( 'boostify-header-footer' );

        // Overide templates from Version 6.7.0
        add_theme_support( 'woocommerce' );

           // Add support for block styles.
            add_theme_support( 'wp-block-styles' );

            // Enqueue editor styles.
            add_editor_style( 'style.css' );


        // Register Store Sidebar
        register_sidebar( array(
            'name'          => __( 'سایدبار فروشگاه', 'kaveh_theme' ),
            'id'            => 'shop',
        ) );

        // Register Blog Sidebar
        register_sidebar( array(
            'name'          => __( 'سایدبار بلاگ', 'kaveh_theme' ),
            'id'            => 'blog',
        ) );

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

    }

    public function kaveh_pingback_header() {
        if ( is_singular() && pings_open() ) {
          printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
        }
    }


    public function kaveh_pr_tax_brand() {
        
        register_taxonomy( 'brands', 'product', array(
            'label'        => __( 'برند', 'textdomain' ),
            'rewrite'      => array( 'slug' => 'brand' ),
            'hierarchical' => true,
        ) );
        
    }

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

    public static function get_breadcrumb() {
        $breadcrumb_items = [];
    
        if (!is_front_page()) {
            $breadcrumb_items[] = [
                'url' => home_url(),
                'text' => 'صفحه اصلی',
            ];
    
            if (function_exists('is_shop') && is_shop()) {
                $breadcrumb_items[] = [
                    'text' => 'محصولات',
                ];
            } elseif (class_exists( 'woocommerce' ) && is_product_category()) {
                $current_term = get_queried_object();
                $ancestors = array_reverse(get_ancestors($current_term->term_id, 'product_cat'));
                foreach($ancestors as $ancestor) {
                    $ancestor_term = get_term($ancestor, 'product_cat');
                    $breadcrumb_items[] = [
                        'url' => get_term_link($ancestor_term),
                        'text' => $ancestor_term->name,
                    ];
                }
                $breadcrumb_items[] = [
                    'text' => $current_term->name,
                ];
            } elseif (is_single() && get_post_type() == 'product') {
                $shop_page_url = get_permalink(get_option('woocommerce_shop_page_id'));
                $breadcrumb_items[] = [
                    'url' => $shop_page_url,
                    'text' => 'محصولات',
                ];
                $terms = wp_get_post_terms(get_the_ID(), 'product_cat');
                foreach ($terms as $term) {
                    $ancestors = array_reverse(get_ancestors($term->term_id, 'product_cat'));
                    foreach($ancestors as $ancestor) {
                        $ancestor_term = get_term($ancestor, 'product_cat');
                        $breadcrumb_items[] = [
                            'url' => get_term_link($ancestor_term),
                            'text' => $ancestor_term->name,
                        ];
                    }
                    $breadcrumb_items[] = [
                        'url' => get_term_link($term->term_id , 'product_cat'),
                        'text' => $term->name,
                    ];
                }
                $breadcrumb_items[] = [
                    'text' => get_the_title(),
                ];
            } elseif (is_category() || is_single()) {
                $category = get_the_category();
                if (!empty($category)) {
                    $category_link = get_category_link($category[0]->term_id);
                    $breadcrumb_items[] = [
                        'url' => $category_link,
                        'text' => $category[0]->name,
                    ];
                    if (is_single()) {
                        $breadcrumb_items[] = [
                            'text' => get_the_title(),
                        ];
                    }
                }
            } elseif (is_page()) {
                $post_id = get_the_ID();
                $post = get_post($post_id);
                if ($post->post_parent) {
                    $ancestors = get_post_ancestors($post_id);
                    $ancestors = array_reverse($ancestors);
                    foreach ($ancestors as $ancestor_id) {
                        $ancestor_title = get_the_title($ancestor_id);
                        $ancestor_url = get_permalink($ancestor_id);
                        $breadcrumb_items[] = [
                            'url' => $ancestor_url,
                            'text' => $ancestor_title,
                        ];
                    }
                }
                if (!is_front_page()) {
                    $breadcrumb_items[] = [
                        'text' => get_the_title(),
                    ];
                }
            }
        } else {
            $breadcrumb_items[] = [
                'text' => 'صفحه اصلی',
            ];
        }
    
        if (!empty($breadcrumb_items)) {
            echo '<ul class="breadcrumb">';
            foreach ($breadcrumb_items as $item) {
                $text = esc_html($item['text']);
                if (isset($item['url'])) {
                    $url = esc_url($item['url']);
                    echo '<li><a href="' . $url . '">' . $text . '</a></li>';
                } else {
                    echo '<li>' . $text . '</li>';
                }
            }
            echo '</ul>';
        }
    }

    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( "کد آیکون منوی موبایل", 'menu-item-desc' ); ?></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()) {
            // Define the text domain and source file in your theme
            $text_domain = 'hashthemes-demo-importer';
            $theme_translation_file = get_template_directory() . "/inc/plugins/languages/{$text_domain}-fa_IR.mo";
            // Define the destination path in wp-content/languages/plugins
            $destination_path = WP_LANG_DIR . '/plugins/';
            // Create the destination directory if it doesn't exist
            if (!is_dir($destination_path)) {
                wp_mkdir_p($destination_path);
            }
            // Copy the translation file from your theme to the wp-content directory
            if (file_exists($theme_translation_file)) {
                $destination_file = $destination_path . basename($theme_translation_file);
                copy($theme_translation_file, $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 static function isLocalEnvironment() {
        // You can modify this function according to your local environment setup.
        return ($_SERVER['SERVER_ADDR'] === '127.0.0.1' || $_SERVER['SERVER_NAME'] === 'localhost');
    }

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