<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package uncode
 */

if(!is_null($post))
{
	$page_obj = get_page($post->ID);
}

$current_page_id = '';

/**
*	Get current page id
**/

if(!is_null($post) && isset($page_obj->ID))
{
    $current_page_id = $page_obj->ID;
}

wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css');

get_header();

$paged = ( get_query_var( 'paged') ) ? absint( get_query_var( 'paged' ) ) : 1; 
$args = array(
	'numberposts'	=> -1,
	'post_type'		=> 'tournaments',
	'paged' => $paged,
	'posts_per_page'=>35
);
$datesort =  "";
$trail = "";
$state = "";
$lake="";
$layouts = array( 'upcoming', 'monthly', 'day' );

$tournaments = "";

if(isset($_GET['bytrails']) && $_GET['bytrails']!=""){
	$trail = $_GET['bytrails'];
}
if(isset($_GET['bystate']) && $_GET['bystate']!=""){
	$state = $_GET['bystate'];
}
if(isset($_GET['bylake']) && $_GET['bylake']!=""){
	$lake = $_GET['bylake'];
}
/*
	if(isset($_GET['datesort']) && $_GET['datesort']!=""){
		$datesort = $_GET['datesort'];
		$year_month = explode('-',$_GET['datesort']);
		$args['date_query'] = array(
			array(
				'year'  => $year_month[0],
				'month' => $year_month[1],
			)
		);

	}
*/
$args['meta_query']	= array(
	'relation'		=> 'and',
	array(
		'key'		=> 'trail',
		'value'		=> $trail,
		'compare'	=> 'LIKE'
	),
	array(
		'key'		=> 'state',
		'value'		=> $state,
		'compare'	=> 'LIKE'
	),
	array(
		'key'		=> 'lake',
		'value'		=> $lake,
		'compare'	=> 'LIKE'
	)
);


$args['meta_key'] = 'from_date';
$args['orderby'] =  'meta_value+0';
$args['order'] = 'ASC';
$args['meta_type'] = 'DATE';

if ( !isset( $_GET['view'] ) ) {
	$_GET['view'] = 'upcoming';
}
		
// if the layout is set to monthly, emulate datesorter
if ( ( isset( $_GET['view'] ) && $_GET['view'] == 'monthly' ) && !( isset($_GET['datesort']) && !empty($_GET['datesort'] ) && strtolower($_GET['datesort']) != 'date' ) ) {
	
	$_GET['datesort'] = date( 'Y-m' );
}
	
if(isset($_GET['datesort']) && !empty($_GET['datesort']) && strtolower($_GET['datesort']) != 'date'){

	$datesort = $_GET['datesort'];
	$year_month = explode('-',$_GET['datesort']);

	$Current_date = date($year_month[0]."-".$year_month[1]."-01");	//Current date...
	$date = strtotime($Current_date);
	$next_month_date = date($year_month[0].'-'.$year_month[1].'-'.date('t',$date));
	
	$start_date = $Current_date;	//Current Month Date...
	$end_date = $next_month_date;	// Next Month
	
	// if the view is set to monthly, get ±7 days
	if ( ( isset( $_GET['view'] ) && $_GET['view'] == 'monthly' ) ) {
		$start_date 		= date( 'Y-m-d', strtotime( $Current_date.' - 6 days' ) );
		$end_date 	= date( 'Y-m-d', strtotime( $next_month_date.' + 6 days' ) );
	}
	
	// get all events of set month
	$args['posts_per_page'] = 9999999999;
	
	$args['meta_query'][]= array(
			'key'		=> 'from_date',
			'value'		=> array($start_date, $end_date),
			'compare'	=> 'BETWEEN',
			'type' => 'DATE' 
		);

} else if(isset($_GET['view']) && $_GET['view'] =="weekly") {
	
	//$start_date = "2017-05-03";
	//$end_date = "2017-06-03";
	
	$Current_date = date("Y-m-d");	//Current date...
	$week_number = get_week_number($Current_date);	//Get week number from the date...
	$year = date("Y",strtotime($Current_date));	// date year...
	$start_date_end_date = getStartAndEndDate($week_number,$year);
	
	
	$start_date = date("Y-m-d",strtotime($start_date_end_date[0]));	//Week Start Date...
	$end_date = date("Y-m-d",strtotime($start_date_end_date[1]));	//Week end date....
	
	$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'value'		=> array($start_date, $end_date),
		'compare'	=> 'BETWEEN',
		 'type' => 'DATE'
		 
	);
	$args['order'] = 'ASC';
} else if(isset($_GET['view']) && $_GET['view'] =="monthly") {
	
		// all set above, nothing to do here
		
} else if(isset($_GET['view']) && $_GET['view'] =="upcoming") {
	$Current_date = date("Y-m-d");	//Current date...
	$args['meta_query'][]= array(
			'key'		=> 'from_date',
			'value'		=> $Current_date,
			'compare'	=> '>=',
			'type' => 'DATE' 
		);
		$args['order'] = 'ASC';
}


$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'compare'	=> 'EXISTS',
	);
$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'value'		=> '',
		'compare'	=> '!=',
	);
	
	
// query
$tournaments = new WP_Query( $args );

/**
*	Get Current page object
**/
if(!is_null($post)) {
	$page_obj = get_page($post->ID);
}

$current_page_id = '';

/**
*	Get current page id
**/

if( !is_null($post) && isset($page_obj->ID) ) {
    $current_page_id = $page_obj->ID;
}

$is_standard_wp_post = FALSE;

if(is_tag()) {
    $is_standard_wp_post = TRUE;
} elseif(is_category()) {
    $is_standard_wp_post = TRUE;
} elseif(is_archive()) {
    $is_standard_wp_post = TRUE;
}


$post_count = 0;


echo '<script type="text/javascript">UNCODE.initHeader();</script>';
?>
	
<div class="page-body">
    <div class="post-wrapper">
      	<div class="post-body">

			<div id="page_content_wrapper">
				<div class="inner">

    	<!-- Begin main content -->
					<div class="inner_wrapper">
						<div class="sidebar_content full_width blog_f">
							<div class="row-container">
								<div class="row row-parent style-light limit-width double-top-padding double-bottom-padding">
									<div id="search-wrapper" style="margin-bottom: 15px;">
		
		<form action="" method="get" class="tournamet_filters">
			 <input type="text" value="Date" class="drop" id="MyDate" name="datesort" value="<?php echo $datesort; ?>" placeholder="Select Date"/>
	         
			 <select class="drop" id="trail" name="bytrails">
				<option value="" >Select Trail</option>
				<?php 
				$args = array( 'posts_per_page' => -1, 'post_type' => 'trails', 'orderby'    => 'post_title',
    'order' => 'asc' );
				$rand_posts = get_posts( $args );
				foreach ( $rand_posts as $post ) : 
					setup_postdata( $post ); 
					
						echo "<option value='$post->ID'";
						if($post->ID==$trail){echo " selected ";}
						echo ">" .$post->post_title . '</option>';
				endforeach; 
				wp_reset_postdata(); 
				
				?>
			 </select>
			 <select class="drop" id="state" name="bystate">
				<option value="" >State</option>
				<?php $values = get_field_object('field_579784592f25e');
				if($values)
				{
					foreach($values['choices'] as $k =>$value)
					{
						echo "<option value='$k'";
						if($k==$state){echo " selected ";}
						echo ">" . $value . '</option>';
						
					}
				}
				?>
			 </select>
			 <select class="drop" id="lake" name="bylake">
			<option value="" >Select Lake</option>
			<?php 
			$args = array( 'posts_per_page' => -1, 'post_type' => 'lakes', 'orderby'    => 'post_title',
    'order' => 'asc' );
			$rand_posts = get_posts( $args );
			foreach ( $rand_posts as $post ) : 
				setup_postdata( $post ); 
				
					echo "<option value='$post->ID'";
					if($post->ID==$lake){echo " selected ";}
					echo ">" .$post->post_title . '</option>';
			endforeach; 
			wp_reset_postdata(); 
			
			?>
			</select>
			<input type="hidden" name="view" value="<?php echo ( ( isset( $_GET['view'] ) && in_array( esc_attr( $_GET['view'] ), $layouts ) ) ? esc_attr( $_GET['view'] ) : '' ); ?>" />
			<input class="button-red" type="submit" value="Search" />
		</form>
									</div>
									
	<div class="view_switch">
		<div class="view_toggler"><i class="fa fa-angle-down" aria-hidden="true"></i>View As</div>
		<ul>
			<li><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?view=upcoming'; ?>" class="<?php echo ( isset( $_GET['view'] ) && $_GET['view'] == 'upcoming' ? 'active' : '' ); ?>" title="Tournaments as list"><i class="fa fa-list"></i> List</a></li>
			<li><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?view=monthly'; ?>" class="<?php echo ( isset( $_GET['view'] ) && $_GET['view'] == 'monthly' ? 'active' : '' ); ?>" title="Tournaments as list"><i class="fa fa-calendar" aria-hidden="true"></i> Month</a></li>
		</ul>
	</div>

	<script type="text/javascript">

				jQuery(function( $ ) {
				
					jQuery( '.view_toggler' ).click( function() {
						jQuery( '.view_switch ul' ).slideToggle( 100 );
					});
					
					$(document).on("click", function(event){
						if(!$(event.target).closest(".view_switch").length){
							jQuery( '.view_switch ul' ).slideUp( 100 );
						}
					});
				
					jQuery('#MyDate').datepicker(
					{
						dateFormat: "yy-mm",
						changeMonth: true,
						changeYear: true,
						showButtonPanel: true,
						placeholder: 'Select Date',
						onClose: function(dateText, inst) {


							function isDonePressed(){
								return (jQuery('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
							}

							if (isDonePressed()){
								var month = jQuery("#ui-datepicker-div .ui-datepicker-month :selected").val();
								var year = jQuery("#ui-datepicker-div .ui-datepicker-year :selected").val();
								jQuery(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
								
								 jQuery('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date
							}
						},
						beforeShow : function(input, inst) {

							inst.dpDiv.addClass('month_year_datepicker')

							if ((datestr = jQuery(this).val()).length > 0) {
								year = datestr.substring(datestr.length-4, datestr.length);
								month = datestr.substring(0, 2);
								jQuery(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
								jQuery(this).datepicker('setDate', new Date(year, month-1, 1));
								jQuery(".ui-datepicker-calendar").hide();
							}
						}
					});
					jQuery('#MyDate').prop( 'placeholder', 'Select Date');
					
			});
		</script>

	
<!-- Begin each blog post -->
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<div class="post_wrapper">
	    <div class="post_content_wrapper">
	    	<div class="post_header mixed">
				<div class="dtable post-listing tournament-listing <?php echo ( ( isset( $_GET['view'] ) && in_array( esc_attr( $_GET['view'] ), $layouts ) ) ? esc_attr( $_GET['view'] ) : '' ); ?>">
<?php 
	
	$layout = 'upcoming';
	if ( isset( $_GET['view'] ) && in_array( esc_attr( $_GET['view'] ), $layouts ) ) {
		$layout = esc_attr( $_GET['view'] );
	}
	
	$checkmonth = '';
	
	$groupbydate = array();
	
	$week = 0;
	
	$new_add_to_show = 0;
	if ($tournaments->have_posts()) {
		while ($tournaments->have_posts()) { 
			$tournaments->the_post();
			$from_date= date( 'Y-m-d', strtotime( get_post_meta(get_the_ID(),'from_date',true) ) );
			$to_date= date( 'Y-m-d', strtotime( get_post_meta(get_the_ID(),'to_date',true) ) );
			$featured = get_field( 'featured', get_the_ID() );
			$is_featured = (  ( isset( $featured[0] ) && $featured[0] == 'yes' ) ? 'is_featured' : '' );
			$tournamentsID = get_the_ID();

			if ( $layout != 'monthly' ) {
				include( locate_template( 'templates/tournaments-'. $layout .'.php' ) );
			} else {
			
				$groupbydate[$from_date][] = array(
				
					'from_date' => $from_date,
					'to_date' => $to_date,
					'ID' => $tournamentsID,
				);
				
			}

			$new_add_to_show = $new_add_to_show + 1; 
		}
		
		
		
		if ( isset( $_GET['view'] ) && $_GET['view'] == 'monthly' ) {
		
			// Create array containing abbreviations of days of week.
			$daysOfWeek = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday');
			
			$month 	= $year_month[1];
			$year 	= $year_month[0];

			// What is the first day of the month in question?
			$firstDayOfMonth = mktime(0,0,0,$month,1,$year);

			// How many days does this month contain?
			$numberDays = date( 't',$firstDayOfMonth );

			// Retrieve some information about the first day of the
			// month in question.
			$dateComponents = getdate( $firstDayOfMonth );

			// What is the name of the month in question?
			$monthName = $dateComponents['month'];

			$dayOfWeek = $dateComponents['wday'];
			
			$period = new DatePeriod(
				 new DateTime($start_date),
				 new DateInterval('P1D'),
				 new DateTime($end_date)
			);
			
			$now = new DateTime( $_GET['datesort'] );
			$previousMonth = $now->modify('first day of previous month');
			$now = new DateTime( $_GET['datesort'] );
			$nextMonth = $now->modify('first day of next month');
			
			$link_query = $_GET;
			unset( $link_query['datesort'] );
			
			?>
			<div class="calendar_header">
				<div class="calendar_nav prev"><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?datesort='.$previousMonth->format('Y-m').'&'.http_build_query( $link_query ); ?>"><i class="fa fa-chevron-left"></i> <?php echo $previousMonth->format('F'); ?></a></div>
				<div><h2><?php echo $monthName.' '. $year; ?></h2></div>
				<div class="calendar_nav next"><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?datesort='.$nextMonth->format('Y-m').'&'.http_build_query( $link_query ); ?>"><?php echo $nextMonth->format('F'); ?> <i class="fa fa-chevron-right"></i></a></div>
			</div>
			<div class="calendar_wrap">
				<div class="week_wrap week_0">
			<?php
				// loop https://www.php.net/manual/en/class.datetime.php
				$found_first_monday = false;
				$daycount = 0;
				$weekcount = 0;
				$fetched_days = iterator_count( $period );
				
				foreach ($period as $key => $dt) {
				
					$day = $dt->format('D');
					
					// continue untill the first Monday is found
					if ( $day != 'Mon' && !$found_first_monday ) {
						continue;
					}
					
					$found_first_monday = true;
					$full_date = $dt->format( 'Y-m-d' );
					$num_of_events = count( $groupbydate[ $full_date ] );
					?>
					
						<div class="day_wrap<?php echo ( ( $dt->format( 'm' ) == $previousMonth->format( 'm' ) || $dt->format( 'm' ) == $nextMonth->format( 'm' ) ) ? ' inactive' : '' ); ?>">
							<div class="day_header"><?php echo $dt->format('l'); ?></div>
							<div class="day_events">
							<?php
								include( locate_template( 'templates/tournaments-'. $layout .'.php' ) );
							?>
							</div>
						</div>
					
					<?php
					
					
					
					$daycount++;
					
					if ( ( $daycount % 7 ) == false ) {
						$next_day = $dt->modify('+1 day');
						if ( $next_day->format('n') == $nextMonth->format('n') ) {
							break;
						}

						$weekcount++;
						echo '</div><div class="week_wrap week_'. $weekcount .'">';
					}
				}
			
			?>
				</div>
			</div>
			<div class="calendar_header bottom">
				<div class="calendar_nav prev"><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?datesort='.$previousMonth->format('Y-m').'&'.http_build_query( $link_query ); ?>"><i class="fa fa-chevron-left"></i> <?php echo $previousMonth->format('F'); ?></a></div>
				<div></div>
				<div class="calendar_nav next"><a href="<?php echo get_post_type_archive_link( 'tournaments' ).'?datesort='.$nextMonth->format('Y-m').'&'.http_build_query( $link_query ); ?>"><?php echo $nextMonth->format('F'); ?> <i class="fa fa-chevron-right"></i></a></div>
			</div>
			<?php		
		}
		
	} 
?>

				</div>
			</div>
	    </div>
	</div>
</div>
<br class="clear"/>
<!-- End each blog post -->



	    	<?php /*?><?php 
				if(!isset($paged) OR empty($paged))
				{
					$paged = 1;
				}
			?>
			
	    	<div class="pagination"><div class="pagination_page"><?php echo esc_html($paged); ?></div><?php posts_nav_link(' ', '<i class="fa fa-angle-double-left"></i>'.esc_html__('Newer Posts', 'grandnews' ), esc_html__('Older Posts', 'grandnews' ).'<i class="fa fa-angle-double-right"></i>'); ?></div><?php */?>
    		
			</div>
    		
    	</div>
    <!-- End main content -->
	</div>
</div>
</div>
</div>
</div>

	

	</div>
</div>
<?php

// end of the loop.

get_footer(); ?>
