<?php 

/* Ajax Booking*/

add_action('wp_ajax_um_booking', 'um_booking');
add_action('wp_ajax_nopriv_um_booking', 'um_booking');

function um_booking(){
	
	$post_ID = $_POST['post_id'];
	?>
	<div class="um_booking_lightbox um_lightbox">
	
		<div class="um_helper">
			<div class="um_middle">
				

				<div class="container">
					<section class="bookingContainer hasDec mainBgColor">
						<div class="bookingScroll">
							<div class="bookingContent">
								<h4 class="title titleUp brandColor"><?php the_field('reservation_title', 'options'); ?></h4>
								<div class="formDescription">
									<?php the_field('reservation_content', 'options'); ?>
								</div>			
							
								<?php if(!get_field('fully_booked',$post_ID)): ?>	
										<?php get_template_part('content','booking'); ?>
								<?php else: ?>
									
									<div class="alert alert-danger"><?php the_field('no_available_room_message','options'); ?></div>
								
								<?php endif; ?>
								
							</div>
						
						</div>
						
						
						<div class="closeBtn">
							<div class="triangle"><i class="brandColor fa fa-plus"></i></div>
						</div>
						
						
					</section>
				</div>
				 
			</div>
		</div>
	</div>		
	<?php
	die();
}

add_action('wp_ajax_um_booking_completed', 'um_booking_completed');
add_action('wp_ajax_nopriv_um_booking_completed', 'um_booking_completed');


function um_booking_completed(){
	
	$hasCheckInOut = get_field('check_in/out','options');
	$calulateTotal = get_field('calculate_price','options');
	$postID = $_POST['post_id'];
	$bookingData = $_POST['booking_data'];
	$adults = '';
	$children = '';
	$nights = '';
	$calcA = false;
	$calcCH = false;
	$price = '';
	
	
	
	if($hasCheckInOut){
		$nights = checkNights($bookingData);	
		if($calulateTotal){ 
			 if(get_field('advanced_calculation','options')){										
				 if (in_array('adults', get_field('advanced_calculation','options')) ){
						$uniqueAdultsID = get_field('adult_filed_id','options');
						$adults = findChildrenAdults($bookingData ,$uniqueAdultsID);
						$calcA = true;
			 	}
			 	if(in_array('children', get_field('advanced_calculation','options')) ){
					 	$uniqueChildrenID = get_field('children_field_id','options');
						$children = findChildrenAdults($bookingData ,$uniqueChildrenID);
						$calcCH = true;
				}
			}
			if($calcA && $calcCH){
				
				$adultPrice = get_field('price', $postID);
				$childrenPrice = get_field('children_price', $postID);
				
				$total = $nights * $adultPrice * $adults;
				$cTotal = $nights * $childrenPrice * $children;
				$price = $total + $cTotal;
			}
			elseif($calcA && (!$calcCH)){
				$adultPrice = get_field('price', $postID);
				$price = $nights * $adultPrice * $adults;
			}
			elseif((!$calcA) && $calcCH){
				$childrenPrice = get_field('children_price', $postID);
				$price = $nights * $childrenPrice * $children;
			}
			else{	
				$defaultPrice = get_field('price', $postID);
				$price = $nights * $defaultPrice;
			}
		}
	}
	
	sendEmail($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price );
	insertIntoDB($bookingData, $price, $postID);
	receiveEmail($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price );
	
?>
	
	

	
			
			<div class="printLogo visible-print">
				<?php if(get_field('logo_type','options') == 'text' ): ?>
          			 <h1 class="logo"><a href="<?php echo site_url(); ?>"><?php the_field('logo_text','options') ?></a></h1>
                    <?php elseif(get_field('logo_type','options') == 'image'): ?>
                    	<?php $logoImg = wp_get_attachment_image_src( get_field('logo_image' ,'option'), 'full'); ?>
						<?php $retinaLogo = 'um_noRetina';  ?>
						<?php if(get_field('retina_logo','options')){
			        				$logoW = $logoImg[1] / 2; 
			        				$logoH = $logoImg[2] / 2;
									$retinaLogo = 'um_retina'; 
			        			}
			        			else{
									$logoW = $logoImg[1]; 
			        				$logoH = $logoImg[2];
								}	
							?>
								<a href="<?php echo site_url(); ?>"><img width="<?php echo $logoW; ?>" height="<?php echo $logoH; ?>" src="<?php echo $logoImg[0]; ?>" class="logo imgLogo <?php echo $retinaLogo; ?>"></a>			        	
            		<?php else: ?>
						<h1 class="logo"><a href="<?php echo site_url(); ?>"><?php bloginfo('name');?></a> </h1>
					<?php endif; ?>
			</div>
			
					<section class="bookingContainer hasDec mainBgColor">
						<div class="billScroll">
							<div class="bookingContent">
								<?php if(get_field('completed_type','options') == 'bill'): ?>
									<table class="um_table">
										<thead>
											<tr>
												<th colspan="2" class="brandBgColor"><h5 class="title titleUp"><?php the_field('bill_title','options'); ?></h5></th>
											</tr>
										</thead>
										<tbody>
											<tr>
												<td><?php _e('Room','um_lang'); ?></td>
												<td><?php echo get_the_title($postID); ?></td>
											</tr>					
											<?php foreach ($bookingData as $singleData):?>
												<?php foreach($singleData as $data): ?>
													<?php if($data['type'] != 'check'): ?>
														<tr>
															<td><?php echo $data['label']; ?></td>
															<td><?php echo $data['value']; ?></td>
														</tr>
													<?php else: ?>
														<tr>
															<td><?php echo $data['label']; ?></td>
															<?php if($data['value'][0] != 'null'): ?>
																<td>
																	<?php foreach($data['value'] as $value): ?>
																		<?php echo $value.' '; ?>
																	<?php endforeach; ?>
																</td>
															<?php else: ?>
															 	<td></td>
															<?php endif; ?>
														</tr>
													<?php endif; ?>
												<?php endforeach; ?>
											<?php endforeach; ?>
										</tbody>
										<?php if($hasCheckInOut): ?>	
											<?php if($calulateTotal): ?>
												<tfoot>
													<tr class="bookTotal">
														
														
														<td><label class="title">Total:</label></td>
														<td class="bookResult">
															
															<?php if(get_field('advanced_calculation','options')): ?>
																<?php if (in_array('adults', get_field('advanced_calculation','options')) ):?>
																	<span class="period"> <span><?php echo $adults; ?></span> <?php _e('Adults','um_lang'); ?></span>
																<?php endif; ?>
																<?php if(in_array('children', get_field('advanced_calculation','options')) ): ?>	
																	<span class="period"> <span ><?php echo $children; ?></span> <?php _e('Children','um_lang'); ?></span>
																<?php endif; ?>
															<?php endif; ?>
															<span class="period"><?php echo $nights.' '; ?> <?php _e('nights','um_lang'); ?></span>
															<strong class="price"><?php echo $price; the_field('default_currency','options'); ?></strong>
														</td>
													</tr>
												</tfoot>
											<?php endif; ?>
										<?php endif; ?>
									 </table>
									 
									 <div class="billButtons">
									 	<button onclick="window.print();" class="btn default titleUp"><i class="fa fa-print"></i><?php the_field('print_bill_text','options'); ?></button>
										<button onclick="location.href='<?php echo site_url(); ?>'"  class="btn grey titleUp"><i class="fa fa-caret-left"></i><?php the_field('back_to_home_page_text','options'); ?></button>
									 </div>
							 	
							 	<?php else: ?>
							 		
							 			<div class="alert alert-success"><?php the_field('thank_you_note','options'); ?></div>
							 	
							 	<?php endif; ?>
							 	
							 	<div class="closeBtn">
									<div class="triangle"><i class="brandColor fa fa-plus"></i></div>
								</div>
							</div>
						</div>
					</section>

	
<?php
	
	die();
}
/* Ajax Booking END*/



function insertIntoDB($bookingData, $price, $postID){
	
	if($price != ''){
		array_push ($bookingData, array( array("type" => "price", "currency" => get_field('default_currency','options'), "value" => $price)));
	}
		
		
		global $wpdb;
        $table_name = 'um_bookingTable';  
        $jsonEncoded = json_encode($bookingData);
        $data = array(
                        'booking_post_id' => $postID,
                        'fields' => $jsonEncoded
                    ); 
        $wpdb->insert($table_name, $data);
		
		
}


function checkNights($bookingData){
		$arival = '';
		$departure = '';
		foreach ($bookingData as $singleData){
			foreach($singleData as $data){
				if($data['type'] == "um_arival"){
					$arival = $data['value'];
				}
				if($data['type'] == "um_departure"){
					$departure = $data['value'];	
				}
			}
		}
	
		$date1 = date_create($arival);
		$date2 = date_create($departure);
		$result = date_diff($date2, $date1);
		
	return $result->days;
}


function findChildrenAdults($bookingData, $uniqueID){
	$result = '';
		foreach ($bookingData as $singleData){
			foreach($singleData as $data){
				if($data['type'] == 'number'){	
					if($data['uniqueID'] == $uniqueID){
							
						$result = $data['value'];
					}				
				}
			}
		}
	return $result;	
}

function sendEmail($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price ){
	
	if(get_field('send_email','options')){
		$email = '';
		$uniqueID = get_field('email_id','options');
		
		foreach ($bookingData as $singleData){
			foreach($singleData as $data){
				if($data['type'] == 'email'){	
					if($data['uniqueID'] == $uniqueID){
						$email = $data['value'];
					}				
				}
			}
		}
		
		if($email){
			if(get_field('email_type','options') == "bill"){
				
					$subject = "[".get_bloginfo('name')."]";
					$message = emailBill($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price);
					
					
					
					$headers = "From: " . get_bloginfo('name') . "\r\n";
		
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
					
					wp_mail($email,$subject,$message,$headers);
				
			}
			else{
				$subject = "[".get_bloginfo('name')."]";
			
				$message = get_field('custom_email');
				wp_mail($email,$subject,$message);
			}
		}
		
	}
}

function receiveEmail($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price ){
	
	
	if(get_field('accept_emails','options')){
		
		$email = get_option('admin_email');
		if(get_field('receivers_email','options')){
			$email = get_field('receivers_email','options');
		}
		
		$subject = "[".get_bloginfo('name')."]";
		
		$message = emailBill($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price );
		
		$headers = "From: " . get_bloginfo('name') . "\r\n";
		
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
		
		wp_mail($email,$subject,$message,$headers);
					
		
	}
	
}



function emailBill($postID, $bookingData, $hasCheckInOut, $calulateTotal, $adults, $children, $nights, $price ){
		
	
	$message = "
		<html>
			<body>
			
			<table style='border: solid 1px #e4e4e4; width:600px; border-collapse: collapse; font-family: Helvetica,Arial,sans-serif; font-size:13px; color:#747474;'>
			<thead>
				<tr>
					<th colspan='2' style='padding: 10px 20px; color: #fff; background: #e2b55d;'><h5 style='text-transform: uppercase; font-weight: bold; font-size: 16px; font-size: 16px; line-height: 40px; margin: 0;'>".get_field('bill_title','options')."</h5></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>".__('Room','um_lang')."</td>
					<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>". get_the_title($postID)."</td>
				</tr>";
									
				 foreach ($bookingData as $singleData){
					 foreach($singleData as $data){ 
						if($data['type'] != 'check'){ 
							
							$message .= "					
											<tr>
												<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>".$data['label'] ."</td>
												<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>".$data['value']."</td>
											</tr>";
						}
						else{
							
							$message .= "
								<tr>
									<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>". $data['label']."</td>";
									
									if($data['value'][0] != 'null'){
									$message .= "<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'>";
											  foreach($data['value'] as $value){ 
												$message .=  $value." "; 
											  }
										$message .= "</td>";
									}
									else{ 
										$message .= "<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px;'></td>";
									}
									
							$message .= "		 
								</tr>";			
						 }
					}
				}
			$message .= "</tbody>";
			
			 if($hasCheckInOut){ 
				 if($calulateTotal){ 
					
				$message .= "<tfoot>
						<tr style='background: #cbcbcb;'>
						
							<td style='border:solid 1px #e4e4e4; width:50%; padding: 13px 20px; border-right-color:#cbcbcb;'><label class='title'><b>Total:</b></label></td>
							<td style='padding:13px 20px;'>
						";
								
								 if(get_field('advanced_calculation','options')){
									 if (in_array('adults', get_field('advanced_calculation','options')) ){
									 
										$message .=	"<span class='period'> <span>".$adults."</span>".__('Adults','um_lang')."</span>";
									 }
									 if(in_array('children', get_field('advanced_calculation','options')) ){	
											$message .=	"<span class='period'> <span >".$children."</span>".__('Children','um_lang')."</span>";
										}
								}
								 
								$message .=	" <span class='period'>".$nights." ".__('nights','um_lang')."</span>";
								$message .=	"<strong class='price'>".$price.get_field('default_currency','options')."</strong>";
					$message .=	"			
							</td>
						</tr>
					</tfoot>";
					
					}
				}
		$message .= "</table>
			</body>
		</html>
		";
	
	return $message;
	
}

?>