<?php
/**
 * Template part for displaying single comic collection
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package Toocheke
 */
$comic_order = get_option('toocheke-comics-order') ? get_option('toocheke-comics-order') : 'DESC';
$display_default = get_option('toocheke-comics-navigation') && 1 == get_option('toocheke-comics-navigation');
//ALL collections carousel
get_template_part('template-parts/content', 'collectionscarousel');
// Get latest collection
// Get the array of objects
$collection_term_objects = get_terms(array(
    'taxonomy' => 'collections',
    'parent' => 0,
    'orderby' => 'meta_value_num',
    'order' => $comic_order,
    'meta_query' => array(
        array(
            'key' => 'collection-order',
            'type' => 'NUMERIC',
        )),
    'show_count' => 0,
    'number' => 1,
));

// Define terms array
$collection_terms = array();
// Step through array of objects,
// and populate terms array
foreach ($collection_term_objects as $collection_term_object) {
    $collection_terms[] = $collection_term_object->slug;
}
$latest_collection_id = $collection_term_objects[0]->term_id;
?>

<!-- START LATEST COMIC-->
<div id="latest-comic">
 <div id="single-comic-row" class="row">
<div id="single-comic-col" class="col-lg-12">
                  <?php
$single_comics_args = array(
    'post_type' => 'comic',
    'post_status' => 'publish',
    'posts_per_page' => 1,
    'orderby' => 'post_date',
    'order' => $comic_order,
    'tax_query' => array(
        array(
            'taxonomy' => 'collections',
            'field' => 'slug',
            'terms' => $collection_terms,
        ),
    ),
);
$single_comic_query = new WP_Query($single_comics_args);
/* Start the Loop */
while ($single_comic_query->have_posts()): $single_comic_query->the_post();
    ?>
						                <?php
    get_template_part('template-parts/content', 'singlecomic');
    ?>
						                    <div class="single-comic-navigation">
						                    <?php
    $allowed_tags = array(
        'a' => array(
            'title' => array(),
            'href' => array(),
        ),
        'i' => array(
            'class' => array(),
        ),
        'img' => array(
            'class' => array(),
            'src' => array(),
        ),
    );
    $random_url = home_url() . '/?random&amp;nocache=1&amp;post_type=comic';
    $image_button_url = get_option('toocheke-random-button');
    $button = $display_default ? '<i class="fas fa-lg fa-random"></i>' : '<img class="comic-image-nav" src="' . esc_attr($image_button_url) . '" />';
    ?>
		    <?php
    if ('DESC' === $comic_order) {
        echo wp_kses(toocheke_get_comic_link('ASC', 'backward', $latest_collection_id, $display_default, 'first'), $allowed_tags);
        echo wp_kses(toocheke_adjacent_comic_link(get_the_ID(), $latest_collection_id, 'previous', $display_default), $allowed_tags);
    }
    ?>

		<a style="<?php echo esc_attr($latest_collection_id == 0 ? "" : "display:none") ?>" href="<?php echo esc_url($random_url); ?>" title="Random Comic"><?php echo $button ?></a>
		                       <?php
    if ('ASC' === $comic_order) {
        echo wp_kses(toocheke_adjacent_comic_link(get_the_ID(), $latest_collection_id, 'next', $display_default), $allowed_tags);
        echo wp_kses(toocheke_get_comic_link('DESC', 'forward', $latest_collection_id, $display_default, 'latest'), $allowed_tags);

    }
    ?>

						   <div id="comic-social">
					       <?php
    //check if plugin/post type has been activated
    if (post_type_exists('comic')):
        do_action('toocheke_get_sharing_buttons');
    endif;
    ?>


										                    </div>
						</div>
						                <?php

endwhile;

wp_reset_postdata();
?>
                  </div>
                  </div>
                  </div>
                   <!-- END LATEST COMIC-->
<div id="comics-section">&nbsp;</div>
<div id="main-content-row" class="row">
               <!--START LEFT COL-->
               <div class="col-lg-8">
                  <div id="left-col">
                     <div id="left-content">
						 <!-- START COMIC ARCHIVE-->
                         <div id="comic-archive-list">
					 <?php

if (have_posts() && post_type_exists('comic')):

    /**
     * Setup query to show the ‘comic’ post type for the latest collection with ‘10’ posts.
     * Output is comic thumbnail with comic title.
     */
    $comics_args = array(
        'post_type' => 'comic',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'paged' => $comics_paged,
        'orderby' => 'post_date',
        'order' => $comic_order,
        'tax_query' => array(
            array(
                'taxonomy' => 'collections',
                'field' => 'slug',
                'terms' => $collection_terms,
            ),
        ),
    );

    $comics_query = new WP_Query($comics_args);

    ?>
										<?php
    if ($comics_query->have_posts()):
    ?>
											 <h2 class="left-title"><?php esc_html_e('Latest Comics', 'toocheke');?></h2>
												 <ul id="comic-list">
													 <?php

    /* Start the Loop */
    while ($comics_query->have_posts()): $comics_query->the_post();

        /*
         * Include the Post-Type-specific template for the content.
         * If you want to override this in a child theme, then include a file
         * called content-___.php (where ___ is the Post Type name) and that will be used instead.
         */
        set_query_var('latest_collection_id', $latest_collection_id);
        set_query_var('show_comic_number', false);
        get_template_part('template-parts/content', 'comiclistitem');

    endwhile;

    ?>
								</ul>
								<?php
endif;
?>


            <!-- Start Pagination -->
			<?php
// Set up paginated links.
$comic_links = paginate_links(array(
    'format' => '?comics_paged=%#%#comics-section',
    'current' => $comics_paged,
    'total' => $comics_query->max_num_pages,
    'prev_text' => wp_kses(__('<i class=\'fas fa-chevron-left\'></i>', 'toocheke'), array('i' => array('class' => array()))),
    'next_text' => wp_kses(__('<i class=\'fas fa-chevron-right\'></i>', 'toocheke'), array('i' => array('class' => array()))),
    'add_args' => array('blog_paged' => $blog_paged),
));

if ($comic_links):

?>

<nav class="pagination">

            <?php echo wp_kses($comic_links, array(
    'a' => array(
        'href' => array(),
        'class' => array(),
    ),
    'i' => array(
        'class' => array(),
    ),
    'span' => array(
        'class' => array(),
    ),
)); ?>

    </nav><!--/ .navigation -->
    <?php
endif;
?>
 <!-- End Pagination -->
<?php
$comics_query = null;
wp_reset_postdata();

endif;
?>
</div>
				 <!-- END COMIC ARCHIVE-->

				 <?php
/**
 * Get latest six chapters of comics. If there are no chapters or chapters with no comics, don't display.
 */

$chapters_list = get_terms(array(
    'taxonomy' => 'collections',
    'parent' => $latest_collection_id,
    'orderby' => 'meta_value_num',
    'order' => $comic_order,
    'meta_query' => array(
        array(
            'key' => 'collection-order',
            'type' => 'NUMERIC',
        )),
    'show_count' => 0,
    'number' => 6,
));

if ($chapters_list) {
    ?>
    <!-- START COMIC CHAPTER LIST-->
    <div id="chapter-wrapper">
	<div class="row">
        <div class="col-md-12">
            <h2 class="left-title"><?php esc_html_e('Latest Chapters', 'toocheke');?></h2>
        </div>
		<?php

    foreach ($chapters_list as $chapter) {
        /**
         * Get latest post for this chapter
         */
        $link_to_first_comic = '';
        $args = array(
            'posts_per_page' => 1,
            'post_type' => 'comic',
            "tax_query" => array(
                array(
                    'taxonomy' => "collections", // use the $tax you define at the top of your script
                    'field' => 'term_id',
                    'terms' => $chapter->term_id, // use the current term in your foreach loop
                ),
            ),
            'no_found_rows' => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        );
        $first_comic_query = new WP_Query($args);
        // The Loop
        while ($first_comic_query->have_posts()): $first_comic_query->the_post();
            $link_to_first_comic = add_query_arg('col', $latest_collection_id, get_post_permalink()); // Display the image of the first post in category
        endwhile;
        printf(wp_kses_data('%1$s'), '<div class="col-md-4 collection-thumbnail">');
        printf(wp_kses_data('%1$s'), '<a href="' . esc_url($link_to_first_comic) . '">');
        $term_id = absint($chapter->term_id);
        $thumb_id = get_term_meta($term_id, 'collection-image-id', true);

        if (!empty($thumb_id)) {
            $term_img = wp_get_attachment_url($thumb_id);
            printf(wp_kses_data('%1$s'), '<img src="' . esc_attr($term_img) . '" /><br/>');
        }

        echo wp_kses_data($chapter->name);
        echo '</a></div>';
    }
    // Reset Post Data
    wp_reset_postdata();

    ?>
    </div><!--end chapters row-->
	<div class="col-md-12 more-chapters-wrapper">
	    <a class="btn btn-danger btn-xs" href="<?php echo esc_url(add_query_arg('col', $latest_collection_id, get_permalink(get_page_by_path('collections')))) ?>" role="button"><?php esc_html_e('More Chapters', 'toocheke');?></a>
    </div><!--end more wrapper-->
    </div><!--end chapters wrapper-->
    <!-- END COMIC CHAPTER LIST-->

	<?php
}
/**
 * Get latest six collections of comics. If there are no collections or collections with no comics, don't display.
 */

$collections_list = get_terms(array(
    'taxonomy' => 'collections',
    'parent' => 0,
    'orderby' => 'meta_value_num',
    'order' => $comic_order,
    'meta_query' => array(
        array(
            'key' => 'collection-order',
            'type' => 'NUMERIC',
        )),
    'show_count' => 0,
    'number' => 6,
));

if ($collections_list) {
    ?>
      <!-- START COMIC COLLECTION LIST-->
      <div id="collection-wrapper">
	<div class="row">
    <div class="col-md-12">
        <h2 class="left-title"><?php esc_html_e('Latest Collections', 'toocheke');?></h2>
    </div>
		<?php

    foreach ($collections_list as $collection) {
        /**
         * Get latest post for this collection
         */
        $link_to_first_comic = '';
        $args = array(
            'posts_per_page' => 1,
            'post_type' => 'comic',
            "tax_query" => array(
                array(
                    'taxonomy' => "collections", // use the $tax you define at the top of your script
                    'field' => 'term_id',
                    'terms' => $collection->term_id, // use the current term in your foreach loop
                ),
            ),
            'no_found_rows' => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        );
        $first_comic_query = new WP_Query($args);
        // The Loop
        while ($first_comic_query->have_posts()): $first_comic_query->the_post();
            $link_to_first_comic = add_query_arg('col', $latest_collection_id, get_post_permalink()); // Display the image of the first post in category
        endwhile;
        printf(wp_kses_data('%1$s'), '<div class="col-md-4 collection-thumbnail">');
        printf(wp_kses_data('%1$s'), '<a href="' . esc_url($link_to_first_comic) . '">');
        $term_id = absint($collection->term_id);
        $thumb_id = get_term_meta($term_id, 'collection-image-id', true);

        if (!empty($thumb_id)) {
            $term_img = wp_get_attachment_url($thumb_id);
            printf(wp_kses_data('%1$s'), '<img src="' . esc_attr($term_img) . '" /><br/>');
        }

        echo wp_kses_data($collection->name);
        echo '</a></div>';
    }
// Reset Post Data
    wp_reset_postdata();

    ?>
	</div><!--end collections row-->
	<div class="col-md-12 more-chapters-wrapper">
	    <a class="btn btn-danger btn-xs" href="<?php echo esc_url(add_query_arg('col', 0, get_permalink(get_page_by_path('collections')))) ?>" role="button"><?php esc_html_e('More Collections', 'toocheke');?></a>
	</div><!--end more wrapper-->
    </div><!--end collections wrapper-->
    <!-- END COMIC COLLECTION LIST-->
	<?php
}
