<?php

if ( !function_exists( 'wp_body_open' ) ):
	/**
	 * Shim for sites older than 5.2.
	 *
	 * @link https://core.trac.wordpress.org/ticket/12563
	 */
	function wp_body_open() {
		do_action( 'wp_body_open' );
	}
endif;

/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package newshit
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function newshit_body_classes( $classes ) {
	// Adds a class of hfeed to non-singular pages.
	if ( !is_singular() ) {
		$classes[] = 'hfeed';
	}

	// Adds a class of no-sidebar when there is no sidebar present.
	if ( !is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-sidebar';
	}

	return $classes;
}
add_filter( 'body_class', 'newshit_body_classes' );

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function newshit_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'newshit_pingback_header' );

/**
 * Allow Html
 */
if ( !function_exists( 'newshit_allow_html' ) ) {
	function newshit_allow_html() {
		return array(
			'a'      => array(
				'href'   => array(),
				'target' => array(),
				'title'  => array(),
				'rel'    => array(),
			),
			'strong' => array(),
			'small'  => array(),
			'span'   => array(
				'style' => array(),
			),
			'p'      => array(),
			'br'     => array(),
			'img'    => array(
				'src'    => array(),
				'title'  => array(),
				'alt'    => array(),
				'width'  => array(),
				'height' => array(),
				'class'  => array(),
			),
			'h1'     => array(),
			'h2'     => array(),
			'h3'     => array(),
			'h4'     => array(),
			'h5'     => array(),
			'h6'     => array(),
		);
	}
}

/**
 * Add span tag in archive list count number
 */
function newshit_add_span_archive_count( $links ) {
	$links = str_replace( '</a>&nbsp;(', '</a> <span class="post-count-number">(', $links );
	$links = str_replace( ')', ')</span>', $links );
	return $links;
}

add_filter( 'get_archives_link', 'newshit_add_span_archive_count' );

/**
 * Add span tag in category list count number
 */
function newshit_add_span_category_count( $links ) {
	$links = str_replace( '</a> (', '</a> <span class="post-count-number">(', $links );
	$links = str_replace( ')', ')</span>', $links );
	return $links;
}

add_filter( 'wp_list_categories', 'newshit_add_span_category_count' );

/**
 * Prints HTML with meta information for the current post-date/time.
 */
if ( !function_exists( 'newshit_posted_on' ) ):

	function newshit_posted_on() {
		$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
		if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
			$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
		}

		$time_string = sprintf( $time_string,
			esc_attr( get_the_date( DATE_W3C ) ),
			esc_html( get_the_date() ),
			esc_attr( get_the_modified_date( DATE_W3C ) ),
			esc_html( get_the_modified_date() )
		);

		$posted_on = sprintf(
			/* translators: %s: post date. */
			esc_html_x( ' %s', 'post date', 'newshit' ), // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
			'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
		);

		echo '<span class="posted-on"><i class="far fa-calendar-check"></i>' . $posted_on . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

	}
endif;

/**
 * Prints HTML with meta information for the current author.
 */
if ( !function_exists( 'newshit_posted_by' ) ):

	function newshit_posted_by() {
		$byline = sprintf(
			/* translators: %s: post author. */
			esc_html_x( ' %s', 'post author', 'newshit' ), // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
			'<span class="author vcard">' . esc_html( get_the_author() ) . '</span>'
		);

		echo '<span class="byline"><i class="far fa-user"></i> ' . $byline . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

	}
endif;

/**
 * Prints HTML with meta information for the tags.
 */
if ( !function_exists( 'newshit_post_tags' ) ):

	function newshit_post_tags() {
		// Hide category and tag text for pages.
		if ( 'post' === get_post_type() ) {

			/* translators: used between list items, there is a space after the comma */
			$tags_list = get_the_tag_list( '', esc_html_x( '', 'list item separator', 'newshit' ) ); // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
			if ( $tags_list ) {
				/* translators: 1: list of tags. */
				printf( '<span class="tags-links"><span class="tag-title">' . esc_html__( 'Tags:', 'newshit' ) . '</span>' . esc_html__( ' %1$s', 'newshit' ) . '</span>', $tags_list ); // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
			}

		}
	}
endif;

/**
 * Prints HTML with meta information for the categories.
 */
if ( !function_exists( 'newshit_post_categories' ) ):

	function newshit_post_categories() {
		if ( 'post' === get_post_type() ) {

			/* translators: used between list items, there is a space after the comma */
			$categories_list = get_the_category_list( esc_html__( ', ', 'newshit' ) );
			if ( $categories_list ) {
				/* translators: 1: list of categories. */
				printf( '<span class="cat-links"><i class="far fa-folder"></i>' . esc_html__( '%1$s', 'newshit' ) . '</span>', $categories_list ); // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings
			}

		}
	}
endif;

/**
 * Prints HTML with meta information for the comments.
 */
if ( !function_exists( 'newshit_comment_count' ) ):

	function newshit_comment_count() {
		if ( !post_password_required() && ( comments_open() || get_comments_number() ) && get_comments_number() != 0 ) {
			echo '<span class="comments-link"><i class="far fa-comments"></i>';
			comments_popup_link( '', '' . esc_html__( '1', 'newshit' ) . ' <span class="comment-count-text">' . esc_html__( 'Comment', 'newshit' ) . '</span>', '% <span class="comment-count-text">' . esc_html__( 'Comments', 'newshit' ) . '</span>' );
			echo '</span>';
		}
	}
endif;

if ( !function_exists( 'newshit_entry_footer' ) ):
	/**
	 * Prints HTML with meta information for the categories, tags and comments.
	 */
	function newshit_entry_footer() {
		edit_post_link(
			sprintf(
				wp_kses(
					/* translators: %s: Name of current post. Only visible to screen readers */
					__( 'Edit <span class="screen-reader-text">%s</span>', 'newshit' ),
					array(
						'span' => array(
							'class' => array(),
						),
					)
				),
				wp_kses_post( get_the_title() )
			),
			'<span class="edit-link">',
			'</span>'
		);
	}
endif;

if ( !function_exists( 'newshit_post_thumbnail' ) ):
	/**
	 * Displays an optional post thumbnail.
	 *
	 * Wraps the post thumbnail in an anchor element on index views, or a div
	 * element when on single views.
	 */
	function newshit_post_thumbnail() {
		if ( post_password_required() || is_attachment() || !has_post_thumbnail() ) {
			return;
		}

		if ( is_singular() ):
		?>

			<div class="post-singlebnail">
				<?php the_post_thumbnail(); ?>
			</div><!-- .post-singlebnail -->

			<?php else: ?>

			<a class="post-singlebnail" href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
					<?php
						the_post_thumbnail(
						'post-singlebnail',
						array(
							'alt' => the_title_attribute(
								array(
									'echo' => false,
								)
							),
						)
					);
				?>
			</a>
		<?php
endif; // End is_singular().
}
endif;

/**
 * Words limit
 */
function newshit_words_limit( $text, $limit ) {
	$words = explode( ' ', $text, ( $limit + 1 ) );

	if ( count( $words ) > $limit ) {
		array_pop( $words );
	}

	return implode( ' ', $words );
}

/**
 * Comments Pagination
 */
if ( !function_exists( 'newshit_comments_pagination' ) ) {
	function newshit_comments_pagination() {
		the_comments_pagination( array(
			'screen_reader_text' => ' ',
			'prev_text'          => '<i class="fa fa-angle-left"></i>',
			'next_text'          => '<i class="fa fa-angle-right"></i>',
			'type'               => 'list',
			'mid_size'           => 1,
		) );
	}
}

/**
 * Post Pagination
 */
if ( !function_exists( 'newshit_Post_pagination' ) ) {
	function newshit_Post_pagination() {
		the_posts_pagination( array(
			'screen_reader_text' => '',
			'prev_text'          => '<i class="fa fa-angle-left"></i>',
			'next_text'          => '<i class="fa fa-angle-right"></i>',
			'type'               => 'list',
			'mid_size'           => 1,
		) );
	}
}

/**
 * Prints post's first category
 */

if ( !function_exists( 'newshit_post_first_category' ) ):

	function newshit_post_first_category() {
		if ( 'post' === get_post_type() ) {

			$post_category_list = get_the_terms( get_the_ID(), 'category' );
			$post_first_category = $post_category_list[0];
			if ( !empty( $post_first_category->slug ) ) {
				echo '<span class="cat-links"><i class="far fa-folder"></i><a href="' . get_term_link( $post_first_category->slug, 'category' ) . '">' . $post_first_category->name . '</a></span>';
			}
		}
	}
endif;

/**
 * Prints post's first without Link category
 */

 if ( !function_exists( 'newshit_post_first_nolink_category' ) ):

	function newshit_post_first_nolink_category() {
		if ( 'post' === get_post_type() ) {

			$post_category_list = get_the_terms( get_the_ID(), 'category' );
			$post_first_category = $post_category_list[0];
			if ( !empty( $post_first_category->slug ) ) {
				echo '<span class="cat-no-link"><i class="far fa-folder"></i>' . $post_first_category->name . '</span>';
			}
		}
	}
endif;


/**
 * Next Preview Post Pagination
 */
function newshit_post_navigation() {
	$prev_post = get_previous_post();
	$next_post = get_next_post();
	if ( !$prev_post && !$next_post ) {
		return;
	}
	?>
    <nav class="newshit-post-navication-single" role="navigation">
        <h2 class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'newshit' ); ?></h2>
        <div class="nav-links">
            <?php
				if ( $prev_post ):
					?>
                <div class="nav-previous post-single-nav">
					<a href="<?php echo esc_url( get_the_permalink( $prev_post->ID ) ); ?>" class="nav-label">
						<span class="nav-subtitle"><?php esc_html_e( 'Previous Post', 'newshit' ); ?></span>
					</a>
                    <div class="nav-holder">
						<div class="nav-title">
							<a href="<?php echo esc_url( get_the_permalink( $prev_post->ID ) ); ?>">
								<span class="nav-title"><?php echo wp_kses_post( get_the_title( $prev_post->ID ) ); ?></span>
							</a>
						</div>
                    </div>
                </div>
            <?php endif; ?>

            <?php
				if ( $next_post ):
					?>
				<div class="nav-next post-single-nav">
					<a href="<?php echo esc_url( get_the_permalink( $next_post->ID ) ); ?>" class="nav-label">
						<span class="nav-subtitle"><?php esc_html_e( 'Next Post', 'newshit' ); ?></span>
					</a>
                    <div class="nav-holder">
						<div class="nav-title">
							<a href="<?php echo esc_url( get_the_permalink( $next_post->ID ) ); ?>">
								<span class="nav-title"><?php echo wp_kses_post( get_the_title( $next_post->ID ) ); ?></span>
							</a>
						</div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </nav>
    <?php
}

/**
 * newshit Post Share Function
 */
if ( !function_exists( 'newshit_post_share' ) ):

	function newshit_post_share() {
		global $post;
		$post_title = get_the_title();
		$post_id = get_the_ID();
		$post_title = htmlspecialchars( urlencode( html_entity_decode( esc_attr( get_the_title() ), ENT_COMPAT, 'UTF-8' ) ), ENT_COMPAT, 'UTF-8' );
		$post_url = get_permalink( $post_id );
		$pin_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
		$protocol = is_ssl() ? 'https' : 'http';
		?>
			<div class="share-this-post">
				<ul class="social-icons m0p0ln">
					<li>
						<a href="https://www.facebook.com/sharer.php?u=<?php echo rawurlencode( esc_url( $post_url ) ); ?>" class="social-facebook">
							<i class="fab fa-facebook-f"></i>
						</a>
					</li>
					<li>
						<a href="https://twitter.com/share?text=<?php echo esc_attr( wp_strip_all_tags( $post_title ) ); ?>&amp;url=<?php echo rawurlencode( esc_url( $post_url ) ); ?>" class="social-facebook">
							<i class="fab fa-twitter"></i>
						</a>
					</li>
					<li>
						<a href="https://www.pinterest.com/pin/create/button/?url=<?php echo rawurlencode( esc_url( $post_url ) ); ?>&amp;media=<?php echo esc_url( wp_get_attachment_url( get_post_thumbnail_id( $post_id ) ) ); ?>&amp;description=<?php echo urlencode( wp_trim_words( strip_shortcodes( get_the_content( $post_id ) ), 40 ) ); ?>" class="social-pintarest">
							<i class="fab fa-pinterest"></i>
						</a>
					</li>
					<li>
						<a href="https://www.linkedin.com/shareArticle?mini=true&amp;url=<?php echo rawurlencode( esc_url( $post_url ) ); ?>&amp;title=<?php echo esc_attr( wp_strip_all_tags( $post_title ) ); ?>&amp;summary=<?php echo urlencode( wp_trim_words( strip_shortcodes( get_the_content( $post_id ) ), 40 ) ); ?>&amp;source=<?php echo esc_url( home_url( '/' ) ); ?>" class="social-linkedin">
							<i class="fab fa-linkedin-in"></i>
						</a>
					</li>
				</ul>
			</div>
		<?php }
endif;

/**
 * newshit Breadcrumb Function
 */
if ( ! function_exists( 'newshit_breadcrumb' ) ) : 
	function newshit_breadcrumb() {

		global $post;
		echo '<ul class="newshit-breadcrumb">';
		$delimiter = '<span class="breadcrumb-delimiter">/</span>';
		$home = '<li><a href="' . esc_url(home_url()) . '">' . esc_html__('Home', 'newshit') . '</a>' . $delimiter . '</li>';

		if ( !is_front_page() ) {
			echo $home;

			if ( is_home() ) {

				echo '<li>' . esc_html__('Blog', 'newshit') . '</li>';

			} elseif ( is_category() ) {

				$category = get_category(get_query_var('cat'));
				$cat_link = get_category_link($category->cat_ID);
				echo '<li><a href="' . esc_url($cat_link) . '">' . esc_html($category->name) . '</a></li>';
			
			} elseif ( is_single() && !is_singular('product') ) {

				$category = get_the_category();
				$cat_link = get_category_link( $category[0]->cat_ID );
				
					echo '<li><a href="' . esc_url( $cat_link ) . '">' . esc_html( $category[0]->cat_name ) . '</a>' . $delimiter . '</li>';
				
				echo '<li>' . wp_kses_post( get_the_title() ) . '</li>';
			
			} elseif ( is_page() ) {

				if ( $post->post_parent ) {
					$anc = get_post_ancestors( $post->ID );
					$anc = array_reverse( $anc );
					foreach ( $anc as $ancestor ) {
						echo '<li><a href="' . esc_url( get_permalink( $ancestor ) ) . '">' . get_the_title( $ancestor ) . '</a>' . $delimiter . '</li>';
					}
				}

				echo '<li>' . esc_html( get_the_title() ) . '</li>';
			} elseif ( is_author() ) {
				echo '<li>' . esc_html( get_the_author_meta( 'display_name', $author_id ) ) . '</li>';
			}elseif ( is_archive() ) {
				echo '<li> ' . esc_html( the_archive_title() ) . '</li>';
			} elseif ( is_search() ) {
				echo '<li>' . esc_html__( 'Search Results for', 'newshit' ) . ': ' .  esc_html( get_search_query() ) . '</li>';
			} elseif ( is_tag() ) {
				echo '<li>' . esc_html__( 'Tag', 'newshit' ) . ': ' . esc_html( single_tag_title('', false) ) . '</li>';
			} elseif ( is_404() ) {
				echo '<li>' . esc_html__( 'Error 404', 'newshit' ) . '</li>';
			} elseif ( is_singular('product') && !is_front_page() ) {

				global $product;

				if ( $product instanceof WC_Product ) {
					$category_ids = $product->get_category_ids();

					if ( $category_ids ) {
						$cat_link = get_term_link( $category_ids[0], 'product_cat' );
						echo '<li><a href="' . esc_url( $cat_link ) . '">' . esc_html( get_term_field( 'name', $category_ids[0], 'product_cat' ) ) . '</a>' . $delimiter . '</li>';
					}
				}

				echo '<li>' . wp_kses_post( get_the_title() ) . '</li>';
			} else {
			echo '<li>' . esc_html__( 'Home', 'newshit' ) . '</li>';
		}
		echo '</ul>';
	}
}
endif;

/**
* Iframe embed
*/

function newshit_iframe_embed( $tags, $context ) {
	if ( 'post' === $context ) {
		$tags['iframe'] = array(
			'src'             => true,
			'height'          => true,
			'width'           => true,
			'frameborder'     => true,
			'allowfullscreen' => true,
		);
	}
	return $tags;
}
add_filter( 'wp_kses_allowed_html', 'newshit_iframe_embed', 10, 2 );


function hide_fs_customizer_upsell_control() {
    ?>
    <style>
        #accordion-section-freemius_upsell,#fs_customizer_support {
            display: none !important;
        }
    </style>
    <?php
}
add_action( 'customize_controls_print_styles', 'hide_fs_customizer_upsell_control' );


/**
 * Purchase Demo Link
 */

 if ( ! function_exists( 'newshit_purchase_link' ) ) {
    function newshit_purchase_link() {
        $newshit_purchase = 'https://www.themeuniver.com/newshit-pro';
        $description = sprintf(
            __( 'Purchase the Pro Version for More Features. <a href="%s" target="_blank" class="Purchase-links">Purchase Now</a>', 'newshit' ),
            esc_url( $newshit_purchase )
        );
        return $description;
    }
}

/**
 * Delete the `Hello world!` post after successful demo import.
 */
function newshit_delete_hello_world() {
	$post = get_page_by_path('hello-world', OBJECT, 'post');
    if ($post) {
        wp_delete_post($post->ID,true);
    }
}

add_filter( 'ocdi/import_files', 'newshit_delete_hello_world' );



// Add custom meta field for category color
function newshit_category_color_field($tag) {
    $category_color = '';
    if (isset($tag->term_id)) {
        $category_color = get_term_meta($tag->term_id, 'category-color', true);
    }
    ?>
    <tr class="form-field">
        <th scope="row"><label for="category-color"><?php _e('Category Color', 'newshit'); ?></label></th>
        <td>
            <input type="text" name="category-color" id="category-color" class="color-field" value="<?php echo esc_attr($category_color); ?>" />
        </td>
    </tr>
    <?php
}
add_action('category_add_form_fields', 'newshit_category_color_field');
add_action('category_edit_form_fields', 'newshit_category_color_field');
add_action('web_story_category_add_form_fields', 'newshit_category_color_field');
add_action('web_story_category_edit_form_fields', 'newshit_category_color_field');

// Save custom meta field value
function newshit_save_category_color($term_id) {
    if (isset($_POST['category-color'])) {
        update_term_meta($term_id, 'category-color', sanitize_hex_color($_POST['category-color']));
    }
}
add_action('edited_category', 'newshit_save_category_color', 10, 2);
add_action('create_category', 'newshit_save_category_color', 10, 2);
add_action('edited_web_story_category', 'newshit_save_category_color', 10, 2);
add_action('create_web_story_category', 'newshit_save_category_color', 10, 2);

// Enqueue color picker scripts and styles
// Enqueue color picker scripts and styles
function newshit_enqueue_color_picker() {
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
}
add_action('admin_enqueue_scripts', 'newshit_enqueue_color_picker', 999);


// Initialize color picker
function newshit_color_picker_script() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Add color picker to the field
        $(document).on('focus', '.color-field', function() {
            $(this).wpColorPicker();
        });
    });
    </script>
    <?php
}
add_action('admin_footer', 'newshit_color_picker_script');

// Function to get category color
function get_category_color($category_id) {
    $category_color = get_term_meta($category_id, 'category-color', true);
    return $category_color;
}


if ( ! function_exists( 'newshit_front_post_cat' ) ) {
    function newshit_front_post_cat() {
        $categories = get_the_category();
        
        // Print the category names
        echo '<ul>';
        foreach ( $categories as $category ) {
            $category_id = $category->term_id;
            $category_color = get_category_color( $category_id );
            echo '<li><a href="' . get_category_link( $category->term_id ) . '" style="background-color: ' . $category_color . '">' . $category->name . '</a> </li>';
        }
        echo '</ul>';
    }
}

if ( ! function_exists( 'newshit_story_front_post_cat' ) ) {
    function newshit_story_front_post_cat() {
        $categories = get_the_terms( get_the_ID(), 'web_story_category' );

        // Check if there are categories
        if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
            echo '<ul class="web-story-categories">';
            foreach ( $categories as $category ) {
				$category_id = $category->term_id;
				$category_color = get_category_color( $category_id );
                echo '<li><a href="' . get_term_link( $category, 'web_story_category' ) . '" style="background-color: ' . $category_color . '">' . $category->name . '</a></li>';
            }
            
            echo '</ul>';
        }
    }
}

if ( ! function_exists( 'newshit_story_all_post_cat' ) ) {
    function newshit_story_all_post_cat() {
        $categories = get_the_terms( get_the_ID(), 'web_story_category' );

        // Check if there are categories
        if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
            echo '<ul class="web-story-categories">';
            foreach ( $categories as $category ) {
                echo '<li><a href="' . get_term_link( $category, 'web_story_category' ) . '">' . $category->name . '</a></li>';
            }
            
            echo '</ul>';
        }
    }
}

if ( ! function_exists( 'newshit_story_post_cat' ) ) {
    function newshit_story_post_cat() {
        $categories = get_the_terms( get_the_ID(), 'web_story_category' );

        // Check if there are categories
        if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
            echo '<ul class="web-story-categories"> <i class="far fa-folder"></i>';

            $isFirstCategory = true; // Flag to track the first category

            foreach ( $categories as $category ) {
                echo '<li><a href="' . get_term_link( $category, 'web_story_category' ) . '">' . $category->name . '</a></li>';

                // Display only the first category
                if ($isFirstCategory) {
                    break;
                }

                $isFirstCategory = false; // Set the flag to false after the first iteration
            }
            
            echo '</ul>';
        }
    }
}



function refresh_rewrite_rules() {
    flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'refresh_rewrite_rules' );

// Widget List
function newshit_select_sidebar_widgets() { 
	do_action('widgets_init');
	$sidebars = array(); 
	if ( isset( $GLOBALS['wp_registered_sidebars'] ) ) { 
		$sidebars = $GLOBALS['wp_registered_sidebars']; 
	} 
	$sidebars_choices = array(); 
	foreach ( $sidebars as $sidebar ) { 
		$sidebars_choices[ $sidebar['id'] ] = $sidebar['name']; 
	}  	
	return $sidebars_choices; 
} 


function newshit_customizer_quickedit() {
	// Default function
}
