<?php
/**
 * Template Name: Story
 *
 */
 ?>
<?php get_header(); ?>
 <?php 
	global $wpdb;
	$query_pagination = "SELECT concat(YEAR(p.post_date),'-',MONTH(p.post_date)) as post_ym, p.*
	FROM {$wpdb->posts} AS p
	WHERE p.post_type = 'story' AND p.post_status = 'publish'
	GROUP BY post_ym";
	$total = $wpdb->get_var( "SELECT COUNT(1) FROM (${query_pagination}) AS combined_table" );
	$items_per_page = 4;
	$cpage = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
	$offset = ( $cpage * $items_per_page ) - $items_per_page;
	$postByYearMonth = $wpdb->get_results( $query_pagination . " ORDER BY p.post_date DESC LIMIT ${offset}, ${items_per_page}" );
	$pageCnt = count($postByYearMonth);
	if($pageCnt == 1 ) {
		$firstObj = $lastObj = $postByYearMonth[0];
	} else {
		$firstObj = $postByYearMonth[0];
		$lastObj = $postByYearMonth[$pageCnt - 1];
	}
    $startDate = date('Y-m-t',strtotime($firstObj->post_date));
	$endDate = date('Y-m-d',strtotime($lastObj->post_date));
 	function weekOfMonth($date = NULL) {
		if($date) {
			$d = date('d',strtotime($date));
			$m = date('m',strtotime($date));
			$Y = date('Y',strtotime($date));
			$no_of_days = cal_days_in_month(CAL_GREGORIAN,$m,$Y);
		}
		return ceil($d / 7);
	}
	function weekOfMonthOld($date = NULL) {
		if($date) {
			if(is_numeric($date) && ctype_digit($date) && strtotime(date('Y-m-d H:i:s',$date)) === (int)$date)
				$unix_timestamp = $date;
			else
				$unix_timestamp = strtotime($date);
		} else $unix_timestamp = time();
	
		return (ceil((date('d', $unix_timestamp) - date('w', $unix_timestamp) - 1) / 7) + 1);
	}
 ?>
    <div id="full-content" class="media-coverage-page">
	    <section style="background: url('<?php echo home_url(); ?>/wp-content/uploads/2018/11/media-coverage-banner-bg.jpg')no-repeat center/cover;"  class="media-banner-bg">  
	      <div class="container">
	          <h1 class="page-title-cus"><?php if(is_page(134)) { echo 'Three Longs & Three Shorts'; } else { the_title(); } ?></h1>
	      </div>
	    </section>
		
			<section class="section-padding">
				<div class="container">
					<div class="row resource-content">
						<div class="story-outer col-12">
								<?php
									$year_check = "";
									$the_query = new WP_Query( array('posts_per_page'=>-1,
									'post_type'=>'story',
									'date_query' => array(
										'column' => 'post_date',
										'after' => $endDate,
										'before' => $startDate,
										'inclusive' => true 
									),
									'tax_query', array(
											array(
											'taxonomy' => 'category',
											'orderby' => 'category',
											'order' => 'DESC',
											'field' => 'slug',
											'terms' => array( 'long-read','short-read')
											)
										),
									'orderby' => array(
										'post_date' => 'DESC',
									),
									'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
									); 
									//echo $the_query->request;exit;
									$cnt = 1;		
									$tab = "";$tab_content = "";$html = "";$sub_html = "";
									$year_week_check = "";
									$weekly_post_html = "";
									$posts = array();
									while ($the_query -> have_posts()) : $the_query -> the_post(); 
									$year = "";	
									// Assign the year to a variable
									//$year = the_date('M Y', '', '', FALSE);
									$year = get_the_time('M Y');
									$week = weekOfMonth(get_the_time('Y-m-d'));
									$year_week = $year.'-'.$week;
									$category = get_the_category($post->ID);
									$postData = array(
										'publish_time' => get_the_time('d M, Y'),
										'title'  => get_the_title(),
										'desc'   => pov_excerpt( get_the_excerpt(), '250'),
										'permalink' => get_the_permalink()
									); 
									$posts[$year]['week'][$week][$category[0]->cat_name][] = $postData;
									?>
									<?php endwhile; ?>
									<?php $cnt = 1; ?>
									<?php foreach($posts as $my_key=>$post): ?>
										<section class="month-wrapper <?php if($cnt==1) echo 'open'; ?>">
											<div class="month-header">
												<div class="month-name"><?php echo $my_key; ?></div>
												<div class="tabs">
													<?php //ksort($post['week']); ?>
													<ul>
														<?php $wcnt = 1; foreach($post['week'] as $key=>$pv): ?>
														<!-- <li data-link="week<?php echo $wcnt; ?>" class="<?php if($wcnt==1) echo 'active'; ?>">Week <?php echo $wcnt; ?></li> -->
														<li data-link="week<?php echo $key; ?>" class="<?php if($wcnt==1) echo 'active'; ?>">Week <?php echo $key; ?></li>	
														<?php $wcnt++; endforeach; ?>
													</ul>
												</div>
												<span class="icon"></span>
											</div>
											<section class="tabs-data-wrapper ">
													<?php $wcnt = 1;  foreach($post['week'] as $week_no=>$pv): ?>	
													<!-- <div class="tab-data" data-tab="week<?php echo $wcnt; ?>"> -->
													<div class="tab-data" data-tab="week<?php echo $week_no; ?>">
														<?php foreach($pv as $catKey=>$pdata): ?>	
															<h5 class="data-heading"><?php echo $catKey; ?></h5>
															<div class="data-record row">
																	<?php foreach($pdata as $k=>$parr):  ?>	
																		<article class="col-sm-8 col-md-4 col-11">
																			<div class="media-cover-wrap">
																				<div class="blog-item-info">
																					<p class="published">Published on <?php echo $parr['publish_time']; ?></p>
																					<h3 class="blog-title-h2">
                                                                                        <a href="<?php echo $parr['permalink']; ?>"><?php 
                                                 echo mb_strimwidth($parr['title'], 0,55, '...'); 
                                            ?>
                                                                                       </a></h3>
																					<p class="media-description"><?php echo pov_excerpt( $parr['desc'], '120'); ?></p>
																					<hr>
																					<a href="<?php echo $parr['permalink']; ?>" class="view-detail">Read more</a>
																				</div>
																			</div>
																		</article>
																	<?php endforeach; ?>
															</div>
														<?php endforeach; ?>
													</div>
													<?php $wcnt++;  endforeach; ?>
											</section>
										</section>
									<?php $cnt++;endforeach; ?>
							<?php 
							echo '<div class="pagination-custom">';
								echo paginate_links( array(
								'base' => add_query_arg( 'cpage', '%#%' ),
								'format' => '',
								'prev_text' => __('&laquo; Previous'),
								'next_text' => __('Next &raquo;'),
								'total' => ceil($total / $items_per_page),
								'current' => $cpage,
								/* 'type' => 'list' */
								));
								echo '</div>';
							?>
					</div>
				</div>
			</section>
	</div>
<!-- Pop Message HTMl-->
<?php include(TEMPLATEPATH.'/includes/forms/enquiry.php'); ?>
 <!-- Pop Message End -->
<?php get_footer(); ?>