<?php
$message = (isset($_SESSION['message'])) ? $_SESSION['message'] :"";
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : "insert";

$where 	= " WHERE 1=1 ";

$type_of_appointment = 1;

$query_string = "";

$button_value 	= "Add";
$table_name		= "appointment";

$next_page_condition 	= "";

if($_REQUEST['hide_top']){
	$next_page_condition.="&hide_top=1";
}
if($_REQUEST['hide_left']){
	$next_page_condition.="&hide_left=1";
}
if($_REQUEST['job_id']){
	$job_id = $_REQUEST['job_id'];
	$where 	.= " AND job_id = $job_id ";
	$next_page_condition.="&job_id=".$job_id;
}

$quotation_area_hide = "none";

/*if(isset($_REQUEST['source'])){
	$source = $_REQUEST['source'];
	$next_page_condition.="&source=$source";
}*/

if(isset($_REQUEST['prospect'])){
	$prospect = $_REQUEST['prospect'];
	//$next_page_condition.="&source=$source";
}


$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
	//$next_page_condition.="&start=$start";
}
$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	
	$quotation_area_hide = "block";
	
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	$action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit Appointment";	
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $id= $row_edit['id'];
    $job_id= $row_edit['job_id'];
    $admin_id= explode(",",$row_edit['admin_id']);
	$appointment_text= $row_edit['appointment_text'];
	$appointment_date= $row_edit['appointment_date'];
	$appointment_time= $row_edit['appointment_time'];
	$appointment_time_to= $row_edit['appointment_time_to'];
	$is_full_day= $row_edit['is_full_day'];
	$appointment_location= $row_edit['appointment_location'];
	$attended= $row_edit['attended'];
	$client_not_in= $row_edit['client_not_in'];
	$addess= $row_edit['addess'];
	$notes= $row_edit['notes'];
	$common_appointment_id= $row_edit['common_appointment_id'];
	
	$quotation_accepted= utility::getTableFieldById('job','quotation_accepted','id',$job_id);
	$quotation_declined= utility::getTableFieldById('job','quotation_declined','id',$job_id);
	
	$to_quote		   = utility::getTableFieldById('job','to_quote','id',$job_id);
	$quoted			   = utility::getTableFieldById('job','quoted','id',$job_id);
	$quotation_accepted= utility::getTableFieldById('job','quotation_accepted','id',$job_id);
	$accepted_date_given= utility::getTableFieldById('job','accepted_date_given','id',$job_id);
	$quotation_declined= utility::getTableFieldById('job','quotation_declined','id',$job_id);
	
}
################################################# END EDIT ################################################# 


################################################## START update ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string","admin_id"));
	$id= $_REQUEST['id'];
    $job_id= $_REQUEST['job_id'];
    $admin_id= implode(",",$_REQUEST['admin_id']);
    $appointment_text= $_REQUEST['appointment_text'];
	$old_appointment_date = utility::getTableFieldById($table_name,'appointment_date','id',$id);
	$old_appointment_date = utility::getFormatedDateReturn($old_appointment_date);
	$appointment_date	 = utility::setFormatedDate($_REQUEST['appointment_date']);
	$old_appointment_time = utility::getTableFieldById($table_name,'appointment_time','id',$id);
	$appointment_time= $_REQUEST['appointment_time'];
	$appointment_time_to= $_REQUEST['appointment_time_to'];
	$is_full_day= (isset($_REQUEST['is_full_day'])) ? 1 : 0;
	$attended= (isset($_REQUEST['attended'])) ? 1 : 0;
	$client_not_in= (isset($_REQUEST['client_not_in'])) ? 1 : 0;
	$addess= $_REQUEST['addess'];
	$notes= $_REQUEST['appointment_text'];
	$appointment_location= $_REQUEST['appointment_location'];
	
	$apply_to_coming_event = (isset($_REQUEST['apply_to_coming_event'])) ? 1 : 0;
	
	if($apply_to_coming_event==1){
		$common_appointment_id = utility::getTableFieldById("appointment","common_appointment_id","id",$id);
		$sel_app = " SELECT * FROM appointment WHERE id!='".$id."' AND common_appointment_id='".$common_appointment_id."' AND appointment_date>='".date('Y-m-d H:i:s')."'";		
		$sql_app =mysqli_query($sel_app);
		if(mysqli_num_rows($sql_app)){
			while($row_app = mysqli_fetch_array($sql_app)){
				mysqli_query("UPDATE appointment SET job_id = '$job_id',admin_id = '$admin_id',appointment_text = '$appointment_text',appointment_time = '$appointment_time',appointment_time_to = '$appointment_time_to',is_full_day = '$is_full_day',attended = '$attended',client_not_in = '$client_not_in',addess = '$addess',notes = '$notes',appointment_location = '$appointment_location',updated_by = '".$_SESSION['user_id']."' WHERE id = '".$row_app['id']."' ");
				
			}
		}
	}

    $sql= "UPDATE appointment SET job_id = '$job_id',admin_id = '$admin_id',appointment_text = '$appointment_text',appointment_date = '$appointment_date',appointment_time = '$appointment_time',appointment_time_to = '$appointment_time_to',is_full_day = '$is_full_day',attended = '$attended',client_not_in = '$client_not_in',addess = '$addess',notes = '$notes',appointment_location = '$appointment_location',updated_by = '".$_SESSION['user_id']."' WHERE id = $id";
    mysqli_query($conn,$sql);
	if(isset($_SESSION['uploadfileArray'])){
		foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
			$document_date = date("Y-m-d");
			$created_on = date("Y-m-d");
			$document_text = "Appointment document";
			$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
			mysqli_query($conn,$sql);
		}
		unset($_SESSION['uploadfileArray']);
	}
	/********************* Adding appointment notes *****************************************/
		if(isset($appointment_text) && $appointment_text !=""){
			if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
				$admin_id= $_SESSION['job_user_id'];
				$job_user_id= $_SESSION['job_user_id'];
			}else{
				$admin_id= $_SESSION['user_id'];
			}
			$note_text = $appointment_text;
			$note_date	 = date("Y-m-d");
			$created_on = date("Y-m-d");
			
			mysqli_query($conn,"DELETE FROM notes WHERE appointment_id = '$id' ");
			$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
			mysqli_query($sql_notes);
		}
		/********************* End Adding appointment notes *****************************************/
	
	if($old_appointment_date != $_REQUEST['appointment_date'] || $old_appointment_time != $appointment_time.":00"){
		/********************************* Appointment Mail ****************************************************/
		$mail_format_subject = utility::getTableFieldById("mail_format","mail_format_subject","mail_format_name","activity_appointment");
		//$activity_type_text = Keycode::getkeycodeById($activity_type);
		$activity_type_text = utility::getTableFieldById('job','company_name','id',$job_id);
		$find_array = array("[customer_name]");
		$replace_array = array($activity_type_text,$customer_name);
		$mail_format_subject = str_replace($find_array,$replace_array,$mail_format_subject);
		
		$to_name = "Shoeb Ahmad";//utility::getTableFieldById('job','contact_name','id',$job_id);
		$to_address = "shoebahmad999@gmail.com";//utility::getTableFieldById('job','email_1','id',$job_id);
		$startTime = utility::setFormatedDateAndTimeForCalendar($_REQUEST['appointment_date'],$appointment_time);
		
		$activity_time_array = explode(":",$appointment_time);
		$activity_time_array[0] = $activity_time_array[0]+1;
		$end_activity_time = implode(":",$activity_time_array);
		$endTime = utility::setFormatedDateAndTimeForCalendar($_REQUEST['appointment_date'],$end_activity_time);
		
		$appointment_location = $_REQUEST['appointment_location'];
		
		$site_email = $config->siteEmail;
		
		$first_name1 = utility::getTableFieldById('job','first_name1','id',$job_id);
		$last_name1 = utility::getTableFieldById('job','last_name1','id',$job_id);
		$customer_array = array();
		$name = ucfirst($first_name1)." ".ucfirst($last_name1);
		$customer_array["name"] = $name;
		$address = $krscrm->getCustomerAddressById($job_id);
		$customer_array["address"] = $address;
		
		$telephone = "";
		$telephone_1 = utility::getTableFieldById('job','phone_no1','id',$job_id);
		$telephone_1d = utility::app_crypt($telephone_1,'d');
		if($telephone_1 != ""){
			$telephone .= $telephone_1d;
		}
		$telephone_2 = utility::getTableFieldById('job','phone_no2','id',$job_id);
		$telephone_2d = utility::app_crypt($telephone_2,'d');
		if($telephone_2 != ""){
			$telephone .= ", ".$telephone_2d;
		}
		$customer_array["telephone"] = $telephone;
		//$customer_array["telephone"] = utility::app_crypt($telephone,'d');
		
		foreach($_REQUEST['admin_id'] as $consultant_id){
			$consultant_email = utility::getTableFieldById('admin','email_admin','id',$consultant_id);
			$from_address = "info@community.co.uk";
						
			//$functions->sendIcalEvent($from_name = "Kingsleyroofers", $from_address , $customer_array, $consultant_email, $startTime, $endTime, $mail_format_subject, $notes, $appointment_location,$domain = "www.web-alliance.co.uk");
			//$functions->sendIcalEvent($from_name = "ESI Control", $from_address , $customer_array, $to_address, $startTime, $endTime, $mail_format_subject, $notes, $appointment_location,$domain = "www.web-alliance.co.uk");
		}
		
		//$consultant_email = utility::getTableFieldById('admin','email_admin','id',$consultant_id);
		//$consultant_email = "adityaprakash89@gmail.com, jaydenlewistaylor@gmail.com";
		//$from_address = $consultant_email;
		/* $from_address = "info@afcl.web-alliance.co.uk";
					
		$functions->sendIcalEvent($from_name = "Kingsleyroofers", $from_address , $customer_array, $consultant_email, $startTime, $endTime, $mail_format_subject, $notes, $appointment_location,$domain = "www.web-alliance.co.uk"); */
		/********************************* End Appointment Mail ************************************************/
	}
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace(array("page=add","action=edit"), array("page=list",""), $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['message']	= ucfirst("Appointment updated sucessfully");
	$redirect = "index?page=view$query_string";
	header("Location: $redirect");
	exit();
	
}
################################################# END update ################################################# 
//$custome_limit = 2;
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Appointment Management ";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################

	
    
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	    
	utility::addslashesOnAllInput(array("query_string","admin_id","frequency_checklist","frequency_checklist1","week_of_month","day_of_month"));
    $job_id = $_REQUEST['job_id'];	
    $admin_id= implode(",",$_REQUEST['admin_id']);
	$app_admin_id = implode(",",$_REQUEST['admin_id']);	
	$appointment_text = $_REQUEST['appointment_text'];
	//$source	 = $_REQUEST['source'];
	$appointment_date	 = utility::setFormatedDate($_REQUEST['appointment_date']);
	$appointment_date_to = utility::setFormatedDate($_REQUEST['appointment_date_to']);
	$appointment_time = $_REQUEST['appointment_time'];
	$appointment_time_to = $_REQUEST['appointment_time_to'];
	$is_full_day = (isset($_REQUEST['is_full_day'])) ? 1 : 0;
	$attended = (isset($_REQUEST['attended'])) ? 1 : 0;
	$client_not_in = (isset($_REQUEST['client_not_in'])) ? 1 : 0;
	$addess = $_REQUEST['addess'];
	$notes = $_REQUEST['appointment_text'];
	$appointment_location = $_REQUEST['appointment_location'];
	$created_on = date("Y-m-d");
	$dayOptions 				= $_REQUEST['dayOptions'];
	$day_of_month 				= $_REQUEST['day_of_month'];
	$week_of_month 				= $_REQUEST['week_of_month'];
	$type_of_appointment		= $_REQUEST['type_of_appointment'];
	$frequency_checklist_array	= $_REQUEST['frequency_checklist'];
	$frequency_checklist_array1	= $_REQUEST['frequency_checklist1'];
	if(count($frequency_checklist_array)){
		$frequency_of_week = "";
		foreach($frequency_checklist_array as $key => $frequency_checklist ){
			$frequency_of_week .= $frequency_checklist.",";
		}
		$frequency_of_week = substr($frequency_of_week,0,-1);
	}
	$no_of_day = 0;
	
	if(strtotime($appointment_date_to) >= strtotime($appointment_date)){
		$_SESSION['message']	= ucfirst("Appointment added sucessfully");
		$no_of_days = ((strtotime($appointment_date_to) - strtotime($appointment_date))/(24*60*60)) + 1;
	}else{
		$_SESSION['message']	= "To date can't be less than from date.";
	}
		
    if($type_of_appointment==1){
		
		$appointment_date	 = utility::setFormatedDate($_REQUEST['appointment_date']);
		
		$for_first_common_appoint = true;		
		while(strtotime($appointment_date)<=strtotime($appointment_date_to)){
			$sql= "INSERT INTO $table_name (common_appointment_id,job_id,admin_id,appointment_text,appointment_date,appointment_time,appointment_time_to,is_full_day,attended,client_not_in,addess,notes,appointment_location,updated_by,created_on) VALUES('$common_appointment_id','$job_id','$app_admin_id','$appointment_text','$appointment_date','$appointment_time','$appointment_time_to','$is_full_day','$attended','$client_not_in','$addess','$notes','$appointment_location','".$_SESSION['user_id']."','$created_on')";
			mysqli_query($conn,$sql);
			$appointment_id = mysqli_insert_id();
			if($for_first_common_appoint===true){
				$common_appointment_id = $appointment_id;
				$for_first_common_appoint =false;
				mysqli_query("UPDATE $table_name SET common_appointment_id='".$common_appointment_id."' WHERE id='".$appointment_id."' ");
			}
			
			if(isset($_SESSION['uploadfileArray'])){
				foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
					$document_date = date("Y-m-d");
					$document_text = "Appointment document";
					$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$appointment_id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
					mysqli_query($conn,$sql);
				}
				unset($_SESSION['uploadfileArray']);
			}
			/********************* Adding appointment notes *****************************************/
			if(isset($appointment_text) && $appointment_text !=""){
				if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
					$admin_id= $_SESSION['job_user_id'];
					$job_user_id= $_SESSION['job_user_id'];
				}else{
					$admin_id= $_SESSION['user_id'];
				}
				$note_text = $appointment_text;
				$note_date	 = date("Y-m-d");
				$created_on = date("Y-m-d");
			
				$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$appointment_id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
				mysqli_query($sql_notes);
			}
			/********************* End Adding appointment notes *****************************************/
			
			
			/********************************* Appointment Mail ****************************************************/
			$mail_format_subject = utility::getTableFieldById("mail_format","mail_format_subject","mail_format_name","activity_appointment");
			//$activity_type_text = Keycode::getkeycodeById($activity_type);
			$job_type = utility::getTableFieldById('job','client_industry','id',$job_id);
			$first_name1 = utility::getTableFieldById('job','first_name1','id',$job_id);
			$last_name1 = utility::getTableFieldById('job','last_name1','id',$job_id);
			if($job_type==1){
				$activity_type_text = ucwords($first_name1.' '.$last_name1);
			}else{
				$activity_type_text = utility::getTableFieldById('job','company_name','id',$job_id);
			}
			//$activity_type_text = utility::getTableFieldById('job','company_name','id',$job_id);
			$find_array = array("[customer_name]");
			$replace_array = array($activity_type_text,$customer_name);
			$mail_format_subject = str_replace($find_array,$replace_array,$mail_format_subject);
			
			$to_name = "Shoeb Ahmad";//utility::getTableFieldById('job','contact_name','id',$job_id);
			$to_address = "shoebahmad999@gmail.com";//utility::getTableFieldById('job','email_1','id',$job_id);
			$startTime = utility::setFormatedDateAndTimeForCalendar($_REQUEST['appointment_date'],$appointment_time);
			
	/* 		$activity_time_array = explode(":",$appointment_time);
			$activity_time_array[0] = $activity_time_array[0]+1;
			$end_activity_time = implode(":",$activity_time_array);
			$endTime = utility::setFormatedDateAndTimeForCalendar($_REQUEST['appointment_date'],$end_activity_time); */
			$endTime = utility::setFormatedDateAndTimeForCalendar($_REQUEST['appointment_date'],$appointment_time_to); 
			
			$appointment_location = $_REQUEST['appointment_location'];
			
			$site_email = $config->siteEmail;
			
			$first_name1 = utility::getTableFieldById('job','first_name1','id',$job_id);
			$last_name1 = utility::getTableFieldById('job','last_name1','id',$job_id);
			$customer_array = array();
			$name = ucfirst($first_name1)." ".ucfirst($last_name1);
			$customer_array["name"] = $name;
			$address = $krscrm->getCustomerAddressById($job_id);
			$customer_array["address"] = $address;
			
			$second_address = $krscrm->getCustomerSiteAddressByJobId($job_id);			
			$customer_array["second_address"] = $second_address;
			
			$telephone = "";
			$telephone_1 = utility::getTableFieldById('job','phone_no1','id',$job_id);
			$telephone_1d = utility::app_crypt($telephone_1,'d');
			if($telephone_1 != ""){
				$telephone .= $telephone_1d;
			}
			$telephone_2 = utility::getTableFieldById('job','phone_no2','id',$job_id);
			$telephone_2d = utility::app_crypt($telephone_2,'d');
			if($telephone_2 != ""){
				$telephone .= ", ".$telephone_2d;
			}
			$customer_array["telephone"] = $telephone;
			//$customer_array["telephone"] = utility::app_crypt($telephone,'d');
			
			foreach($_REQUEST['admin_id'] as $consultant_id){
				$consultant_email = utility::getTableFieldById('admin','email_admin','id',$consultant_id);
				$from_address = "info@community.co.uk";
							
				///$functions->sendIcalEvent($from_name = "Kingsleyroofers", $from_address , $customer_array, $consultant_email, $startTime, $endTime, $mail_format_subject, $notes, $appointment_location,$domain = "www.web-alliance.co.uk",$job_type);
				//$functions->sendIcalEvent($from_name = "ESI Control", $from_address , $customer_array, $to_address, $startTime, $endTime, $mail_format_subject, $notes, $appointment_location,$domain = "www.web-alliance.co.uk");
			}
			
			$appointment_date = date("Y-m-d",strtotime("+1 day",strtotime($appointment_date)));
		}
	}else if($type_of_appointment==3){
			
		// 0 (for Sunday) through 6 (for Saturday)
		$for_first_common_appoint = true;
		
		while(strtotime($appointment_date)<=strtotime($appointment_date_to)){
			
			$week_number = date('N',strtotime($appointment_date)); // 1 through 12
			
			if (in_array($week_number, $frequency_checklist_array)){
				
				//echo $appointment_date."<br>";
				echo $sql= "INSERT INTO $table_name (job_id,admin_id,appointment_text,appointment_date,appointment_time,appointment_time_to,is_full_day,attended,client_not_in,addess,notes,appointment_location,common_appointment_id,updated_by,created_on) VALUES('$job_id','$app_admin_id','$appointment_text','$appointment_date','$appointment_time','$appointment_time_to','$is_full_day','$attended','$client_not_in','$addess','$notes','$appointment_location','$common_appointment_id','".$_SESSION['user_id']."','$created_on')";
				mysqli_query($conn,$sql);
				$appointment_id = mysqli_insert_id();
				
				if($for_first_common_appoint===true){
					$common_appointment_id = $appointment_id;
					$for_first_common_appoint =false;
					mysqli_query("UPDATE $table_name SET common_appointment_id='".$common_appointment_id."' WHERE id='".$appointment_id."' ");
				}
				
				if(isset($_SESSION['uploadfileArray'])){
					foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
						$document_date = date("Y-m-d");
						$document_text = "Appointment document";
						$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$appointment_id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
						mysqli_query($conn,$sql);
					}
					
				}
				/********************* Adding appointment notes *****************************************/
				if(isset($appointment_text) && $appointment_text !=""){
					if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
						$admin_id= $_SESSION['job_user_id'];
						$job_user_id= $_SESSION['job_user_id'];
					}else{
						$admin_id= $_SESSION['user_id'];
					}
					$note_text = $appointment_text;
					$note_date	 = date("Y-m-d");
					$created_on = date("Y-m-d");
				
					$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$appointment_id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
					mysqli_query($sql_notes);
				}
				/********************* End Adding appointment notes *****************************************/
			}			
			$appointment_date = date("Y-m-d",strtotime("+1 day",strtotime($appointment_date)));
				
		}
		
		unset($_SESSION['uploadfileArray']);
	}else if($type_of_appointment==2){
		
		
		if($dayOptions=='day'){
			
			$for_first_common_appoint = true;
			
			while(strtotime($appointment_date)<=strtotime($appointment_date_to)){
				$get_day = date('j',strtotime($appointment_date));
				if (in_array($get_day, $day_of_month))
				{
					$sql= "INSERT INTO $table_name (job_id,admin_id,appointment_text,appointment_date,appointment_time,appointment_time_to,is_full_day,attended,client_not_in,addess,notes,appointment_location,common_appointment_id,updated_by,created_on) VALUES('$job_id','$app_admin_id','$appointment_text','$appointment_date','$appointment_time','$appointment_time_to','$is_full_day','$attended','$client_not_in','$addess','$notes','$appointment_location','$common_appointment_id','".$_SESSION['user_id']."','$created_on')";
					mysqli_query($conn,$sql);
					$appointment_id = mysqli_insert_id();
					if($for_first_common_appoint===true){
						$common_appointment_id = $appointment_id;
						$for_first_common_appoint =false;
						mysqli_query("UPDATE $table_name SET common_appointment_id='".$common_appointment_id."' WHERE id='".$appointment_id."' ");
					}
					if(isset($_SESSION['uploadfileArray'])){
						foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
							$document_date = date("Y-m-d");
							$document_text = "Appointment document";
							$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$appointment_id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
							mysqli_query($conn,$sql);
						}
						
					}
					/********************* Adding appointment notes *****************************************/
					if(isset($appointment_text) && $appointment_text !=""){
						if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
							$admin_id= $_SESSION['job_user_id'];
							$job_user_id= $_SESSION['job_user_id'];
						}else{
							$admin_id= $_SESSION['user_id'];
						}
						$note_text = $appointment_text;
						$note_date	 = date("Y-m-d");
						$created_on = date("Y-m-d");
					
						$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$appointment_id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
						mysqli_query($sql_notes);
					}
				
				}
				
				$appointment_date = date("Y-m-d",strtotime("+1 day",strtotime($appointment_date)));		
			}
		
		}else{
		
		$for_first_common_appoint = true;
		
		while(strtotime($appointment_date)<=strtotime($appointment_date_to)){			
			
			$appointment_date_array = explode("-",$appointment_date);
			$appointment_month_first_date = $appointment_date_array[0].'-'.$appointment_date_array['1'].'-01';
			
			$week_number = date('N',strtotime($appointment_date)); // 1 (for Monday) through 7 (for Sunday)			
			
			$first_check_date = date('W',strtotime($appointment_month_first_date));
			$last_check_date = date('W',strtotime($appointment_date));				
			$counter_for_same_month = (($last_check_date - $first_check_date) + 1);
			
			if (in_array($counter_for_same_month, $week_of_month))
			{
				
				if (in_array($week_number, $frequency_checklist_array1))
				{
					
					$sql= "INSERT INTO $table_name (job_id,admin_id,appointment_text,appointment_date,appointment_time,appointment_time_to,is_full_day,attended,client_not_in,addess,notes,appointment_location,common_appointment_id,updated_by,created_on) VALUES('$job_id','$app_admin_id','$appointment_text','$appointment_date','$appointment_time','$appointment_time_to','$is_full_day','$attended','$client_not_in','$addess','$notes','$appointment_location','$common_appointment_id','".$_SESSION['user_id']."','$created_on')";
					mysqli_query($conn,$sql);
					$appointment_id = mysqli_insert_id();
					
					if($for_first_common_appoint===true){
						$common_appointment_id = $appointment_id;
						$for_first_common_appoint =false;
						mysqli_query("UPDATE $table_name SET common_appointment_id='".$common_appointment_id."' WHERE id='".$appointment_id."' ");
					}
					
					if(isset($_SESSION['uploadfileArray'])){
						foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
							$document_date = date("Y-m-d");
							$document_text = "Appointment document";
							$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$appointment_id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
							mysqli_query($conn,$sql);
						}
						
					}
					/********************* Adding appointment notes *****************************************/
					if(isset($appointment_text) && $appointment_text !=""){
						if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
							$admin_id= $_SESSION['job_user_id'];
							$job_user_id= $_SESSION['job_user_id'];
						}else{
							$admin_id= $_SESSION['user_id'];
						}
						$note_text = $appointment_text;
						$note_date	 = date("Y-m-d");
						$created_on = date("Y-m-d");
					
						$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$appointment_id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
						mysqli_query($sql_notes);
					}
				}
				
			}
			
			$appointment_date = date("Y-m-d",strtotime("+1 day",strtotime($appointment_date)));		
			
		}
	
	}	
		unset($_SESSION['uploadfileArray']);
	}else if($type_of_appointment==4){
		
		$for_first_common_appoint = true;	
			
		while(strtotime($appointment_date)<=strtotime($appointment_date_to)){
		
			$sql= "INSERT INTO $table_name (job_id,admin_id,appointment_text,appointment_date,appointment_time,appointment_time_to,is_full_day,attended,client_not_in,addess,notes,appointment_location,common_appointment_id,updated_by,created_on) VALUES('$job_id','$app_admin_id','$appointment_text','$appointment_date','$appointment_time','$appointment_time_to','$is_full_day','$attended','$client_not_in','$addess','$notes','$appointment_location','$common_appointment_id','".$_SESSION['user_id']."','$created_on')";
			mysqli_query($conn,$sql);
			$appointment_id = mysqli_insert_id();
			if($for_first_common_appoint===true){
				$common_appointment_id = $appointment_id;
				$for_first_common_appoint =false;
				mysqli_query("UPDATE $table_name SET common_appointment_id='".$common_appointment_id."' WHERE id='".$appointment_id."' ");
			}
			if(isset($_SESSION['uploadfileArray'])){
				foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
					$document_date = date("Y-m-d");
					$document_text = "Appointment document";
					$sql = "INSERT INTO documents(job_id,appointment_id,document_date,document_name,document_text,updated_by,created_on) VALUES('$job_id','$appointment_id','$document_date','$uploadfile','$document_text','".$_SESSION['user_id']."','$created_on')";
					mysqli_query($conn,$sql);
				}
				unset($_SESSION['uploadfileArray']);
			}
			/********************* Adding appointment notes *****************************************/
			if(isset($appointment_text) && $appointment_text !=""){
				if(isset($_SESSION['job_user_id']) && $_SESSION['job_user_id'] !=""){
					$admin_id= $_SESSION['job_user_id'];
					$job_user_id= $_SESSION['job_user_id'];
				}else{
					$admin_id= $_SESSION['user_id'];
				}
				$note_text = $appointment_text;
				$note_date	 = date("Y-m-d");
				$created_on = date("Y-m-d");
			
				$sql_notes = "INSERT INTO notes(job_id,appointment_id,admin_id,job_user_id,note_text,note_date,updated_by,created_on) VALUES('$job_id','$appointment_id','$admin_id','$job_user_id','$note_text','$note_date','".$admin_id."','$created_on')";
				mysqli_query($sql_notes);
			}
			/********************* End Adding appointment notes *****************************************/
			
			$appointment_date = date("Y-m-d",strtotime("+14 day",strtotime($appointment_date)));
		}
	}
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace("page=add", "page=list", $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['message']	= ucfirst("Appointment added sucessfully");
	$redirect = "index?page=view&name=$name$query_string";
	header("Location: $redirect");
	exit();
}
################################################# END INSERT #################################################


if($_REQUEST['job_id_search']){
	$job_id_search = $_REQUEST['job_id_search'];
	$where 	.= " AND job_id ='$job_id_search' ";
	$next_page_condition.="&job_id_search=".$_REQUEST['job_id_search'];
}

if($_REQUEST['admin_id_search']){
	$admin_id_search = $_REQUEST['admin_id_search'];
	$where 	.= " AND admin_id LIKE '$admin_id_search%' ";
	$next_page_condition.="&admin_id_search=".$_REQUEST['admin_id_search'];
}
$from_appointment_date = isset($_REQUEST['from_appointment_date']) ? utility::setFormatedDate($_REQUEST['from_appointment_date']) : "";
$to_appointment_date = isset($_REQUEST['to_appointment_date']) ? utility::setFormatedDate($_REQUEST['to_appointment_date']) : "";
if($from_appointment_date && $to_appointment_date){
	$where .= " AND appointment_date BETWEEN '$from_appointment_date 00:00:00' and '$to_appointment_date 23:59:59' ";
    $next_page_condition.="&from_appointment_date=".$_REQUEST['from_appointment_date']."&to_appointment_date=".$_REQUEST['to_appointment_date']." ";
}else if($from_appointment_date){
	$where.= " AND appointment_date >= '$from_appointment_date' ";
	$next_page_condition.="&from_appointment_date=".$_REQUEST['from_appointment_date'];
}else if($to_appointment_date){
	$where.= " AND appointment_date <= '$to_appointment_date' ";
	$next_page_condition.="&to_appointment_date=".$_REQUEST['to_appointment_date'];
}

$query = "SELECT * FROM $table_name $where ORDER BY appointment_date DESC LIMIT $eu, $limit ";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

#################################   DELETE    #########################################
// when we click on delete this area of php appointment will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	$uploaddir = '../document/';
	$id	= $_REQUEST['id'];
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
	/* $sql = "SELECT * FROM document WHERE appointment_id = '$id' ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		while($data = mysqli_fetch_assoc($rs)){
			$document_id = $data["id"];
			$document_name = $data["appointment_document"];
			$old_image	=	$uploaddir.$document_name;	
			if(file_exists($old_image)){
				mysqli_query($conn,"DELETE FROM document WHERE id = '$document_id' ");
				unlink($old_image);
			}
		}
	} */
	
	$common_appointment_id	= $_REQUEST['common_appointment_id'];
	$apply_to_coming_event	= $_REQUEST['apply_to_coming_event'];
	
	/* if($apply_to_coming_event==1){
		$sel_qry = "SELECT * FROM $table_name WHERE common_appointment_id='".$common_appointment_id."' AND appointment_date>='".date('Y-m-d H:i:s')."' ";
		$sel_sql = mysqli_query($sel_qry);
		if(mysqli_num_rows($sel_sql)){
			while($app_row=mysqli_fetch_array($sel_sql)){
				$id = $app_row['id'];
				$sql = "SELECT * FROM document WHERE appointment_id = '$id' ";
				$rs = mysqli_query($conn,$sql);
				if(mysqli_num_rows($rs) > 0){
					while($data = mysqli_fetch_assoc($rs)){
						$document_id = $data["id"];
						$document_name = $data["document_name"];
						$old_image	=	$uploaddir.$document_name;	
						if(file_exists($old_image)){
							mysqli_query($conn,"DELETE FROM document WHERE id = '$document_id' ");
							unlink($old_image);
						}
					}
				}
				mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
			}
		}
	} */
	
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	$query_string = str_ireplace(array("action=delete"), array(""), $query_string);
	$query_string = "&".$query_string;
	
	$_SESSION['message']	= ucfirst("Appointment deleted sucessfully");
	$redirect = "index?page=view";
	header("Location: $redirect$query_string");
	exit();
}
#################################  END DELETE    #########################################
?>

<section class="content-header hide">
  <h1>
	<? echo str_replace(array("_"),array(" "),$page_header); ?>
  </h1>		
</section>
<!----------------------- Message ------------------------------->
	<? if(isset($_SESSION['message'])){ ?>
	<section class="content-header">
	  <div class="alert alert-info alert-dismissable" style="margin-bottom:0px;">
		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
		<? echo $_SESSION['message'];
			unset($_SESSION['message']);
		?>
	  </div>
	</section>
	<? } ?>
<!----------------------- End Message ------------------------------->
	<section class="content">
      <div class="container-fluid">
	  <div class="row">
	  <div class="col-12">

				<div class="">
				<div class="" style="">
					<?php include_once('add_appointment.inc.php');?>
				</div>
				<!--<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">-->					
				<form action="?page=view&name=<?=$name?>" method="post" name="form1" id="form1">
				<? if($result>0){ ?>
				<!-- Start  records header -->
				<div class="box-body table-responsive no-padding">
				<table id="example1" class="table table-bordered table-striped">
					<thead>
						<tr>
							<!--<th>Job Id</th>-->
							<th>Contact</th>
							<!--<th>Documents</th>
							<th>&nbsp;</th>-->
							<th>Description</th>
							<th>Consultant</th>
							<!--<th>Location</th>-->
							<th>Date</th>
							<th>Time From</th>
							<th>Time To</th>
							<!--<th>Full Day</th>-->
							
							<th>Edit</th>						
							<th>Delete</th>
						</tr>
					</thead>
					<tbody>
					<!-- End records header -->
					<?
					while($row = mysqli_fetch_array($sql)){
					?>
					<!-- Start data -->
					<tr>
						<!--<td><?php// echo $row['job_id']; ?></td>-->
						<td><?php
								$first_name = utility::getTableFieldById("job","first_name","id",$row['job_id']);
								$last_name = utility::getTableFieldById("job","last_name","id",$row['job_id']);
								echo ucwords($first_name.' '.$last_name);
							?>
						</td>
						<!--<td>
							<div>
								<?
									/* $appointment_doc = "";
									$sql_for_doc = "SELECT * FROM documents WHERE appointment_id = '".$row['id']."' ";
									$rs_for_doc = mysqli_query($conn,$sql_for_doc);
									if(mysqli_num_rows($rs_for_doc) > 0){
										while($data = mysqli_fetch_assoc($rs_for_doc)){
											$appointment_doc .= "<a href='../../document/".$data["document_name"]."'  target='_blank' style='display:block;margin-top:5px;'><img src='../../document/".$data["document_name"]."' style='width: 31px;height: 31px;'></a>";
										}
										$appointment_doc = substr($appointment_doc,0,-4);
									}
									echo $appointment_doc; */
								?>
							</div>
						</td>	
						<td>
							<div style="overflow:hidden;">
								<?
									/* $appointment_doc = "";
									$sql_for_doc = "SELECT * FROM documents WHERE appointment_id = '".$row['id']."' ";
									$rs_for_doc = mysqli_query($conn,$sql_for_doc);
									if(mysqli_num_rows($rs_for_doc) > 0){
										while($data = mysqli_fetch_assoc($rs_for_doc)){
											$appointment_doc .= "<div style='claer:both;width:200px;' id='doc_div".$data["id"]."'><a href='../../document/".$data["document_name"]."'  target='_blank'>".$data["document_name"]." <i class='fa fa-fw fa-download'></i></a><i class='fa fa-close pull-right document_delete_list' alt='".$data["id"]."' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></div>";
										}
										$appointment_doc = substr($appointment_doc,0,-4);
									}
									echo $appointment_doc; */
								?>
							</div>
						</td>-->						
						<td><?php echo $row['appointment_text']; ?></td>
						<td><?php echo Admin::getAdminsById($row['admin_id']); ?></td>
						<!--<td><?php //echo $row['appointment_location']; ?></td>-->
						<td><?php echo utility::getFormatedDateReturn($row['appointment_date']); ?></td>
						<td><?php echo date('H:i',strtotime($row['appointment_time'])); ?></td>
						<td><?php echo date('H:i',strtotime($row['appointment_time_to'])); ?></td>
						<!--<td><?php //echo ($row['is_full_day'] == 0) ? "No" : "Yes"; ?></td>-->
						
						<td><a href="index?page=view&action=edit&id=<?=$row['id'].$next_page_condition.$paging;?>"> <img src="../images/edit.gif" border="0" /> </a></td>
						<td alt ="<?=$row['common_appointment_id']?>"><a href="" data-toggle="modal" data-target="#myModalForSendMail" class="delete_appoint" alt="<?=$row['id'];?>"><img
							src="../images/del.gif" border="0" /> </a></td>
					</tr>
					<!-- End data -->
					<? 
					}?>
					
					<?}else{?>
					<tr>
						<td colspan="6">No appointment found...</td>
					</tr>
					<?php }?>
					</tbody>
				</table>
				</div>
					<!-- Paging starts here  -->
					<? 
					$next_page_condition .="&page=view";
					include("paging/paging_row.inc.php") ?>
					<!-- Paging ends starts here  -->
						
					<!--</table>-->
					</form>
					</div>
				</div>
			</div>
		</div>
	</section>
<div class="modal fade" id="myModalForSendMail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"></div>	
<script type="text/javascript">
$(document).ready(function(){		
	
	$(".delete_appoint").click(function(){
		if(confirm('Are you sure! You want to delete')){
			
			var appointment_id = $(this).attr('alt');
			var common_appointment_id = $(this).parent().attr('alt'); 
			if(common_appointment_id>0){
				var form_data   = {'appointment_id':appointment_id,'common_appointment_id':common_appointment_id};       
				$.ajax({
					async: false,
					type: "POST",
					url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=confirm_multiple_delete",
					data: form_data,
					success: function(r){ 				
						$('#myModalForSendMail').show().html(r);  // put your modal id 
					}
				});
			}else{
				var form_data   = {'appointment_id':appointment_id};       
				$.ajax({
					async: false,
					type: "POST",
					url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=delete_single_appointment",
					data: form_data,
					success: function(result){
						var resultObj = jQuery.parseJSON(result);
						alert(resultObj.message);
						location.reload();
					}
				});
			}
			//return false;
		}else{
			
			return false;
		}
	});
	$('.delete a').click(function(event) {
		var common_appointment_id = $(this).attr("alt");
		if(confirm('Are you sure! You want to delete')){
			if(common_appointment_id>0){
				if(confirm('Do you want to delete all corresponding appointment.')){
					var href = this.href;
					//alert(href);
					// Don't follow the link
					//event.preventDefault();
					var new_url = href+'&common_appointment_id='+common_appointment_id+'&apply_to_coming_event=1';
					
					window.location = new_url;
					return false;
					
				}else{
					var href = this.href;
					//alert(href);
					// Don't follow the link
					//event.preventDefault();

					// Do the async thing
					startSomeAsyncThing(function() {
						// This is the completion callback for the asynchronous thing;
						// go to the link
						window.location = href;
					});
					
					return false;
				}
				
			}else{
				// Remember the link href
				var href = this.href;
				//alert(href);
				// Don't follow the link
				//event.preventDefault();

				// Do the async thing
				startSomeAsyncThing(function() {
					// This is the completion callback for the asynchronous thing;
					// go to the link
					window.location = href;
				});
			}
			
		}else{
			return false;
		}
	});	
	$(".document_delete_list").click(function(){
		if(confirm("Do you want to delete the document?")){
			var document_id = $(this).attr("alt");
			if(document_id != ""){
				var form_data   = {'document_id':document_id};  
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=delete_document_from_list",
					data: form_data,
					success: function(result){
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$("#doc_div"+document_id).hide();
						}
					}
				});	
			}
		}
	});
});	
</script>		