<?php

/**
 * Video item unit selection.
 */


 if ( ! function_exists( 'wpstream_blog_post_card_selector' ) ) :
	function wpstream_blog_post_card_selector( $type=0, $is_grid = 0 ) {

		if ( intval( $type ) === 0 ) {
			$type = get_theme_mod( 'wpstream_theme_blog_post_card_type', 1 );
		}
		$type == 1;
		if ( $type == 1 ) {
			$template = 'cards/blog-card-v1.php';
		} elseif ( $type == 2 ) {
			$template = 'cards/blog-card-v1.php';
		}

		return '/template-parts/single/' . $template;
	}
endif;


/**
 * Determine the column classes for blog cards based on the number of columns per row.
 *
 * @param int $per_row The number of columns per row.
 * @return string The string of column classes.
 */
function wpstream_blog_column_class( $per_row ) {
	$per_row = intval( $per_row );
	$return = 'col-12 col-sm-6 col-md-4 col-lg-4';

	if ( 4 === $per_row ) {
		$return = 'col-12 col-sm-6 col-md-4 col-lg-3';
	}else if ( 2 === $per_row ) {
		$return = 'col-12 col-sm-6 col-md-6 col-lg-6';
	}else if ( 6 === $per_row ) {
		$return = 'col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2';
	}else if ( 5 === $per_row ) {
		$return = 'col-12 col-sm-6 col-md-4 col-2-4';
	}
	return $return;
}


/**
 * Blog functions
 *
 * @package wpstream-theme
 */

if ( ! function_exists( 'wpstream_theme_return_use_transient' ) ) {
	/**
	 * Return use of transient
	 */
	function wpstream_theme_return_use_transient() {
		$use_transient = false;

		return $use_transient;
	}
}

if ( ! function_exists( 'wpstream_theme_more_from_author' ) ) {
	/**
	 * Display a grid of posts from a specific author.
	 *
	 * Retrieves and displays a grid of posts authored by a specific user.
	 *
	 * @param int $author_id The ID of the author whose posts to display.
	 * @return void
	 */
	function wpstream_theme_more_from_author( $author_id, $card_grid_class_overwrite = '' ) {//phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
		$hide_category = false;
		$use_transient = wpstream_theme_return_use_transient();
		$transient_key = 'wpstream_theme_more_from_author_' . $author_id;

		$author_post_args = array(
			'post_status'    => 'publish',
			'post_type'      => 'post',
			'posts_per_page' => 4,
			'author'         => $author_id,
			'orderby'        => 'date', // Order by post date.
			'order'          => 'DESC', // Sort in descending order (latest first).
		);

		$query = wpstream_theme_custom_query( $author_post_args, $transient_key, $use_transient );

		// The query to display results.
		include get_template_directory() . '/template-parts/single/post-loop-content.php';
	}
}

if ( ! function_exists( 'wpstream_get_published_duration_by_date_time' ) ) {
	/**
	 * Get the published duration based on a given date and time.
	 *
	 * Calculates and returns the duration between the given date and time and the current time
	 * in a human-readable format (e.g., "5 mins ago", "1 hour ago", "3 days ago", etc.).
	 *
	 * @param string|int $date_time The date and time to calculate the duration from. Accepts a date/time string or Unix timestamp.
	 * @return string The human-readable duration.
	 */
	function wpstream_get_published_duration_by_date_time( $date_time ) {
		$post_date    = strtotime( $date_time );
		$current_time = time();
		$time_diff    = $current_time - $post_date;

		if ( $time_diff < 60 ) {
			// translators: %s - time in seconds.
			$duration = sprintf( _n( '%s sec ago', '%s secs ago', $time_diff, 'hello-wpstream' ), $time_diff );
		} elseif ( $time_diff < 3600 ) {
			$minutes = floor( $time_diff / 60 );
			// translators: %s - time in minutes.
			$duration = sprintf( _n( '%s min ago', '%s mins ago', $minutes, 'hello-wpstream' ), $minutes );
		} elseif ( $time_diff < 86400 ) {
			$hours = floor( $time_diff / 3600 );
			// translators: %s - time in hours.
			$duration = sprintf( _n( '%s hour ago', '%s hours ago', $hours, 'hello-wpstream' ), $hours );
		} elseif ( $time_diff < 86400 * 365 ) {
			$days = floor( $time_diff / 86400 );
			// translators: %s - time in days.
			$duration = sprintf( _n( '%s day ago', '%s days ago', $days, 'hello-wpstream' ), $days );
		} else {
			$years = floor( $time_diff / ( 86400 * 365 ) );
			// translators: %s - time in years.
			$duration = sprintf( _n( '%s year ago', '%s years ago', $years, 'hello-wpstream' ), $years );
		}

		return $duration;
	}
}

if ( ! function_exists( 'wpstream_get_post_read_count_by_id' ) ) {
	/**
	 * Get the estimated read time of a post by its ID.
	 *
	 * Calculates and returns the estimated read time for a post based on its content length,
	 * assuming an average reading speed of 200 words per minute.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string The estimated read time in a human-readable format.
	 */
	function wpstream_get_post_read_count_by_id( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post ) {
			return '';
		}

		$post_content = $post->post_content;
		$word_count   = str_word_count( wp_strip_all_tags( $post_content ) );

		// Calculate the estimated read time.
		$read_time = ceil( $word_count / 200 ); // Assuming an average reading speed of 200 words per minute.

		if ( $read_time <= 1 ) {
			return __( '1 min read', 'hello-wpstream' );
		} else {
			// translators: %d - time to read in minutes.
			return sprintf( _n( '%d min read', '%d mins read', $read_time, 'hello-wpstream' ), $read_time );
		}
	}
}

add_action( 'wp_head', 'wpstream_increment_post_view_count' );

if ( ! function_exists( 'wpstream_increment_post_view_count' ) ) {
	/**
	 * Increment post view count
	 */
	function wpstream_increment_post_view_count() {
		if ( is_single() ) {
			global $post;
			$post_id = $post->ID;
			$views   = get_post_meta( $post_id, 'post_view_count', true );
			$views   = ( $views ) ? $views + 1 : 1;
			update_post_meta( $post_id, 'post_view_count', $views );
		}
	}
}

if ( ! function_exists( 'wpstream_display_post_view_count_by_id' ) ) {
	/**
	 * Display the post view count by its ID.
	 *
	 * Retrieves and formats the post view count based on the provided post ID.
	 * The view count is formatted with 'K' for thousands, 'M' for millions, and 'B' for billions.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string|int The formatted view count or 0 if the post ID is not set.
	 */
	function wpstream_display_post_view_count_by_id( $post_id ) {
		if ( isset( $post_id ) ) {
			$views = get_post_meta( $post_id, 'post_view_count', true );

			if ( $views >= 1000000000 ) {
				return round( $views / 1000000000 ) . 'B'; // Format as 1B, 2B, etc. for billions.
			} elseif ( $views >= 1000000 ) {
				return round( $views / 1000000 ) . 'M'; // Format as 1M, 2M, etc. for millions.
			} elseif ( $views >= 1000 ) {
				return round( $views / 1000 ) . 'K'; // Format as 1K, 2K, etc. for thousands.
			} else {
				return '' !== $views ? $views : 0; // Display the view count as is if it's less than 1000 or empty.
			}
		}

		return 0; // Provide a default value or an empty string if not a single post.
	}
}


if ( ! function_exists( 'wpstream_get_author_id' ) ) {
	/**
	 * Retrieve the author ID of a post.
	 *
	 * @param int $post_id The ID of the post.
	 * @return int|null The author ID if found, otherwise null.
	 */
	function wpstream_get_author_id( $post_id ) {
		$author_id = get_post_field( 'post_author', $post_id );
		return is_numeric( $author_id ) ? intval( $author_id ) : null;
	}
}

if ( ! function_exists( 'wpstream_theme_show_watch_later' ) ) {
	/**
	 * Display the watch later icons for a specific post.
	 *
	 * This function generates HTML code to display watch later icons for a given post.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string HTML code for watch later icons wrapped in a div container.
	 */
	function wpstream_theme_show_watch_later( $post_id ) {
		$return_string  = '<div class="wpstream-show-watch-later-wrapper">';
		$return_string .= wpstream_theme_show_watch_later_icons( $post_id );
		$return_string .= '</div>';

		return $return_string;
	}
}

if ( ! function_exists( 'wpstream_theme_show_watch_later_icons' ) ) {
	/**
	 * Display watch later icons for a specific post.
	 *
	 * This function generates HTML code to display watch later icons for a given post. It checks if the
	 * current user has added the post to their watch later list and displays appropriate icons and status.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string HTML code for watch later icons.
	 */
	function wpstream_theme_show_watch_later_icons( $post_id ) {
		$user_id           = get_current_user_id();
		$watch_later_items = get_user_meta( $user_id, 'wpstream_user_watch_later_items', true );
		$extra_class       = '';

		if ( is_array( $watch_later_items ) && in_array( $post_id, $watch_later_items, true ) ) {
			$extra_class = 'wpstream_already_watched_later';

			// Set a different SVG icon path when post is in "Watch Later" list.
			$icon_name                   = 'tick-circle.svg';
			$wpstream_water_later_status = esc_html__( 'Added to Watch Later', 'hello-wpstream' );
		} else {
			// Set the default SVG icon path.
			$icon_name                   = 'folder-plus.svg';
			$wpstream_water_later_status = esc_html__( 'Watch Later', 'hello-wpstream' );
		}

		$display_watch_later= true;
		$post_type = get_post_type( $post_id );

		if($post_type == 'product' && function_exists('wc_get_product') ){
			$product 		= wc_get_product( $post_id);
			
			$product_type 	= '';
			if($product){
				$product_type 	= $product->get_type();
			}

			$permited_values= array('subscription','product', 'live_stream','video_on_demand','wpstream_bundle');
	


			if(  !in_array($product_type, $permited_values) ){
				$display_watch_later= false;
			} 
		}
		


		if($display_watch_later){

			if ( is_user_logged_in() ) {
				$return_string = '<div class="wpstream-watch-later-action ' . esc_attr( $extra_class ) . '" '
					. 'data-postID="' . esc_attr( $post_id ) . '">'
					. wpstream_theme_get_svg_icon( $icon_name ) . '<span>' . $wpstream_water_later_status . '</span>'
					. '</div>';
			} else {
				$return_string = '  <div tabindex="0" class="wpstream-watch-later-action wpstream_no_action" data-toggle="tooltip" data-bs-placement="bottom" '
					. 'data-bs-original-title="' . esc_attr__( 'Sign in to watch later', 'hello-wpstream' ) . '"'
					. 'title="' . esc_attr__( 'Watch Later', 'hello-wpstream' ) . '"'
					. 'data-postID="' . esc_attr( $post_id ) . '">'
					. wpstream_theme_get_svg_icon( $icon_name ) . ' <span>' . $wpstream_water_later_status . '</span>'
					. '</div>';
			}

		}

		return $return_string ?? '';
	}
}

if ( ! function_exists( 'wpstream_get_post_published_duration_by_id' ) ) {
	/**
	 * Get the time elapsed since the post was published.
	 *
	 * This function calculates and returns the time elapsed since the post was published in a human-readable format.
	 *
	 * @param int $post_id The post ID.
	 * @return string The time elapsed since the post was published.
	 */
	function wpstream_get_post_published_duration_by_id( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post ) {
			return '';
		}

		$post_date    = strtotime( $post->post_date );
		$current_time = time();
		$time_diff    = $current_time - $post_date;

		if ( $time_diff < 60 ) {
			// translators: %s - time in seconds.
			$duration = sprintf( _n( '%s sec ago', '%s secs ago', $time_diff, 'hello-wpstream' ), $time_diff );
		} elseif ( $time_diff < 3600 ) {
			$minutes = floor( $time_diff / 60 );
			// translators: %s - time in minutes.
			$duration = sprintf( _n( '%s min ago', '%s mins ago', $minutes, 'hello-wpstream' ), $minutes );
		} elseif ( $time_diff < 86400 ) {
			$hours = floor( $time_diff / 3600 );
			// translators: %s - time in hours.
			$duration = sprintf( _n( '%s hour ago', '%s hours ago', $hours, 'hello-wpstream' ), $hours );
		} elseif ( $time_diff < 86400 * 365 ) {
			$days = floor( $time_diff / 86400 );
			// translators: %s - time in days.
			$duration = sprintf( _n( '%s day ago', '%s days ago', $days, 'hello-wpstream' ), $days );
		} else {
			$years = floor( $time_diff / ( 86400 * 365 ) );
			// translators: %s - time in years.
			$duration = sprintf( _n( '%s year ago', '%s years ago', $years, 'hello-wpstream' ), $years );
		}

		return $duration;
	}
}

if ( ! function_exists( 'wpstream_get_author_profile_image_url_by_author_id' ) ) {
	/**
	 * Retrieve the profile image URL of an author by their ID.
	 *
	 * This function retrieves the profile image URL of an author based on their ID and the specified image size.
	 *
	 * @param int    $author_id   The ID of the author.
	 * @param string $image_size  (optional) The size of the image. Default is '48'.
	 * @return string|null The profile image URL of the author, or null if the image is not found.
	 */
	function wpstream_get_author_profile_image_url_by_author_id( $author_id, $image_size = '48' ) {
		$profile_img_url = get_the_author_meta( 'custom_picture', $author_id );
		$author_gravatar_url = get_avatar_url( $author_id, array( 'size' => $image_size ) );

		return !empty($profile_img_url) ? $profile_img_url : $author_gravatar_url;
	}
}

if ( ! function_exists( 'wpstream_get_single_post_author_link' ) ) {
	/**
	 * Retrieve the URL of the author's post archive page for a single post.
	 *
	 * This function retrieves the URL of the author's post archive page for a single post based on the post ID.
	 *
	 * @param int $post_id The ID of the post.
	 * @return string|null The URL of the author's post archive page, or null if not found.
	 */
	function wpstream_get_single_post_author_link( $post_id ) {
		$author_post_url = get_author_posts_url( get_post_field( 'post_author', $post_id ) );

		return $author_post_url ? $author_post_url : null;
	}
}

add_post_type_support( 'page', 'excerpt' );

if ( ! function_exists( 'wpstream_the_breadcrumb' ) ) {
	/**
	 * The breadcrumbs
	 */
	function wpstream_the_breadcrumb() {
		if ( ! is_home() ) {
			echo '<nav aria-label="breadcrumb" class="breadcrumb-scroller mb-4 mt-2 py-2 px-3 bg-light rounded">';
			echo '<ol class="breadcrumb mb-0">';
			echo '<li class="breadcrumb-item"><a href="' . esc_url( home_url() ) . '"><i class="fa-solid fa-house"></i></a></li>';

			// display parent category names with links.
			if ( is_category() || is_single() ) {
				$cat_ids = wp_get_post_categories( get_the_ID() );

				foreach ( $cat_ids as $cat_id ) {
					$cat = get_category( $cat_id );
					echo '<li class="breadcrumb-item"><a href="' . esc_url( get_term_link( $cat->term_id ) ) . '">' . esc_html( $cat->name ) . '</a></li>';
				}
			}

			// display current page name.
			if ( is_page() || is_single() ) {
				echo '<li class="breadcrumb-item active" aria-current="page">' . esc_html( get_the_title() ) . '</li>';
			}

			echo '</ol>';

			echo '</nav>';
		}
	}


	add_filter( 'breadcrumbs', 'breadcrumbs' );

}

add_filter( 'the_password_form', 'wpstream_theme_pw_form' );

if ( ! function_exists( 'wpstream_theme_pw_form' ) ) {
	/**
	 * Theme pw form
	 */
	function wpstream_theme_pw_form() {
		$output = '

        <form action="' . get_option( 'siteurl' ) . '/wp-login.php?action=postpass" method="post" class="form-inline">' . "\n"
			. '<input name="post_password" type="password" size="" class="form-control me-2 my-1" placeholder="' . __( 'Password', 'hello-wpstream' ) . '"/>' . "\n"
			. '<input type="submit" class="btn btn-outline-primary my-1" name="Submit" value="' . __( 'Submit', 'hello-wpstream' ) . '" />' . "\n"
			. '</p>' . "\n"
			. '</form>' . "\n";

		return $output;
	}
}
