<?php
/**
 * Custom template tags for this theme
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package yankee
 */

 /**
 * Post Cat list
 */
function yankee_posted_in() {
    $categories_list = get_the_category_list( esc_html__( '', 'yankee' ) );

    if ( $categories_list ) {
        /* translators: 1: list of categories. */
        $posted_in = sprintf( esc_html__( '%1$s', 'yankee' ), $categories_list );
    } else {
        $posted_in = '';
    }

    return $posted_in;
}

/**
 * Post Meta
 */
function yankee_post_meta() {
    $meta = '<div class="entry-meta">
		<ul>
			<li>
				<a href="' . esc_url( get_the_permalink() ) . '"><i class="fal fa-eye"></i>'. yankee_get_views() .' '. esc_html__('Views', 'yankee') .'</a>
			</li> ';
			if ( !post_password_required() && ( comments_open() || get_comments_number() ) ) {
				$meta .= '<li><a href="' . esc_url( get_comments_link() ) . '"><i class="fal fa-comments"></i> ' . esc_html( get_comments_number() ) . ' ' . esc_html__( 'Comments', 'yankee' ) . '</a></li>';
			}
    	$meta .= '<li>
				<a href="' . esc_url( get_the_permalink() ) . '"><i class="fal fa-calendar-alt"></i> ' . esc_html( get_the_date( 'd M Y' ) ) . '</a>
			</li>
		</ul>
	</div>';

    return $meta;
}

/**
 * Post get View Count
 */
function yankee_get_views($id = false) {
	if( ! $id ) $id = get_the_ID();
	$number = get_post_meta( $id, '_yankee_views_count', true );
	if( empty($number) ) $number = 0;

	return $number;
}

/**
 * Post Update View Count
 */
function yankee_update_views() {
	if( ! is_single() || ! is_singular( 'post' ) ) return;

	$id = get_the_ID();

	$number = yankee_get_views( $id );
	if( empty($number) ) {
		$number = 1;
		add_post_meta( $id, '_yankee_views_count', $number );
	} else {
		$number++;
		update_post_meta( $id, '_yankee_views_count', $number );
	}
}
add_action( 'wp', 'yankee_update_views');

/**
 * Generate custom search form
 */
function yankee_search_form( $form ) {
    $form = '<form role="search" method="get" class="search-form yankee-search-form" action="' . esc_url( home_url( '/' ) ) . '" >
		<input type="search" class="search-field" placeholder="' . esc_attr__( 'Search your keyword...', 'yankee' ) . '" value="' . get_search_query() . '" name="s" />
		<button type="submit" class="search-submit"><i class="far fa-search"></i></button>
	</form>';

    return $form;
};

add_filter( 'get_search_form', 'yankee_search_form' );

/**
 * Post Pagination
 */
function yankee_posts_navigation( $pages = '' ) {
    global $wp_query, $wp_rewrite;
    $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

    if ( $pages == '' ) {
        global $wp_query;
        $pages = $wp_query->max_num_pages;

        if ( !$pages ) {
            $pages = 1;
        }
    }

    $pagination = [
        'base'      => str_replace( 999999999, '%#%', get_pagenum_link( 999999999 ) ),
        'format'    => '',
        'current'   => max( 1, get_query_var( 'paged' ) ),
        'total'     => $pages,
        'prev_text' => '<i class="far fa-angle-double-left"></i>',
        'next_text' => '<i class="far fa-angle-double-right"></i>',
        'type'      => 'list',
        'end_size'  => 3,
        'mid_size'  => 3,
    ];

    $return = paginate_links( $pagination );
    echo str_replace( "<ul class='page-numbers'>", '<ul class="page-pagination">', $return );
}

/**
 *  Add span to category post count
 */
if ( ! function_exists( 'yankee_cat_count_span' ) ) {
	function yankee_cat_count_span($links) {
		$links = str_replace('</a> (', '<span class="posts-count">(', $links);
		$links = str_replace(')', ')</span></a>', $links);
		return $links;
	};

	add_filter('wp_list_categories', 'yankee_cat_count_span');
}

/**
 * ! Add span to archive post count
 */
if ( ! function_exists( 'yankee_archive_count_span' ) ) {
	function yankee_archive_count_span($links) {
		$links = str_replace('</a>&nbsp;(', '<span class="posts-count">(', $links);
		$links = str_replace(')', ')</span></a> ', $links);
		return $links;
	};

	add_filter('get_archives_link', 'yankee_archive_count_span');
}

/**
 * Custom Comment List
 */
function yankee_comments_list( $comment, $args, $depth ) {
    $GLOBALS['comment'] = $comment; ?>

    <li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
        <div class="comment-body" id="div-comment-<?php comment_ID() ?>">
            <?php echo get_avatar( $comment, 100 ); ?>
            <div class="comment-content">
                <h6 class="comment-author">
                    <?php printf(__('%s','yankee'), get_comment_author_link()) ?>
                </h6>
                <span class="comment-time"><?php comment_time( get_option( 'date_format' ) ); ?></span>
                <div class="comment-text">
                    <?php if ($comment->comment_approved == '0') : ?>
                        <em><?php esc_html_e('Your comment is awaiting moderation.','yankee') ?></em>
                    <?php else : ?>
                        <?php comment_text() ?>
                    <?php endif; ?>
                </div>
                <div class="comment-reply">
                    <?php
                        comment_reply_link( array_merge( $args, array(
                            'add_below'  => 'div-comment',
                            'depth'      => $depth,
                            'max_depth'  => $args['max_depth'],
                            'reply_text' => '<i class="far fa-reply"></i>Reply'
                        ) ) );

                    ?>
                </div>
            </div>
        </div>
    <?php
    // IMPORTANT: Note that we do NOT close the opening tag, WordPress does this for us
}

/**
 * Related Post
 */
function yankee_related_post() {
    if ( is_singular('post') ) {
        $cats = get_the_terms(get_the_ID(), 'category' );
        $cat_ids = wp_list_pluck($cats,'term_id' );

        $post_count = !empty( yankee_get_option( 'related-post-count') ) ? yankee_get_option( 'related-post-count') : 2;
        $title = !empty( yankee_get_option( 'post-related-title') ) ? yankee_get_option( 'post-related-title') : 'Releted Post';
        $title_limit = !empty( yankee_get_option( 'related-title-limit') ) ? yankee_get_option( 'related-title-limit') : 10;

        $args = array(
            'post_type' => 'post',
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'id',
                    'terms' => $cat_ids,
                    'operator'=> 'IN'
                )),
            'posts_per_page' => $post_count,
            'ignore_sticky_posts' => 1,
            'orderby' => 'rand',
            'post__not_in' => array(get_the_ID())
        );
        $posts = new WP_Query( $args );

        if( $posts->have_posts() ) {
            ?>
                <div class="related-post">
                    <h3 class="related-title"><?php echo esc_html( $title ) ?></h3>
                    <div class="row">
                        <?php
                            while($posts->have_posts()) : $posts->the_post(); ?>
                                <div class="col-md-6">
                                    <div class="single-related-post">
                                        <?php if ( has_post_thumbnail() ) : ?>
                                            <div class="thumb">
                                                <?php the_post_thumbnail( 'medium-large' ) ?>
                                            </div>
                                        <?php endif; ?>
                                        <div class="desc">
                                            <span class="date">
                                                <i class="far fa-calendar-alt"></i>  <?php echo esc_html( get_the_date('d M Y') ) ?>
                                            </span>
                                            <h4>
                                                <a href="<?php echo esc_url( get_the_permalink() ) ?>">
                                                    <?php
                                                        $title = wp_trim_words(get_the_title(), $title_limit );
                                                        echo wp_kses_post( $title );
                                                    ?>
                                                </a>
                                            </h4>
                                            <?php
                                                $the_content = wp_trim_words(get_the_content(), 12 );
                                                echo wpautop( wp_kses_post( $the_content ) );
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile;
                            wp_reset_postdata();
                        ?>
                    </div>
                </div>
            <?php
        }
    }
}

/**
 * Yankee author info
 */
function yankee_author_info() {

    global $post;
    $user_id = get_the_author_meta('ID');

    // Get author's display name - NB! changed display_name to first_name. Error in code.
    $display_name = get_the_author_meta( 'display_name', $post->post_author );

    // If display name is not available then use nickname as display name
    if ( empty( $display_name ) ) {
        $display_name = get_the_author_meta( 'nickname', $post->post_author );
    }

    $user_description   = get_the_author_meta( 'user_description', $post->post_author );
	$user_posts = get_author_posts_url( get_the_author_meta( $user_id , $post->post_author));
    $user_avatar = get_avatar( $user_id , 180 );

    $user_meta = get_user_meta( $user_id, 'yankee_user_metaboxes', true );

    ?>
        <div class="author-info-box">
            <div class="author-avatar">
                <?php echo wp_kses_post( $user_avatar ); ?>
            </div>
            <div class="author-desc">
                <span class="written-by"><?php echo esc_html_e( 'Written by', 'yankee' ) ?></span>
                <h3 class="name">
                    <a href="<?php echo esc_url( $user_posts ) ?>"> <?php echo esc_html( $display_name ) ?> </a>
                </h3>
                <?php
                    echo wpautop( $user_description );

                    if( !empty( $user_meta['user_social_links'] ) ) : ?>
                        <ul class="user-links">
                            <?php foreach ( $user_meta['user_social_links'] as $item ) : ?>
                            <li>
                                <a href="<?php echo esc_url( $item['social_url'] ) ?>"><i class="<?php echo esc_attr( $item['social_icon'] ) ?>"></i></a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif;
                ?>
            </div>
        </div>
    <?php
}

/**
 * Post nav
 */
function yankee_post_nav() {
    global $post;
    if ( 'post' === get_post_type() ) {
        $prev = get_previous_post();
        $next = get_next_post();
        ?>
            <div class="post-nav">
				<div class="row justify-content-between">
                    <?php if ( !empty( $prev ) ) :
                        $prev_id = $prev->ID; ?>
                        <div class="col-sm-6">
                            <div class="prev-post">
                                <span><?php echo esc_html__( 'Prev Post', 'yankee' ) ?></span>
                                <a href="<?php echo esc_url( get_permalink( $prev_id ) ) ?>">
                                    <?php
                                        $title = wp_trim_words(get_the_title($prev_id), 4 );
                                        echo wp_kses_post( $title );
                                    ?>
                                </a>
                            </div>
                        </div>
                    <?php endif; if ( !empty( $next ) ) :
                        $next_id = $next->ID; ?>
                        <div class="col-sm-6">
                            <div class="next-post">
                                <span><?php echo esc_html__( 'Next Post', 'yankee' ) ?></span>
                                <a href="<?php echo esc_url( get_permalink( $next_id ) ) ?>">
                                    <?php
                                        $title = wp_trim_words(get_the_title($next_id), 4 );
                                        echo wp_kses_post( $title );
                                    ?>
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
				</div>
			</div>
        <?php
    }
}

/**
 * Post Share
 */
function yankee_post_share() {

    global $post;
    if(!isset($post->ID)) return;

    // Get Post infomations
    $permalink = esc_url( get_permalink($post->ID) );
    $post_title = esc_html( get_the_title( $post->ID ) );
    $post_excerpt = wp_kses_post( get_the_excerpt() );

    // Get sharabela sites
    $share_items = yankee_get_option( 'social-share-item' );
    $share = $share_items['enabled'];

    $html = '';
    if( array_key_exists('twitter', $share) ) {
        $html .= '<li><a target="_blank" href="https://twitter.com/intent/tweet?text=' .$post_title. '&url=' .$permalink. '" title="Twitter"><i class="fab fa-twitter"></i></a></li>';
    }
    if( array_key_exists('facebook', $share) ) {
        $html .= '<li><a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=' .$permalink. '" title="Facebook"><i class="fab fa-facebook-f"></i></a></li>';
    }
    if( array_key_exists('pinterest', $share) ) {
        $html .= '<li><a target="_blank" href="https://www.pinterest.com/pin/create/button/?url=' .$permalink. '&description=' .$post_title. '" title="Pinterest"><i class="fab fa-pinterest-p"></i></a></li>';
    }
    if( array_key_exists('linkedin', $share) ) {
        $html .= '<li><a target="_blank" href="https://www.linkedin.com/shareArticle?mini=true&url=' .$permalink. '&title=' .$post_title. '&summary=' .esc_url( get_home_url('/') ). '&source=' .get_bloginfo( 'name' ). '" title="LinkedIn"><i class="fab fa-linkedin-in"></i></a></li>';
    }
    if( array_key_exists('google', $share) ) {
        $html .= '<li><a target="_blank" href="https://plus.google.com/share?url=' .$permalink. '" title="Google Plus"><i class="fab fa-google-plus-g"></i></a></li>';
    }
    if( array_key_exists('tumblr', $share) ) {
        $html .= '<li><a target="_blank" href="http://www.tumblr.com/share/link?url=' .$permalink. '&name=' .$post_title. '&description=' .$post_excerpt. '" title="Tumblr"><i class="fab fa-tumblr"></i></a></li>';
    }
    if( array_key_exists('reddit', $share) ) {
        $html .= '<li><a target="_blank" href="http://reddit.com/submit?url=' .$permalink. '&title=' .$post_title. '" target="_blank" title="Reddit"><i class="fab fa-reddit-alien" aria-hidden="true"></i></a></li>';
    }
    if( array_key_exists('vk', $share) ) {
        $html .= '<li><a target="_blank" href="http://vk.com/share.php?url=' .$permalink. '" target="_blank" title="VK"><i class="fab fa-vk"></i></a></li>';
    }

    echo '<ul>'. $html .'</ul>';
}

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;