<?php
/**
 * Template helper functions.
 *
 * @package Shabnam_MuchWOW
 */

defined( 'ABSPATH' ) || exit;

/**
 * Return a URL inside the theme assets directory.
 */
function shabnam_asset_uri( $path = '' ) {
	$path = ltrim( (string) $path, '/' );
	return trailingslashit( get_template_directory_uri() . '/assets' ) . $path;
}

/**
 * Return the best available contact destination.
 * Falls back to the FAQ section when no contact page exists.
 */
function shabnam_contact_url() {
	$contact_page = get_page_by_path( 'contact' );
	if ( $contact_page instanceof WP_Post ) {
		return get_permalink( $contact_page );
	}
	return home_url( '/#faq' );
}

/**
 * Return the WooCommerce shop URL when available.
 */
function shabnam_shop_url() {
	if ( class_exists( 'WooCommerce' ) ) {
		$shop_url = wc_get_page_permalink( 'shop' );
		if ( $shop_url ) {
			return $shop_url;
		}
	}
	return home_url( '/' );
}

/**
 * Print post date metadata.
 */
function shabnam_posted_on() {
	printf(
		'<a class="text-none text-white text-opacity-70" href="%1$s"><time datetime="%2$s">%3$s</time></a>',
		esc_url( get_permalink() ),
		esc_attr( get_the_date( DATE_W3C ) ),
		esc_html( get_the_date() )
	);
}

/**
 * Print author metadata.
 */
function shabnam_posted_by() {
	printf(
		'<a class="text-none text-secondary" href="%1$s">%2$s</a>',
		esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
		esc_html( get_the_author() )
	);
}

/**
 * Primary menu fallback with useful one-page anchors.
 */
function shabnam_primary_menu_fallback() {
	$home = home_url( '/' );
	?>
	<ul class="uc-navbar-nav fs-4 gap-3 lg:gap-4 d-none lg:d-flex fw-semibold text-white">
		<li><a href="<?php echo esc_url( $home . '#about' ); ?>"><?php esc_html_e( 'داستان ما', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#tokenomics' ); ?>"><?php esc_html_e( 'اقتصاد توکن', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#roadmap' ); ?>"><?php esc_html_e( 'نقشه راه', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#faq' ); ?>"><?php esc_html_e( 'پرسش‌های متداول', 'shabnam-muchwow' ); ?></a></li>
	</ul>
	<?php
}

/**
 * Mobile menu fallback.
 */
function shabnam_mobile_menu_fallback() {
	$home = home_url( '/' );
	?>
	<ul class="nav-y gap-narrow fw-medium fs-6" data-uc-nav="">
		<li><a href="<?php echo esc_url( $home . '#about' ); ?>"><?php esc_html_e( 'درباره ما', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#tokenomics' ); ?>"><?php esc_html_e( 'اقتصاد توکن', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#roadmap' ); ?>"><?php esc_html_e( 'نقشه راه', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#faq' ); ?>"><?php esc_html_e( 'پرسش‌های متداول', 'shabnam-muchwow' ); ?></a></li>
		<?php if ( class_exists( 'WooCommerce' ) ) : ?>
			<li><a href="<?php echo esc_url( wc_get_page_permalink( 'shop' ) ); ?>"><?php esc_html_e( 'فروشگاه', 'shabnam-muchwow' ); ?></a></li>
		<?php endif; ?>
	</ul>
	<?php
}

/**
 * Footer menu fallback.
 */
function shabnam_footer_menu_fallback() {
	$home = home_url( '/' );
	?>
	<ul class="nav-x gap-0 row child-cols-auto justify-center gx-4 gy-2 lg:g-4 fs-5 xl:fs-4">
		<li><a href="<?php echo esc_url( $home . '#about' ); ?>"><?php esc_html_e( 'درباره ما', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#roadmap' ); ?>"><?php esc_html_e( 'نقشه راه', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#tokenomics' ); ?>"><?php esc_html_e( 'اقتصاد توکن', 'shabnam-muchwow' ); ?></a></li>
		<li><a href="<?php echo esc_url( $home . '#faq' ); ?>"><?php esc_html_e( 'پرسش‌های متداول', 'shabnam-muchwow' ); ?></a></li>
	</ul>
	<?php
}

/**
 * Return the configured posts archive URL.
 *
 * @return string
 */
function shabnam_blog_url() {
	$page_for_posts = absint( get_option( 'page_for_posts' ) );
	if ( $page_for_posts ) {
		$url = get_permalink( $page_for_posts );
		if ( $url ) {
			return $url;
		}
	}
	return home_url( '/' );
}

/**
 * Return archive grid columns from framework settings.
 *
 * @return int
 */
function shabnam_blog_columns() {
	$columns = function_exists( 'shabnam_get_setting' ) ? absint( shabnam_get_setting( 'blog_columns', 3 ) ) : 3;
	return max( 1, min( 4, $columns ) );
}

/**
 * Print post metadata according to framework preferences.
 */
function shabnam_post_meta() {
	$show_date   = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_date', true ) : true;
	$show_author = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_author', true ) : true;

	if ( ! $show_date && ! $show_author ) {
		return;
	}

	echo '<div class="shabnam-post-meta hstack justify-center gap-2 fs-6 text-white text-opacity-70">';
	if ( $show_date ) {
		echo '<span>';
		shabnam_posted_on();
		echo '</span>';
	}
	if ( $show_date && $show_author ) {
		echo '<span aria-hidden="true">•</span>';
	}
	if ( $show_author ) {
		echo '<span>';
		shabnam_posted_by();
		echo '</span>';
	}
	echo '</div>';
}




/**
 * Compact metadata row for archive/home cards.
 * Keeping every item in one list prevents RTL wrapping from creating large,
 * uneven gaps between date, author, category and reading time.
 */
function shabnam_post_card_meta() {
	$show_date       = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_date', true ) : true;
	$show_author     = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_author', true ) : true;
	$show_categories = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_categories', true ) : true;
	$show_reading    = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_reading_time', true ) : true;
	$items           = array();

	if ( $show_date ) {
		$items[] = '<span class="shabnam-card-meta-date">' . esc_html( get_the_date() ) . '</span>';
	}
	if ( $show_author ) {
		$items[] = '<span class="shabnam-card-meta-author">' . esc_html( get_the_author() ) . '</span>';
	}
	if ( $show_categories ) {
		$categories = get_the_category();
		if ( $categories ) {
			$links = array();
			foreach ( array_slice( $categories, 0, 1 ) as $category ) {
				$links[] = '<a href="' . esc_url( get_category_link( $category ) ) . '">' . esc_html( $category->name ) . '</a>';
			}
			if ( $links ) {
				$items[] = '<span class="shabnam-card-meta-categories">' . implode( '، ', $links ) . '</span>';
			}
		}
	}
	if ( $show_reading ) {
		$items[] = '<span class="shabnam-card-meta-reading">' . esc_html( sprintf( __( '%d دقیقه مطالعه', 'shabnam-muchwow' ), shabnam_reading_time() ) ) . '</span>';
	}
	if ( ! $items ) {
		return;
	}

	echo '<div class="shabnam-card-meta" aria-label="' . esc_attr__( 'اطلاعات نوشته', 'shabnam-muchwow' ) . '">';
	foreach ( $items as $item ) {
		echo '<span class="shabnam-card-meta-item">' . wp_kses_post( $item ) . '</span>';
	}
	echo '</div>';
}

/**
 * Restore the homepage blog query after third-party pre_get_posts callbacks.
 *
 * The section uses only WordPress query APIs. This late guard prevents broad
 * plugin callbacks from accidentally turning the small homepage post query
 * into a product/search/archive query while keeping SQL generation inside
 * WordPress itself.
 *
 * @param WP_Query $query Query instance.
 */
function shabnam_protect_home_blog_query( $query ) {
	if ( ! ( $query instanceof WP_Query ) || ! $query->get( 'shabnam_home_blog_query' ) ) {
		return;
	}

	$count    = absint( $query->get( 'shabnam_home_blog_count' ) );
	$category = absint( $query->get( 'shabnam_home_blog_category' ) );
	$orderby  = sanitize_key( (string) $query->get( 'shabnam_home_blog_orderby' ) );
	$order    = strtoupper( sanitize_text_field( (string) $query->get( 'shabnam_home_blog_order' ) ) );
	$count    = max( 2, min( 12, $count ? $count : 3 ) );
	$orderby  = in_array( $orderby, array( 'date', 'modified', 'comment_count', 'title' ), true ) ? $orderby : 'date';
	$order    = in_array( $order, array( 'ASC', 'DESC' ), true ) ? $order : 'DESC';

	// Remove unrelated scalar constraints that broad pre_get_posts callbacks may add.
	$scalar_resets = array(
		'p' => 0, 'page_id' => 0, 'name' => '', 'pagename' => '', 'post_parent' => '',
		'author' => '', 'author_name' => '', 'year' => 0, 'monthnum' => 0, 'w' => 0,
		'day' => 0, 'hour' => 0, 'minute' => 0, 'second' => 0, 'm' => 0, 's' => '',
		'sentence' => false, 'title' => '', 'meta_key' => '', 'meta_value' => '',
		'category_name' => '', 'tag' => '', 'tag_id' => 0, 'offset' => 0,
	);
	foreach ( $scalar_resets as $key => $value ) {
		$query->set( $key, $value );
	}

	// Array query arguments must remain arrays; setting them to strings can create warnings in plugins.
	foreach ( array(
		'post_parent__in', 'post_parent__not_in', 'post__in', 'post__not_in', 'author__in', 'author__not_in',
		'category__and', 'category__in', 'category__not_in', 'tag__and', 'tag__in', 'tag__not_in',
		'tag_slug__and', 'tag_slug__in', 'meta_query', 'tax_query', 'date_query'
	) as $key ) {
		$query->set( $key, array() );
	}

	$query->set( 'post_type', 'post' );
	$query->set( 'post_status', 'publish' );
	$query->set( 'posts_per_page', $count );
	$query->set( 'ignore_sticky_posts', true );
	$query->set( 'no_found_rows', true );
	$query->set( 'suppress_filters', true );
	$query->set( 'cache_results', true );
	$query->set( 'update_post_meta_cache', true );
	$query->set( 'update_post_term_cache', true );
	$query->set( 'orderby', $orderby );
	$query->set( 'order', $order );
	$query->set( 'cat', $category && term_exists( $category, 'category' ) ? $category : 0 );
}
add_action( 'pre_get_posts', 'shabnam_protect_home_blog_query', PHP_INT_MAX );

/**
 * Build a resilient query for the homepage blog section.
 *
 * The custom marker lets the theme restore the essential query arguments at
 * the end of pre_get_posts, protecting this small section from broad filters
 * that some plugins incorrectly apply to every WP_Query instance.
 *
 * @param array<string,mixed> $overrides Optional query overrides.
 * @return WP_Query
 */
function shabnam_home_blog_query( $overrides = array() ) {
	$count    = function_exists( 'shabnam_get_setting' ) ? absint( shabnam_get_setting( 'blog_home_count', 3 ) ) : 3;
	$category = function_exists( 'shabnam_get_setting' ) ? absint( shabnam_get_setting( 'blog_home_category', 0 ) ) : 0;
	$orderby  = function_exists( 'shabnam_get_setting' ) ? sanitize_key( (string) shabnam_get_setting( 'blog_home_orderby', 'date' ) ) : 'date';
	$order    = function_exists( 'shabnam_get_setting' ) ? strtoupper( sanitize_text_field( (string) shabnam_get_setting( 'blog_home_order', 'DESC' ) ) ) : 'DESC';

	$count   = max( 2, min( 12, $count ) );
	$orderby = in_array( $orderby, array( 'date', 'modified', 'comment_count', 'title' ), true ) ? $orderby : 'date';
	$order   = in_array( $order, array( 'ASC', 'DESC' ), true ) ? $order : 'DESC';

	$args = array(
		'post_type'                     => 'post',
		'post_status'                   => 'publish',
		'posts_per_page'                => $count,
		'ignore_sticky_posts'           => true,
		'no_found_rows'                 => true,
		'suppress_filters'              => true,
		'cache_results'                 => true,
		'update_post_meta_cache'        => true,
		'update_post_term_cache'        => true,
		'orderby'                       => $orderby,
		'order'                         => $order,
		'shabnam_home_blog_query'       => 1,
		'shabnam_home_blog_count'       => $count,
		'shabnam_home_blog_category'    => $category,
		'shabnam_home_blog_orderby'     => $orderby,
		'shabnam_home_blog_order'       => $order,
	);

	if ( $category && term_exists( $category, 'category' ) ) {
		$args['cat'] = $category;
	}

	$args = wp_parse_args( is_array( $overrides ) ? $overrides : array(), $args );
	$args['posts_per_page']             = max( 2, min( 12, absint( $args['posts_per_page'] ) ) );
	$args['shabnam_home_blog_count']    = $args['posts_per_page'];
	$args['shabnam_home_blog_category'] = isset( $args['cat'] ) ? absint( $args['cat'] ) : $category;
	$args['shabnam_home_blog_orderby']  = $orderby;
	$args['shabnam_home_blog_order']    = $order;

	$query = new WP_Query( $args );

	// A stale or empty category selection must never make the homepage look empty.
	if ( ! $query->have_posts() && ! empty( $args['cat'] ) ) {
		unset( $args['cat'] );
		$args['shabnam_home_blog_category'] = 0;
		$query = new WP_Query( $args );
	}

	return $query;
}

/**
 * Return the configured column count for the homepage blog section.
 *
 * @return int
 */
function shabnam_home_blog_columns() {
	$columns = function_exists( 'shabnam_get_setting' ) ? absint( shabnam_get_setting( 'blog_home_columns', 3 ) ) : 3;
	return max( 1, min( 4, $columns ) );
}

/**
 * Return an approximate reading time for the current post.
 *
 * @param int $post_id Post ID.
 * @return int
 */
function shabnam_reading_time( $post_id = 0 ) {
	$post_id = absint( $post_id ? $post_id : get_the_ID() );
	$content = $post_id ? get_post_field( 'post_content', $post_id ) : '';
	$text    = trim( wp_strip_all_tags( strip_shortcodes( (string) $content ) ) );
	if ( '' === $text ) {
		return 1;
	}
	$words = preg_split( '/\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY );
	$count = is_array( $words ) ? count( $words ) : 0;
	return max( 1, (int) ceil( $count / 220 ) );
}

/**
 * Print categories and reading-time helpers for cards and single posts.
 */
function shabnam_post_secondary_meta() {
	$show_categories = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_categories', true ) : true;
	$show_reading    = function_exists( 'shabnam_get_setting' ) ? (bool) shabnam_get_setting( 'blog_show_reading_time', true ) : true;
	$categories      = $show_categories ? get_the_category_list( '، ' ) : '';

	if ( ! $categories && ! $show_reading ) {
		return;
	}

	echo '<div class="shabnam-post-secondary-meta hstack gap-2 flex-wrap fs-7 text-white text-opacity-70">';
	if ( $categories ) {
		echo '<span class="shabnam-post-categories">' . wp_kses_post( $categories ) . '</span>';
	}
	if ( $categories && $show_reading ) {
		echo '<span aria-hidden="true">•</span>';
	}
	if ( $show_reading ) {
		printf( '<span>%s</span>', esc_html( sprintf( __( '%d دقیقه مطالعه', 'shabnam-muchwow' ), shabnam_reading_time() ) ) );
	}
	echo '</div>';
}

/**
 * Render related blog posts for the current single post.
 */
function shabnam_related_posts() {
	if ( ! is_singular( 'post' ) || ( function_exists( 'shabnam_get_setting' ) && ! shabnam_get_setting( 'blog_related_posts', true ) ) ) {
		return;
	}

	$count = function_exists( 'shabnam_get_setting' ) ? absint( shabnam_get_setting( 'blog_related_count', 3 ) ) : 3;
	$count = max( 2, min( 8, $count ) );
	$cats  = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );
	$args  = array(
		'post_type'           => 'post',
		'post_status'         => 'publish',
		'posts_per_page'      => $count,
		'post__not_in'        => array( get_the_ID() ),
		'ignore_sticky_posts' => true,
		'no_found_rows'       => true,
		'orderby'             => 'date',
		'order'               => 'DESC',
	);
	if ( $cats ) {
		$args['category__in'] = array_map( 'absint', $cats );
	}
	$query = new WP_Query( $args );
	if ( ! $query->have_posts() ) {
		return;
	}
	$columns = min( 4, max( 2, $count ) );
	?>
	<section class="shabnam-related-posts mt-6" aria-labelledby="shabnam-related-title">
		<div class="hstack justify-between gap-2 mb-3"><h2 id="shabnam-related-title" class="h4 m-0 text-white"><?php esc_html_e( 'نوشته‌های مرتبط', 'shabnam-muchwow' ); ?></h2><a class="text-secondary fw-semibold" href="<?php echo esc_url( shabnam_blog_url() ); ?>"><?php esc_html_e( 'همه نوشته‌ها', 'shabnam-muchwow' ); ?></a></div>
		<div class="shabnam-blog-grid" style="--shcd-blog-columns:<?php echo esc_attr( $columns ); ?>">
			<?php while ( $query->have_posts() ) : $query->the_post(); get_template_part( 'template-parts/content', 'card' ); endwhile; ?>
		</div>
	</section>
	<?php
	wp_reset_postdata();
}
