<?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 newscope
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function newscope_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', 'newscope_body_classes' );

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

/**
 * Allow Html
 */
if ( !function_exists( 'newscope_allow_html' ) ) {
	function newscope_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 newscope_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', 'newscope_add_span_archive_count' );

/**
 * Add span tag in category list count number
 */

function newscope_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', 'newscope_add_span_category_count' );

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

	function newscope_posted_on() {
		// Retrieve the date the post was published and last modified
		$published_date = get_the_date(DATE_W3C);
		$modified_date = get_the_modified_date(DATE_W3C);
		$display_published_date = get_the_date();
		$display_modified_date = get_the_modified_date();
	
		// Prepare the time string
		$time_string = '<time class="entry-date published" 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>';
		}
	
		// Format the time string
		$time_string = sprintf(
			$time_string,
			esc_attr($published_date),
			esc_html($display_published_date),
			esc_attr($modified_date),
			esc_html($display_modified_date)
		);
	
		// Format the posted on string
		$posted_on = sprintf(
			esc_html_x('%s', 'post date', 'newscope'),
			'<a href="' . esc_url(get_permalink()) . '" rel="bookmark">' . $time_string . '</a>'
		);
	
		// Output the posted on string
		echo '<span class="posted-on"><i class="far fa-calendar-check"></i>' . $posted_on . '</span>';
	}	
endif;

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

	function newscope_posted_by() {
		$byline = sprintf(
			/* translators: %s: post author. */
			esc_html_x( ' %s', 'post author', 'newscope' ),
			'<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( 'newscope_post_tags' ) ):

	function newscope_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', 'newscope' ) );
			if ( $tags_list ) {
				/* translators: 1: list of tags. */
				printf( '<span class="tags-links"><span class="tag-title">' . esc_html__( 'Tags:', 'newscope' ) . '</span>' . esc_html__( ' %1$s', 'newscope' ) . '</span>', $tags_list ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}

		}
	}
endif;

/**
 * Prints HTML with meta information for the categories.
 */

if ( !function_exists( 'newscope_post_categories' ) ):

	function newscope_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__( ', ', 'newscope' ) );
			if ( $categories_list ) {
				/* translators: 1: list of categories. */
				printf( '<span class="cat-links"><i class="far fa-folder"></i>' . esc_html__( '%1$s', 'newscope' ) . '</span>', $categories_list ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}

		}
	}
endif;

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

	function newscope_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', 'newscope' ) . ' <span class="comment-count-text">' . esc_html__( 'Comment', 'newscope' ) . '</span>', '% <span class="comment-count-text">' . esc_html__( 'Comments', 'newscope' ) . '</span>' );
			echo '</span>';
		}
	}
endif;

if ( !function_exists( 'newscope_entry_footer' ) ):
	/**
	 * Prints HTML with meta information for the categories, tags and comments.
	 */
	function newscope_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>', 'newscope' ),
					array(
						'span' => array(
							'class' => array(),
						),
					)
				),
				wp_kses_post( get_the_title() )
			),
			'<span class="edit-link">',
			'</span>'
		);
	}
endif;

if ( !function_exists( 'newscope_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 newscope_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 newscope_words_limit( $text, $limit ) {
	$words = explode( ' ', $text, ( $limit + 1 ) );

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

	return implode( ' ', $words );
}

/**
 * Comments Pagination
 */

if ( !function_exists( 'newscope_comments_pagination' ) ) {
	function newscope_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( 'newscope_Post_pagination' ) ) {
	function newscope_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( 'newscope_post_first_category' ) ):

	function newscope_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( 'newscope_post_first_nolink_category' ) ):

	function newscope_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 newscope_post_navigation() {
	$prev_post = get_previous_post();
	$next_post = get_next_post();
	if ( !$prev_post && !$next_post ) {
		return;
	}
	?>
    <nav class="newscope-post-navication-single" role="navigation">
        <h2 class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'newscope' ); ?></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', 'newscope' ); ?></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', 'newscope' ); ?></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
}

/**
 * newscope Post Share Function
 */
if ( !function_exists( 'newscope_post_share' ) ):

	function newscope_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;

/**
 * newscope Breadcrumb Function
 */
if ( ! function_exists( 'newscope_breadcrumb' ) ) : 
	function newscope_breadcrumb() {

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

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

			if ( is_home() ) {

				echo '<li>' . esc_html__('Blog', 'newscope') . '</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', 'newscope' ) . ': ' .  esc_html( get_search_query() ) . '</li>';
			} elseif ( is_tag() ) {
				echo '<li>' . esc_html__( 'Tag', 'newscope' ) . ': ' . esc_html( single_tag_title('', false) ) . '</li>';
			} elseif ( is_404() ) {
				echo '<li>' . esc_html__( 'Error 404', 'newscope' ) . '</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', 'newscope' ) . '</li>';
		}
		echo '</ul>';
	}
}
endif;

/**
 * Iframe embed
 */

function newscope_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', 'newscope_iframe_embed', 10, 2 );



// Add custom meta fields for category color and image
function newscope_category_color_image_field($tag) {
    $category_color = '';
    $category_image = '';
    if (isset($tag->term_id)) {
        $category_color = get_term_meta($tag->term_id, 'category-color', true);
        $category_image = get_term_meta($tag->term_id, 'category-image', true);
    }
    ?>
    <tr class="form-field">
        <th scope="row"><label for="category-color"><?php esc_html_e('Category Color', 'newscope'); ?></label></th>
        <td>
            <input type="text" name="category-color" id="category-color" class="color-field" value="<?php echo esc_attr($category_color); ?>" />
        </td>
    </tr>
    <tr class="form-field">
        <th scope="row"><label for="category-image"><?php esc_html_e('Category Image', 'newscope'); ?></label></th>
        <td>
            <input type="button" class="button button-secondary" id="upload-category-image-button" value="<?php esc_attr_e('Upload Image', 'newscope'); ?>" />
            <input type="hidden" name="category-image" id="category-image" value="<?php echo esc_url($category_image); ?>" />
            <div id="category-image-preview">
                <?php if ($category_image) : ?>
                    <img src="<?php echo esc_url($category_image); ?>" style="max-width:100%;" />
                <?php endif; ?>
            </div>
        </td>
    </tr>
    <?php
}
add_action('category_add_form_fields', 'newscope_category_color_image_field');
add_action('category_edit_form_fields', 'newscope_category_color_image_field');
add_action('web_story_category_add_form_fields', 'newscope_category_color_image_field');
add_action('web_story_category_edit_form_fields', 'newscope_category_color_image_field');

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

// Enqueue color picker scripts and styles and media uploader
function newscope_enqueue_scripts() {
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_enqueue_media();
    wp_enqueue_script('newscope-media-uploader', get_template_directory_uri() . '/assets/js/admin-media-uploader.js', array('jquery'), null, true);
}
add_action('admin_enqueue_scripts', 'newscope_enqueue_scripts', 999);

// Initialize color picker
function newscope_color_picker_script() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        $('.color-field').wpColorPicker();
    });
    </script>
    <?php
}
add_action('admin_footer', 'newscope_color_picker_script');

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

// Function to get category image
function get_category_image($category_id) {
    return get_term_meta($category_id, 'category-image', true);
}


// front post category
if ( ! function_exists( 'newscope_front_post_cat' ) ) {
    function newscope_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>';
    }
}


// Widget List
function newscope_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; 
} 


// Fallback Function for Customizer 

function newscope_customizer_quickedit() {}


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


/**
 * Purchase Demo Link
 */

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

/**
 * Delete the `Hello world!` post after successful demo import.
 */
function newscope_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', 'newscope_delete_hello_world' );