<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package benqu
 */

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

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


/**
 * Category Badge With Color
 *
 * @return loop
 */
function benqu_category_name($cate_badge_length = -1) {

	$catgorys = get_the_category();
	if($cate_badge_length != -1) {
		$catgorys = array_slice($catgorys, 0, $cate_badge_length, true);
	}

	foreach( $catgorys as $key => $category):

		$meta = get_term_meta($category->term_id, 'benqu_cate_meta', true);
		$catemeta = !empty( $meta['cate-color'] )? $meta['cate-color'] : '#3b60fe';
	?>
		<a class="benqu-cate-name" href="<?php echo esc_url(get_category_link($category->term_id)); ?>" style="color:<?php echo esc_attr($catemeta); ?>">
			<span><?php echo esc_html($category->cat_name); ?></span>
		</a>
	<?php endforeach;
}

/**
 * Category Badge With Background Color
 *
 * @return loop
 */
function benqu_category_badge($cate_badge_length = -1) {

	$catgorys = get_the_category();
	if($cate_badge_length != -1) {
		$catgorys = array_slice($catgorys, 0, $cate_badge_length, true);
	}

	foreach($catgorys as $key => $category):

		$meta = get_term_meta($category->term_id, 'benqu_cate_meta', true);
		$catemeta = !empty( $meta['cate-color'] ) ? $meta['cate-color'] : '#3b60fe';
		$categoryClass = !empty( $category->parent ) ? esc_attr('child-category') : esc_attr('parent-category');
	?>
		<a class="benqu-cate-badge <?php echo $categoryClass; ?>" href="<?php echo esc_url(get_category_link($category->term_id)); ?>" style="background-color:<?php echo esc_attr($catemeta); ?>">
			<span><?php echo esc_html($category->cat_name); ?></span>
		</a>
	<?php endforeach;
}

/**
 * post Pagination
 */
function benqu_pagination() {
    global $wp_query;
    $links = paginate_links( array(
    'current'   => max( 1, get_query_var( 'paged' ) ),
    'total'     => $wp_query->max_num_pages,
    'type'      => 'list',
    'mid_size'  => 3,
    'prev_text' => '<i class="fal fa-long-arrow-left"></i>',
    'next_text' => '<i class="fal fa-long-arrow-right"></i>',
    ) );

    echo wp_kses_post( $links );
}

/**
 * benqu Post Suppurt Tag
 */

function benqu_wp_kses( $val ) {
    return wp_kses( $val, array(

        'p'      => array(
            'class' => array(),
            'style' => array(),
        ),

        'img'    => array(
            'src'   => array(),
            'alt'   => array(),
            'class' => array(),
            'style' => array(),
        ),
        'span'   => array(
            'class' => array(),
            'style' => array(),
        ),
        'small'  => array(),
        'div'    => array(
            'style' => array(),
        ),
        'strong' => array(
            'style' => array(),
        ),
        'b'      => array(
            'style' => array(),
        ),
        'br'     => array(),
        'h1'     => array(
            'style' => array(),
        ),
        'i'      => array(
            'class' => array(),
            'style' => array(),
        ),
        'ul'     => array(
            'class' => array(),
            'style' => array(),
        ),
        'ul'     => array(
            'id' => array(),
        ),
        'li'     => array(
            'class' => array(),
            'style' => array(),
        ),
        'li'     => array(
            'id' => array(),
        ),
        'h1'     => array(
            'style' => array(),
        ),
        'h2'     => array(),
        'h3'     => array(
            'style' => array(),
        ),
        'h4'     => array(
            'style' => array(),
        ),
        'h5'     => array(
            'style' => array(),
        ),
        'h6'     => array(
            'style' => array(),
        ),
        'a'      => array( 
            'href' => array(), 
            'target' => array(),
            'style' => array(),
        ),
        'iframe' => array( 'src' => array(), 'height' => array(), 'width' => array() ),

    ), '' );
}

function benqu_breadcrumb($seperator = '', $word = '') {

		global $post;
		$speaker_category = get_queried_object();
		$benqu_root_br_text = cs_get_option( 'benqu_root_br_text' );

		echo '<ol class="breadcrumb-item">';
		if (!is_home()) {
				echo '<li><a href="';
				echo esc_url(get_home_url('/'));
				echo '">';

				if(!empty($benqu_root_br_text)){
						esc_html_e($benqu_root_br_text);
				} else {
						esc_html_e( 'Home', 'benqu' );
				}

				echo "</a></li> " . esc_attr($seperator);
				if (is_category() || is_single()) {

						if(is_single()) {
								$category = get_the_category()[0];
						} else {
								$category = get_category( get_query_var( 'cat' ) );
						}

						if(!empty( $category )){
								echo '<li> <a href='.get_category_link($category->term_id). '>';
						}

						$post = get_queried_object();
						$postType = get_post_type_object( get_post_type( $post ) );

						if ( !empty( $category ) ) {
							echo esc_html( $category->cat_name ) . '</a> </li>';
						} else if ( $postType ) {
							echo esc_html( $postType->labels->singular_name ) . '</a></li>';
						}

						if ( is_single() ) {
								echo '<li>'.benqu_wp_kses( $seperator );
								echo esc_html( $word ) != '' ? wp_trim_words( get_the_title(), $word ) : get_the_title();
								echo '</li>';
						}
				} elseif ( is_page() && !$post->post_parent ) {
						echo '<li>';
								echo esc_html( $word ) != '' ? wp_trim_words( get_the_title(), $word ) : get_the_title();
						echo '</li>';
				} elseif ( is_page() && $post->post_parent ) {
						$parent_id = $post->post_parent;
						$breadcrumb_page = array();
						while($parent_id){
							$page = get_page($parent_id);
							$breadcrumb_page[] = '<li><a href="'.esc_url(get_permalink($page->ID)).'">'.get_the_title($page->ID).'</a></li>';
							$parent_id = $page->post_parent;
						}
						$breadcrumb_page = array_reverse($breadcrumb_page);
						for($i = 0; $i < count($breadcrumb_page); $i++){				
							echo benqu_wp_kses($breadcrumb_page[$i]);
							echo esc_html( $seperator );
						}			
						echo '<li>';
						echo esc_html( $word ) != '' ? wp_trim_words( get_the_title(), $word ) : get_the_title();
						echo '</li>';
				}
		}

		if (isset($speaker_category->taxonomy)) {
				if ($speaker_category->taxonomy == 'speaker-category') {
						echo esc_html($speaker_category->name);
				}
		}

		if (is_tag()) {
			 ?>
			 <li> <?php single_tag_title(); ?></li>
			 <?php
		} elseif (is_day()) {
				echo "<li>" . esc_html__('Blogs for', 'benqu') . " ";
				the_time('F jS, Y');
				echo '</li>';
		} elseif (is_month()) {
				echo "<li>" . esc_html__('Blogs for', 'benqu') . " ";
				the_time('F, Y');
				echo '</li>';
		} elseif (is_post_type_archive('xs-speaker')) {
				$postType = get_post_type_object(get_post_type());
				echo "<li>" . esc_html($postType->labels->name);
				echo '</li>';
		} elseif (is_year()) {
				echo "<li>" . esc_html__('Blogs for', 'benqu') . " ";
				the_time('Y');
				echo '</li>';
		} elseif (is_author()) {
				echo "<li>" . esc_html__('Author Blogs', 'benqu');
				echo '</li>';
		} elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {
				echo "<li>" . esc_html__('Blogs', 'benqu');
				echo '</li>';
		} elseif (is_search()) {
				echo "<li>" . esc_html__('Search Result', 'benqu');
				echo '</li>';
		} elseif (is_404()) {
				echo "<li>" . esc_html__('404 Not Found', 'benqu');
				echo '</li>';
		}
		echo '</ol>';
}

/**
 * Search Form
 */
function my_search_form( $form ) {
    $form = '
    <form method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
        <div class="pfy-search-form input-group">
            <input type="search" value="' . get_search_query() . '" name="s" id="s" placeholder="'. esc_attr__( 'Search Here ...', 'benqu' ) .'" />
            <button class="search-btn">'.esc_html__('Search', 'benqu').'</button>
        </div>
    </form>';

    return $form;
}

add_filter( 'get_search_form', 'my_search_form', 100 );


/**
 * benqu Single Post Nav
 */
function benqu_single_post_pagination(){ 
    $benqu_prev_post = get_previous_post();
    $benqu_next_post = get_next_post();
?>
<div class="post-next-prev pfy__post_np">
    <div class="row">
        <?php 
             if($benqu_prev_post || $benqu_next_post):
        ?>
        <div class="col-md-5">
            <div class="nav-post-item prev-post-item d-flex align-items-center">
                <div class="post_nav_inner">                  
                    <a class="navi-link" href="<?php echo esc_url(get_the_permalink($benqu_prev_post));?>">
                        <?php if(has_post_thumbnail()):?>
                        <div class="bnq-navi__thumb">                            
                            <img src="<?php echo esc_url(get_the_post_thumbnail_url($benqu_prev_post, 'thumbnail'));?>" alt="<?php the_title_attribute();?>">
                        </div>                        
                        <?php endif;?>
                        <div class="bnq-navi__info">
                            <span><i class="fal fa-angle-left"></i> <?php esc_html_e( 'Previous', 'benqu' );?></span>
                            <h4><?php echo esc_html(get_the_title($benqu_prev_post));?></h4>
                        </div>
                    </a>
                </div>
            </div>
        </div>
        <?php endif;?>
        <div class="col-md-2 d-flex justify-content-center align-items-center">
            <span class="navi-shape"></span>
        </div>
        <?php 
            
            if($benqu_next_post):
        ?>
        <div class="col-md-5">
            <div class="nav-post-item next-post-item d-flex align-items-center">
                <div class="post_nav_inner">                  
                    <a class="navi-link" href="<?php echo esc_url(get_the_permalink($benqu_next_post));?>">
                        <div class="bnq-navi__info">
                            <span><?php esc_html_e( 'Next', 'benqu' );?> <i class="fal fa-angle-right"></i></span>
                            <h4><?php echo esc_html(get_the_title($benqu_next_post));?></h4>
                        </div>
                        <?php if(has_post_thumbnail()):?>
                            <div class="bnq-navi__thumb">                            
                                <img src="<?php echo esc_url(get_the_post_thumbnail_url($benqu_next_post, 'thumbnail'));?>" alt="<?php the_title_attribute();?>">
                            </div>                        
                        <?php endif;?>
                    </a>
                </div>
            </div>
        </div>
        <?php endif;?>
    </div>
</div>
<?php 
}



/**
 * Comment List Modification
 */

function benqu_comments( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;?>

	<li     <?php comment_class('comment');?> id="comment-<?php comment_ID()?>">
        <div class="comment-body">
            <?php if ( get_avatar( $comment ) ) {?>
                <div class="author-thumb">
                    <?php echo get_avatar( $comment, 60 ); ?>
                </div>
            <?php }?>

            <div class="comment-content">
                <h4 class="name"><?php comment_author_link()?></h4>                
                <span class="comment-date"><?php echo esc_html(get_the_time( get_option('date_format')));?></span>
                <?php if ( $comment->comment_approved == '0' ): ?>
                    <p><em><?php esc_html_e( 'Your comment is awaiting moderation.', 'benqu' );?></em></p>
                <?php endif;?>
                <?php comment_text();?>
                <div class="comment-footer">
                <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) );?>
                </div>
            </div>
        </div>
	</li>


<?php
}



/**
 * Comment Message Box
 */
function benqu_comment_reform( $arg ) {

	$arg['title_reply']   = esc_html__( 'Leave a comment', 'benqu' );
	$arg['comment_field'] = '<div class="row"><div class="col-md-12"><div class="input-field mb-30"><textarea id="comment" class="form_control" name="comment" cols="77" rows="3" placeholder="' . esc_attr__( "Comment", "benqu" ) . '" aria-required="true"></textarea></div></div></div>';

	return $arg;

}
add_filter( 'comment_form_defaults', 'benqu_comment_reform' );

/**
 * Comment Form Field
 */

function benqu_modify_comment_form_fields( $fields ) {
	$commenter = wp_get_current_commenter();
	$req       = get_option( 'require_name_email' );

	$fields['author'] = '<div class="row"><div class="col-md-6"><div class="input-field mb-30"><input type="text" name="author" id="author" value="' . esc_attr( $commenter['comment_author'] ) . '" placeholder="' . esc_attr__( "Name", "benqu" ) . '" size="22" tabindex="1"' . ( $req ? 'aria-required="true"' : '' ) . ' class="form_control" /></div></div>';

	$fields['email'] = '<div class="col-md-6"><div class="input-field mb-30"><input type="email" name="email" id="email" value="' . esc_attr( $commenter['comment_author_email'] ) . '" placeholder="' . esc_attr__( "Email", "benqu" ) . '" size="22" tabindex="2"' . ( $req ? 'aria-required="true"' : '' ) . ' class="form_control"  /></div></div>';

	$fields['url'] = '<div class="col-md-12"><div class="input-field mb-30"><input type="url" name="url" id="url" value="' . esc_attr( $commenter['comment_author_url'] ) . '" placeholder="' . esc_attr__( "Website", "benqu" ) . '" size="22" tabindex="2"' . ( $req ? 'aria-required="false"' : '' ) . ' class="form_control"  /></div></div></div>';

	return $fields;
}
add_filter( 'comment_form_default_fields', 'benqu_modify_comment_form_fields' );

// comment Move Field
function benqu_move_comment_field_to_bottom( $fields ) {
	$comment_field = $fields['comment'];
	unset( $fields['comment'] );
	$fields['comment'] = $comment_field;
	return $fields;
}
add_filter( 'comment_form_fields', 'benqu_move_comment_field_to_bottom' );

/**
 * Category Count Markup
 */
function benqu_category_html( $links ) {
    $links = str_replace( '</a> (', '<span class="item-count">(', $links );
    $links = str_replace( ')', ')</span></a>', $links );
    return $links;
}
add_filter( 'wp_list_categories', 'benqu_category_html' );

/**
 * Archive Count Markup
 */
function benqu_archive_html($links) {
    $links = str_replace('</a>&nbsp;(', '<span class="item-count">(', $links);
    $links = str_replace(')', ')</span></a>', $links);
    return $links;
}

add_filter('get_archives_link', 'benqu_archive_html');

function benqu_return( $cd ) {
   
	return $cd;
}


/* Ajax update cart total number */

add_filter( 'woocommerce_add_to_cart_fragments', 'benqu_woocommerce_sidebar_cart_count_number' );
function benqu_woocommerce_sidebar_cart_count_number( $fragments ) {
	ob_start();
	?>
	<span class="widget_cart_counter"><i class="total-cart total-like"><?php echo sprintf (_n( '%d', '%d', WC()->cart->cart_contents_count, 'benqu' ), WC()->cart->cart_contents_count ); ?></i></span>
	<?php
	
	$fragments['.widget_cart_counter'] = ob_get_clean();
	
	return $fragments;
}

add_filter( 'woocommerce_add_to_cart_fragments', 'benqu_woocommerce_sidebar_cart_count_number_header' );
function benqu_woocommerce_sidebar_cart_count_number_header( $fragments ) {
	ob_start(); ?>
	<span class="widget_cart_counter_header"><?php echo sprintf (_n( '%d', '%d', WC()->cart->cart_contents_count, 'benqu' ), WC()->cart->cart_contents_count ); ?> - <span class="cart-total"><?php echo WC()->cart->get_cart_subtotal(); ?></span></span>
	<?php
	
	$fragments['.widget_cart_counter_header'] = ob_get_clean();
	
	return $fragments;
}
