<?php
/**
 * @package shop-zen
 */

defined( 'ABSPATH' ) || exit;


/**
* Footer
*/

if ( ! function_exists( 'shop_zen_footer_copyrights' ) ) :
function shop_zen_footer_copyrights() {
	?>
		<div class="footer-bottom">
            <p>
                <?php

                    $copyright_text = get_theme_mod( 'shop_zen_footer_copyright_text' );
                    	if ( ! empty( $copyright_text ) ) :
                    		echo esc_html( $copyright_text );
                    else :
                        echo date_i18n(
                            /* translators: Copyright date format, see https://secure.php.net/date */
                            _x( 'Y', 'copyright date format', 'shop-zen' )
                        );
                        ?>
                            <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php echo esc_html( get_bloginfo( 'name' ) ); ?></a>
                        <?php
                    endif;
                ?>
            </p>
        </div>
	<?php
}
endif;
add_action( 'shop_zen_action_footer', 'shop_zen_footer_copyrights' );


/**
* Custom excerpt length.
*/
if ( ! function_exists( 'shop_zen_my_excerpt_length' ) ) :
function shop_zen_my_excerpt_length($length) {
	if ( is_admin() ) :
		return $length;
	endif;
  	return absint(get_theme_mod( 'shop_zen_excerpt_length',70));
}
endif;
add_filter('excerpt_length', 'shop_zen_my_excerpt_length');


/**
  * Get Breadcrumbs Content
  */
if( !function_exists( 'shop_zen_get_breadcrumbs_content' ) ):
    function shop_zen_get_breadcrumbs_content() {
        if(!is_front_page()) :

            // Build breadcrumb items
            $breadcrumb_items = array();

            if ( is_single() ) {
                // Single post breadcrumb
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );

                $blog_page_id = get_option('page_for_posts');
                if ( $blog_page_id ) {
                    $breadcrumb_items[] = array( 'label' => get_the_title( $blog_page_id ), 'url' => get_permalink( $blog_page_id ) );
                } else {
                    $breadcrumb_items[] = array( 'label' => __( 'Journal', 'shop-zen' ), 'url' => home_url( '/' ) );
                }

                $categories = get_the_category();
                if ( !empty($categories) ) {
                    $category = $categories[0];
                    $breadcrumb_items[] = array( 'label' => $category->name, 'url' => get_category_link( $category->term_id ) );
                }

                $breadcrumb_items[] = array( 'label' => get_the_title(), 'url' => '' );

            } elseif ( is_category() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );

                $blog_page_id = get_option('page_for_posts');
                if ( $blog_page_id ) {
                    $breadcrumb_items[] = array( 'label' => get_the_title( $blog_page_id ), 'url' => get_permalink( $blog_page_id ) );
                }

                $breadcrumb_items[] = array( 'label' => single_cat_title( '', false ), 'url' => '' );

            } elseif ( is_home() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );

                $blog_page_id = get_option('page_for_posts');
                if ( $blog_page_id ) {
                    $breadcrumb_items[] = array( 'label' => get_the_title( $blog_page_id ), 'url' => '' );
                } else {
                    $breadcrumb_items[] = array( 'label' => __( 'Blog', 'shop-zen' ), 'url' => '' );
                }

            } elseif ( is_page() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );

                // Check for parent pages
                $parent_id = wp_get_post_parent_id( get_the_ID() );
                if ( $parent_id ) {
                    $breadcrumb_items[] = array( 'label' => get_the_title( $parent_id ), 'url' => get_permalink( $parent_id ) );
                }

                $breadcrumb_items[] = array( 'label' => get_the_title(), 'url' => '' );

            } elseif ( is_shop() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( 'Shop', 'shop-zen' ), 'url' => '' );

            } elseif ( is_cart() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( 'Cart', 'shop-zen' ), 'url' => '' );

            } elseif ( is_checkout() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( 'Cart', 'shop-zen' ), 'url' => wc_get_cart_url() );
                $breadcrumb_items[] = array( 'label' => __( 'Checkout', 'shop-zen' ), 'url' => '' );

            } elseif ( is_product_category() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( 'Shop', 'shop-zen' ), 'url' => get_permalink( wc_get_page_id( 'shop' ) ) );
                $breadcrumb_items[] = array( 'label' => single_term_title( '', false ), 'url' => '' );

            } elseif ( is_archive() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => get_the_archive_title(), 'url' => '' );

            } elseif ( is_search() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( 'Search Results', 'shop-zen' ), 'url' => '' );

            } elseif ( is_404() ) {
                $breadcrumb_items[] = array( 'label' => __( 'Home', 'shop-zen' ), 'url' => home_url( '/' ) );
                $breadcrumb_items[] = array( 'label' => __( '404 Not Found', 'shop-zen' ), 'url' => '' );
            }

            // Only render breadcrumbs if we have items
            if ( empty( $breadcrumb_items ) ) :
                return;
            endif;

            ?>
            <!-- Breadcrumbs -->
            <div class="page-breadcrumbs">
                <div class="container">
                    <nav class="page-breadcrumb-nav" aria-label="<?php esc_attr_e( 'Breadcrumb', 'shop-zen' ); ?>">
                        <?php foreach ( $breadcrumb_items as $i => $item ) : ?>
                            <?php if ( ! empty( $item['url'] ) ) : ?>
                                <a href="<?php echo esc_url( $item['url'] ); ?>"><?php echo esc_html( $item['label'] ); ?></a>
                                <span class="page-breadcrumb-sep">/</span>
                            <?php else : ?>
                                <span class="page-breadcrumb-current"><?php echo esc_html( $item['label'] ); ?></span>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </nav>
                </div>
            </div>
            <?php
        endif;
    }
endif;

/**
  * Get Page Title
  */

if( !function_exists( 'shop_zen_get_title' ) ):
    function shop_zen_get_title() {
        if(!is_front_page()) :
            // Skip title on cart page
            if(function_exists('is_cart') && is_cart()) :
                return;
            endif;
            // Skip title on checkout page
            if(function_exists('is_checkout') && is_checkout()) :
                return;
            endif;
            ?>
                <div class="page-title">
                    <?php shop_zen_before_title_content(); ?>
                    <div class="container">
                        <h1 class="main-title"><?php the_title(); ?></h1>
                    </div>
                    <?php shop_zen_after_title_content(); ?>
                </div>
            <?php
        endif;
    }
endif;


/**
  * Function for displaying menu item description
  *
  */
function shop_zen_nav_description( $item_output, $item, $depth, $args ) {
    if( isset($args->theme_location) && !empty($item->description) ) :
        $description_html = '<span class="menu-bubble-description">'.esc_html($item->description).'</span>';
        return $item_output.$description_html;
    endif;
    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'shop_zen_nav_description', 10, 4 );


/**
  * Function for Minimizing dynamic CSS
  */
function shop_zen_minimize_css($css){
    $css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css);
    $css = preg_replace('/\s{2,}/', ' ', $css);
    $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
    $css = preg_replace('/;}/', '}', $css);
    return $css;
}

/**
  * Adding blog sidebar classes to body
  */
if ( ! function_exists( 'shop_zen_add_blog_sidebar_classes_to_body' ) ) :
function shop_zen_add_blog_sidebar_classes_to_body($classes = '') {
    $sidebar_layout = get_theme_mod( 'shop_zen_blog_single_sidebar_layout', 'no' );
    if ( 'right' === $sidebar_layout && is_single() ) :
        $classes[] = 'single-right-sidebar';

    elseif ( 'left' === $sidebar_layout && is_single() ) :
        $classes[] = 'single-left-sidebar';

    elseif ( 'no' === $sidebar_layout && is_single() ) :
        $classes[] = 'single-no-sidebar';
    endif;
    return $classes;
}
endif;
add_filter('body_class', 'shop_zen_add_blog_sidebar_classes_to_body');


/**
 * Estimated Reading Time
 */
if (!function_exists('shop_zen_estimated_reading_time')) {
    function shop_zen_estimated_reading_time($content) {
        $word_count = str_word_count(strip_tags($content));
        $reading_time = ceil($word_count / 200); // Average reading speed: 200 words per minute
        return $reading_time;
    }
}

/**
 * Custom Comment Callback
 */
if (!function_exists('shop_zen_comment_callback')) {
    function shop_zen_comment_callback($comment, $args, $depth) {
        $commenter = wp_get_current_commenter();
        $req = get_option('require_name_email');
        ?>
        <div <?php comment_class( 'comment-item' ); ?> id="comment-<?php comment_ID(); ?>">
            <div class="comment-item-header">
                <div class="comment-item-author">
                    <div class="comment-item-avatar">
                        <?php echo get_avatar($comment->comment_author_email, 40); ?>
                    </div>
                    <div class="comment-item-info">
                        <h4 class="comment-item-name"><?php echo wp_kses_post( get_comment_author_link() ); ?></h4>
                        <span class="comment-item-date"><?php printf(esc_html__('%s ago', 'shop-zen'), human_time_diff(get_comment_time('U'), time())); ?></span>
                    </div>
                </div>
            </div>
            <div class="comment-item-text">
                <?php comment_text(); ?>
            </div>
            <div class="comment-item-actions">
                <?php
                comment_reply_link(array(
                    'depth'     => $depth,
                    'max_depth' => $args['max_depth'],
                    'before'    => '<button class="comment-action-btn">',
                    'after'     => '</button>',
                    'add_below' => 'comment',
                    'reply_text' => '<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg> ' . esc_html__('Reply', 'shop-zen'),
                ));
                ?>
            </div>
        <?php
    }
}

/**
 * Fallback menu
 */
if ( ! function_exists( 'shop_zen_default_menu_fallback' ) ) :
function shop_zen_default_menu_fallback( $args ) {
    $pages = get_pages( array(
        'sort_column'  => 'menu_order, post_title',
        'number'       => 5,
        'hierarchical' => false,
    ) );

    if ( empty( $pages ) ) {
        return;
    }

    foreach ( $pages as $page ) {
        printf(
            '<li class="menu-item"><a href="%s">%s</a></li>',
            esc_url( get_permalink( $page->ID ) ),
            esc_html( $page->post_title )
        );
    }
}
endif;

/**
 * Product Tabs.
 *
 * Renders the Description, Additional Information and Reviews tabs on the
 * single product page
 */
if ( ! function_exists( 'shop_zen_render_product_tabs' ) ) :
function shop_zen_render_product_tabs() {
	global $product;

	if ( ! is_a( $product, WC_Product::class ) ) {
		return;
	}

	$product_id      = $product->get_id();
	$description     = $product->get_description();
	$short_desc      = $product->get_short_description();
	$tab_content     = ! empty( $description ) ? $description : $short_desc;
	$rating_count    = $product->get_rating_count();

	// The Additional Information tab, only relevant
	// when the product exposes attributes, weight or dimensions.
	$has_additional_info = $product->has_attributes() || $product->has_dimensions() || $product->has_weight();
	$reviews_label   = $rating_count > 0
		? sprintf(
			/* translators: %d: number of reviews */
			_n( 'Reviews (%d)', 'Reviews (%d)', $rating_count, 'shop-zen' ),
			number_format_i18n( $rating_count )
		)
		: __( 'Reviews', 'shop-zen' );
	?>
	<div class="shop-zen-product-tabs">
		<div class="shop-zen-tab-headers" role="tablist">
			<button type="button" class="shop-zen-tab-header active-tab" data-tab="description" role="tab" aria-selected="true"><?php esc_html_e( 'Description', 'shop-zen' ); ?></button>
			<?php
			// Additional Information tab
			if ( $has_additional_info ) {
				echo '<button type="button" class="shop-zen-tab-header" data-tab="additional_information" role="tab" aria-selected="false">' . esc_html__( 'Additional Information', 'shop-zen' ) . '</button>';
			}
			?>
			<?php
			// Specifications tab
			if ( defined( 'SHOP_ZEN_PRO_VERSION' ) ) {
				echo '<button type="button" class="shop-zen-tab-header" data-tab="specifications" role="tab">' . esc_html__( 'Specifications', 'shop-zen' ) . '</button>';
			}
			?>
			<button type="button" class="shop-zen-tab-header" data-tab="reviews" role="tab" aria-selected="false"><?php echo esc_html( $reviews_label ); ?></button>
		</div>

		<div class="shop-zen-tab-panel active-panel" id="panel-description" role="tabpanel">
			<?php if ( ! empty( $tab_content ) ) : ?>
				<?php echo wp_kses_post( wpautop( $tab_content ) ); ?>
			<?php else : ?>
				<p><?php esc_html_e( 'No description available for this product.', 'shop-zen' ); ?></p>
			<?php endif; ?>
		</div>

		<?php if ( $has_additional_info ) : ?>
			<div class="shop-zen-tab-panel shop-zen-additional-info" id="panel-additional_information" role="tabpanel">
				<?php wc_display_product_attributes( $product ); ?>
			</div>
		<?php endif; ?>

		<?php
		// The Reviews panel content
		do_action( 'shop_zen_reviews_tab_content' );
		?>
	</div>
	<?php
}
endif;
add_action( 'shop_zen_product_tabs', 'shop_zen_render_product_tabs' );


/**
 * Trust Signals predefined icons.
 *
 * Returns the list of selectable icons for the trust signals
 * on the single product page.
 */
if ( ! function_exists( 'shop_zen_get_trust_signal_icons' ) ) :
function shop_zen_get_trust_signal_icons() {
	return array(
		'truck'   => array(
			'label' => __( 'Shipping Truck', 'shop-zen' ),
			'svg'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"/><path d="M14 9h4l4 4v4a1 1 0 0 1-1 1h-1"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></svg>',
		),
		'returns' => array(
			'label' => __( 'Return Arrow', 'shop-zen' ),
			'svg'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 4v4h4"/></svg>',
		),
		'shield'  => array(
			'label' => __( 'Shield Check', 'shop-zen' ),
			'svg'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-.5-8-5-8-10V6l8-4z"/><path d="M9 12l2 2 4-4"/></svg>',
		),
		'badge'   => array(
			'label' => __( 'Badge Check', 'shop-zen' ),
			'svg'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z"/><path d="m9 12 2 2 4-4"/></svg>',
		),
		'card'    => array(
			'label' => __( 'Payment Card', 'shop-zen' ),
			'svg'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>',
		),
	);
}
endif;


/**
 * Trust Signals.
 *
 * Renders the trust badges box (shipping, returns, warranty) on the
 * single product page.
 */
if ( ! function_exists( 'shop_zen_render_trust_signals' ) ) :
function shop_zen_render_trust_signals() {
	if ( ! get_theme_mod( 'shop_zen_enable_trust_signals', true ) ) {
		return;
	}

	$icons = shop_zen_get_trust_signal_icons();

	$items = array(
		array(
			'icon'  => $icons['truck']['svg'],
			'key'   => 'truck',
			'mod'   => 'shop_zen_trust_signal_1_icon',
			'label' => get_theme_mod( 'shop_zen_trust_signal_1', __( 'Free Shipping', 'shop-zen' ) ),
		),
		array(
			'icon'  => $icons['returns']['svg'],
			'key'   => 'returns',
			'mod'   => 'shop_zen_trust_signal_2_icon',
			'label' => get_theme_mod( 'shop_zen_trust_signal_2', __( '30-Day Returns', 'shop-zen' ) ),
		),
		array(
			'icon'  => $icons['shield']['svg'],
			'key'   => 'shield',
			'mod'   => 'shop_zen_trust_signal_3_icon',
			'label' => get_theme_mod( 'shop_zen_trust_signal_3', __( '2-Year Warranty', 'shop-zen' ) ),
		),
	);

	foreach ( $items as $index => $item ) {
		$selected = get_theme_mod( $item['mod'], $item['key'] );
		if ( 'none' === $selected ) {
			$items[ $index ]['icon'] = '';
		} elseif ( isset( $icons[ $selected ] ) ) {
			$items[ $index ]['icon'] = $icons[ $selected ]['svg'];
		}
	}

	// Skip items with an empty label.
	$items = array_filter(
		$items,
		function ( $item ) {
			return '' !== $item['label'];
		}
	);

	$items = apply_filters( 'shop_zen_trust_signals_items', $items );

	if ( empty( $items ) ) {
		return;
	}
	?>
	<div class="shop-zen-trust-signals">
		<?php
		$allowed_svg = array(
			'svg'   => array( 'width' => true, 'height' => true, 'viewbox' => true, 'fill' => true, 'stroke' => true, 'xmlns' => true ),
			'path'  => array( 'd' => true, 'fill' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true ),
			'circle' => array( 'cx' => true, 'cy' => true, 'r' => true, 'fill' => true, 'stroke' => true, 'stroke-width' => true ),
			'line'  => array( 'x1' => true, 'y1' => true, 'x2' => true, 'y2' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linecap' => true ),
			'rect'  => array( 'x' => true, 'y' => true, 'width' => true, 'height' => true, 'rx' => true, 'fill' => true, 'stroke' => true, 'stroke-width' => true ),
		);
		foreach ( $items as $item ) :
		?>
			<div class="shop-zen-trust-item">
				<?php if ( ! empty( $item['icon'] ) ) : ?>
					<span class="shop-zen-trust-icon"><?php echo wp_kses( $item['icon'], $allowed_svg ); ?></span>
				<?php endif; ?>
				<p><?php echo esc_html( $item['label'] ); ?></p>
			</div>
		<?php endforeach; ?>
	</div>
	<?php
}
endif;
add_action( 'shop_zen_trust_signals', 'shop_zen_render_trust_signals' );


/**
 * Custom Comment Callback
 */

if ( ! function_exists( 'shop_zen_related_blog_posts' ) ) :
function shop_zen_related_blog_posts() {
    
    $related_args = array(
        'posts_per_page' => 2,
        'post__not_in'   => array( get_the_ID() ),
        'category__in'   => wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) ),
        'orderby'        => 'rand',
    );
    $related_query = new WP_Query( $related_args );
    if ( $related_query->have_posts() ) :
    ?>
    <!-- Related Posts -->
    <section class="related-section fade-in">
        <h2 class="related-title font-display"><?php esc_html_e( 'Continue reading', 'shop-zen' ); ?></h2>
        <div class="related-grid">
            <?php
                while ( $related_query->have_posts() ) :
                    $related_query->the_post();
            ?>
            <a href="<?php the_permalink(); ?>" class="related-card">
                <?php if ( has_post_thumbnail() ) : ?>
                <?php the_post_thumbnail( 'medium' ); ?>
                <?php endif; ?>
                <div class="related-card-body">
                    <?php
                    $rel_categories = get_the_category();
                    if ( ! empty( $rel_categories ) ) :
                    ?>
                    <span class="related-card-category"><?php echo esc_html( $rel_categories[0]->name ); ?></span>
                    <?php endif; ?>
                    <h3 class="related-card-title"><?php the_title(); ?></h3>
                    <span class="related-card-date"><?php echo esc_html( get_the_date() ); ?></span>
                </div>
            </a>
            <?php endwhile; ?>
        </div>
    </section>
    <?php
        wp_reset_postdata();
    endif;
}
endif;

/**
 * Disable onboarding wizards for WooCommerce and Elementor.
 *
 * Prevents WooCommerce from redirecting to its setup wizard and marks
 * the Elementor onboarding as completed, so neither plugin interrupts
 * store owners with its first-run setup flow.
 */
if ( ! function_exists( 'shop_zen_disable_plugin_onboarding' ) ) :
function shop_zen_disable_plugin_onboarding() {

	// WooCommerce: prevent the automatic setup wizard redirect and disable the onboarding profiler.
	if ( class_exists( 'WooCommerce' ) ) {
		add_filter( 'woocommerce_prevent_automatic_wizard_redirect', '__return_true' );
        add_filter( 'woocommerce_enable_setup_wizard', '__return_false' );
	}

	// Elementor: mark the onboarding as complete so the wizard is skipped.
    if ( class_exists( '\Elementor\Plugin' ) ) {

        delete_transient( 'elementor_activation_redirect' );

        if ( ! get_option( 'elementor_onboarded' ) ) {
            update_option( 'elementor_onboarded', true );
        }
    }
}
endif;
add_action( 'admin_init', 'shop_zen_disable_plugin_onboarding' );