
<?php 
if( ! defined( 'ABSPATH' ) ) exit;
if(!is_admin()) {
session_start();
global $wpdb, $post;

$table_name = $wpdb->prefix . "sync_options";
$entries = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE option_name = %s", 'sync_car_default_time'));
?>

<div class="sync_form_wrapper_set sync_user_option">
	<div class="head_label">
		<h2>Car Rentals</h2>
	</div>
	<div class="select_opt">
		<input type="button" value="Rent a Car" name="rent_car" class="rent_car">
		<input type="button" value="Check Rental" name="check_rental" class="check_rental">  
	</div>
</div>

<div class="sync_form_wrapper car-rental-wrapper" style="display: none;">
	<div class="go_back">
		<span class="back_text"><i class="fa fa-arrow-left"></i>  Back</span>
	</div>
	<div class="sync_container pick-date">
		<div class="sync_options_currency">
		</div>
		<div class="sync_title">
			<h2>Rental Services</h2>
			<?php
			if (!empty($_SESSION['message'])) {
			    echo '<p class="message"> '.esc_html($_SESSION['message']).'</p>';
			    unset($_SESSION['message']);
			}
			?>
		</div>
		<div class="sync_components">
			<form id="search_car_rental" action="" method="post">
				<?php wp_nonce_field('search_car', 'search_car_nonce'); ?>
				<div class="sync_components-container">
					<div class="sync-holder-field">
						<div class="holder holder-calendar">
							<label>Pickup Date <span class="sync_asterisk">*</span></label>
							<input readonly id="datepicker_car_rental_pick" required value="<?php echo isset($_POST['date_pick']) ? esc_attr($_POST['date_pick']) : '' ?>" data-toggle="car-datepicker" name="date_pick">
						</div>
						<div style="display: none;" data-toggle="car-datepicker"></div>
						<div class="holder time_field">
							<label>Pickup Time <span class="sync_asterisk" style="visibility: hidden;">*</span></label>
							<?php
							if ( ! $entries ) {
								?>
								<input id="rental_pick_time" type="text" placeholder="Select Time" value="<?php echo isset($_POST['pick_time']) ? esc_attr($_POST['pick_time']) : '' ?>" name="pick_time">
								<?php
							}else{
								?>
								<input id="rental_pick_time" type="text" placeholder="Select Time" value="<?php echo isset($_POST['pick_time']) ? esc_attr($_POST['pick_time']) : esc_attr(explode("-", $entries[0]->option_value, 2)[0]) ?>" name="pick_time">
								<?php
							}
							?>
							<i class="fas fa-clock fa-1x"></i>
						</div>
						<div class="holder holder-calendar return">
							<label>Return Date <span class="sync_asterisk">*</span></label>
							<input readonly id="datepicker_car_rental_return" required value="<?php echo isset($_POST['date_return']) ? esc_attr($_POST['date_return']) : '' ?>" data-toggle="car-min-datepicker" name="date_return">
						</div>
						<div style="display: none;" data-toggle="car-min-datepicker"></div>
						<div class="holder return_time">
							<label>Return Time<span class="sync_asterisk" style="visibility: hidden;">*</span></label>
							<?php
							if ( ! $entries ) {
								?>
								<input id="rental_return_time" type="text" placeholder="Select Time" class="tooltip-error1" title="(Return time) must be less than of (Pick up time)" value="<?php echo isset($_POST['return_time']) ? esc_html($_POST['return_time']) : '' ?>" name="return_time">
								<?php
							}else{
								?>
								<input id="rental_return_time" type="text" placeholder="Select Time" class="tooltip-error1" title="(Return time) must be less than of (Pick up time)" value="<?php echo isset($_POST['return_time']) ? esc_attr($_POST['return_time']) : esc_attr(explode("-", $entries[0]->option_value, 2)[1])?>" name="return_time">
								<?php
							}
							?>
							<i class="fas fa-clock fa-1x"></i>
						</div>
						<div class="holder">
							<label>Pickup Location<span class="sync_asterisk" style="visibility: hidden;">*</span></label>
							<select class="rental_pick_location js-states form-control" name="pick_location">
							  	<?php
			                        $table_name = $wpdb->prefix . "sync_options";
			                        $entries = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table_name WHERE option_name = %s ORDER BY id DESC", 'sync_car_pickup') );
			                        if ( ! $entries ) {
			                            $wpdb->print_error(); 
			                        }else {
			                            foreach ( $entries as $key => $value) {
			                            	
			                            	if(isset($_POST['pick_location']) && esc_html($_POST['pick_location'])==$value->option_value) {
			                            		?><option selected value="<?php echo esc_attr($value->option_value);?>"><?php echo esc_attr(ucfirst($value->option_value));?></option><?php
			                            	} else {
			                            		?><option value="<?php echo esc_attr($value->option_value);?>"><?php echo esc_attr(ucfirst($value->option_value));?></option><?php
			                            	}
			                            }
			                        }
				                ?>
							</select>
						</div>
						<div class="holder">
							<label>Vehicle Type<span class="sync_asterisk" style="visibility: hidden;">*</span></label>
							<select class="rental_vehicle_type js-states form-control" name="vehicle_type">
								<option value="all">All</option>
								<?php
									$args = array(
										'orderby' => 'post_date',
										'order' => 'DESC',
										'post_type' => 'easync_car_rental',
										'post_status' => 'publish',
										'posts_per_page' => -1,
										'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
									);

									query_posts($args);
									$the_query = new WP_Query( $args );
									$meta_unique =  array();
									while ($the_query->have_posts()) : $the_query->the_post();
										$temp_id = get_the_ID();
										$meta_table = $wpdb->prefix . 'postmeta';
							            
							            $meta_override = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $meta_table WHERE meta_key = %s AND post_id = %d ORDER BY meta_id DESC", 'easync_car', $temp_id), OBJECT );
							            
							            if ( ! $meta_override ) {
							                $wpdb->print_error(); 
							            }else {
							            	foreach ($meta_override as $key => $value) {
							            		$meta = get_post_meta( get_the_ID(), $value->meta_key, true );
							            		array_push($meta_unique, $meta['type']);
							            	}
							            }
							        endwhile;
							        wp_reset_query();
							        $meta_unique = array_unique($meta_unique); 

							        foreach ($meta_unique as $key => $value) {
						        		if(isset($_POST['vehicle_type']) && esc_html($_POST['vehicle_type'])==$value) {
		                            		?><option selected value="<?php echo esc_attr($value);?>"><?php echo esc_html(ucfirst($value));?></option><?php
		                            	}else{
		                            		?><option value="<?php echo esc_attr($value); ?>"><?php echo esc_html(ucfirst($value));?></option><?php
		                            	}
							        }
								?>	
							</select>
						</div>
					</div>
					<div class="holder holder-check-availability">
						<input type="hidden" name="with_or_out_driver" class="with_or_out_driver" value="<?php echo isset($_POST['with_or_out_driver']) ? esc_attr($_POST['with_or_out_driver']) : 'self-driven' ?>">
						<input type="submit" value="Check Availability" name="check_car" class="find-car">
						<div class="holder options">
							<label style="visibility: hidden;">Self-Driven</label>
							<div class="car-driver" style="visibility:hidden;">
								<input type="checkbox" name="self_driven" value="self-driven" class="rent-driver self-driver">
								<?php
									if(isset($_POST['with_or_out_driver'])) {
										if(esc_html($_POST['with_or_out_driver'])=='with driver') {
											?><label class="active">Self-driven</label><?php
										}else{
											?><label class="active">Self-driven</label><?php
										}
									}else{
										?><label class="active">Self-driven</label><?php
									}
								?>
							</div>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>

<?php    
	$converPickTime = date('h:i a', strtotime($_POST['pick_time']));
	if(substr( $converPickTime, 0, 1 ) == 0) {
		$converPickTime  = substr( $converPickTime, 1 );
	}
	$converReturnTime = date('h:i a', strtotime($_POST['return_time']));
	if(substr( $converReturnTime, 0, 1 ) == 0) {
		$converReturnTime  = substr( $converReturnTime, 1 );
	}
	
	if(!empty(sanitize_text_field($_POST['date_pick'])) && !empty(sanitize_text_field($converPickTime)) && !empty(sanitize_text_field($_POST['date_return'])) && !empty(sanitize_text_field($converReturnTime)) && !empty(sanitize_text_field($_POST['pick_location'])) && !empty(sanitize_text_field($_POST['vehicle_type']))) {

		$pick_time   = sanitize_text_field($converPickTime);
		$pick_time_h = explode(":", $pick_time, 2);
		$pick_am_pm  = substr($pick_time, -2);
		$return_time   = sanitize_text_field($converReturnTime);
		$return_time_h = explode(":", $return_time, 2);
		$return_am_pm  = substr($return_time , -2);

		if (isset($_POST['search_car_nonce']) && wp_verify_nonce($_POST['search_car_nonce'], 'search_car')) {
			if( empty($pick_time) ) {
				echo "
					<script type=\"text/javascript\" async>
						$('.tooltip-error1').tooltipster({
							animation: 'fade',
							delay: 200,
							theme: 'tooltipster-punk',
							trigger: 'click'
						});
						$('#rental_return_time').click();					
					</script>";
			} else {
				$date_pick          = sanitize_text_field($_POST['date_pick']); 
				$pick_time          = sanitize_text_field($converPickTime);
				$date_return        = sanitize_text_field($_POST['date_return']);
				$return_time        = sanitize_text_field($converReturnTime);
				$pick_location      = sanitize_text_field($_POST['pick_location']);
				$vehicle_type       = sanitize_text_field($_POST['vehicle_type']);
				$self_driven        = sanitize_text_field($_POST['self_driven']);
				$with_or_out_driver = sanitize_text_field($_POST['with_or_out_driver']);
	
				$date_start = new DateTime($date_pick);
				$date_end   = new DateTime($date_return);
				$get_duration = $date_end->diff($date_start)->format("%a");
				$number_days = ($get_duration == 0) ? 1 : $get_duration;
	
				include('personal-info.php');
				include('payment.php');	
	
			}
		}
	} 
}
?>

<script>
	jQuery(".select_opt .rent_car").click( function () {
		jQuery(".sync_form_wrapper.car-rental-wrapper").show();
		jQuery(".sync_form_wrapper_set.sync_user_option").hide();
	});
	
	jQuery(".select_opt .check_rental").click( function () {
		jQuery(".sync_form_wrapper_set.sync_check_rental").show();
		jQuery(".sync_form_wrapper_set.sync_user_option").hide();
	});

	jQuery(".car-rental-wrapper .go_back").click( function () {
		jQuery('.sync_form_wrapper_set.sync_user_option').show();
		jQuery('.sync_form_wrapper.car-rental-wrapper').hide();
	});
	
	jQuery(".sync_check_rental .go_back").click( function () {
		jQuery('.sync_form_wrapper_set.sync_user_option').show();
		jQuery('.sync_form_wrapper_set.sync_check_rental').hide();
	});

	jQuery("#cancel_success_car .close_modal").click( function () {
		jQuery('body').loading('stop');
		location.reload();
	});

	jQuery("#cancel_success_car .close").click( function () {
		jQuery('body').loading('stop');
		location.reload();
	});

	jQuery(document).on('click', '.find-car', function (e) {
		var pickup_time = jQuery('#rental_pick_time').val();
		var pickup_date = jQuery('#datepicker_car_rental_pick').val();
		var return_date = jQuery('#search_car_rental .holder #datepicker_car_rental_return').val();
		var return_time = jQuery('#search_car_rental .holder #rental_return_time').val();
		var today = new Date();
		var hour = String(today.getHours());
		var minute = String(today.getMinutes());
		var minutes = "";
		var get_diff = "";
		var dd = String(today.getDate()).padStart(2, '0');
		var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
		var yyyy = today.getFullYear();
		current_date = mm + '/' + dd + '/' + yyyy;

		if (minute < '10') {
			minutes = ('0' + minute).slice(-2);
		} else {
			minutes = minute;
		}

		var current_hour = ('0' + hour).slice(-2);
		var current = current_hour + ':' + minutes;

		var convert_pickup = new Date(pickup_date);
		var convert_return = new Date(return_date);
		var convert_current = new Date(current_date);
		
		split_pick = pickup_time.split(':');
		split_return = return_time.split(':');
		split_current = current.split(':');

		pick_to_minutes = (+split_pick[0]) * 60 + (+split_pick[1]);
		return_to_minutes =(+split_return[0]) * 60 + (+split_return[1]);
		current_to_minutes =(+split_current[0]) * 60 + (+split_current[1]);


		get_diff_duration = return_to_minutes - pick_to_minutes;
		get_diff_from_current = pick_to_minutes - current_to_minutes;
	
		current = today.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' });

		
		if (convert_pickup.getTime() == convert_current.getTime()) {
			
			if (current > pickup_time) {
				e.preventDefault();
				jQuery('.error-name.error-time.active').remove();
				jQuery('#search_car_rental .holder.time_field').append('<div class="error error-name error-time active">Time set is already past the current time.</div>'); 
				jQuery('html, body').animate({scrollTop: jQuery('#search_car_rental').offset().top}, 200);
				jQuery('.car-search-result-container').hide();
			} else {
				if (get_diff_from_current < 120) {
					e.preventDefault();
					if (get_diff_from_current == 0) {
						jQuery('.error-name.error-time.active').remove();
						jQuery('#search_car_rental .holder.return_time').append('<div class="error error-name error-time active">Pickup and return time should not be the same.</div>'); 
						jQuery('html, body').animate({scrollTop: jQuery('#search_car_rental').offset().top}, 200);
						jQuery('.car-search-result-container').hide();
					} else {
						jQuery('.error-name.error-time.active').remove();
						jQuery('#search_car_rental .holder.time_field').append('<div class="error error-name error-time active">Rental time should be atleast 2 hours ahead.</div>'); 
						jQuery('html, body').animate({scrollTop: jQuery('#search_car_rental').offset().top}, 200);
						jQuery('.car-search-result-container').hide();
					}

				} else {
					jQuery('.error-name.error-time.active').remove();
				}
			}
		} else {
			jQuery('.error-name.error-time.active').remove();
			if (convert_pickup == convert_return) {
				if (get_diff_duration < 60) {
					e.preventDefault();
					if (get_diff_duration == 0) {
						jQuery('.error-name.error-time.active').remove();
						jQuery('#search_car_rental .holder.return_time').append('<div class="error error-name error-time active">Pickup and return time should not be the same.</div>'); 
						jQuery('html, body').animate({scrollTop: jQuery('#search_car_rental').offset().top}, 200);
						jQuery('.car-search-result-container').hide();
					} else {
						jQuery('.error-name.error-time.active').remove();
						jQuery('#search_car_rental .holder.return_time').append('<div class="error error-name error-time active">Rental duration should be atleast 1 hour.</div>'); 
						jQuery('html, body').animate({scrollTop: jQuery('#search_car_rental').offset().top}, 200);
						jQuery('.car-search-result-container').hide();
					}
				}
			} else {
				jQuery('.error-name.error-time.active').remove();
			}
		}

		if (return_date == "") {
			e.preventDefault();
			jQuery('#search_car_rental .holder.holder-calendar.return').append('<div class="error error-name error-time active">This field is required.</div>');
		}

	});
</script>
