<?php 
$button_value 	= "Submit";
$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
$submit_url = $file_name."?page=add_appointment_for_calender&action=insert";
$appointment_date = $_REQUEST["app_date"];
$quotation_area_hide = "none";
$type_of_appointment = 1;
$table_name ='appointment';

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['notes'];
	$appointment_location= $_REQUEST['appointment_location'];
	$created_on = date("Y-m-d");
	$type_of_appointment		= $_REQUEST['type_of_appointment'];
	$week_of_month				= $_REQUEST['week_of_month'];
	$frequency_checklist_array1	= $_REQUEST['frequency_checklist1'];
	$frequency_checklist_array	= $_REQUEST['frequency_checklist'];
	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);
	}
		
	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']);
		//echo $appointment_date."<br>";
		$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($conn,"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($conn,$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_name = utility::getTableFieldById('job','first_name','id',$job_id);
			$last_name = utility::getTableFieldById('job','last_name','id',$job_id);
			if($job_type==1){
				$activity_type_text = ucwords($first_name.' '.$last_name);
			}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_name = utility::getTableFieldById('job','first_name','id',$job_id);
			$last_name = utility::getTableFieldById('job','last_name','id',$job_id);
			$customer_array = array();
			$name = ucfirst($first_name)." ".ucfirst($last_name);
			$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@kingsleyroofers.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>";
				$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($conn,"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($conn,$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($conn,"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($conn,$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($conn,"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($conn,$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($conn,"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($conn,$sql_notes);
			}
			/********************* End Adding appointment notes *****************************************/
			
			$appointment_date = date("Y-m-d",strtotime("+14 day",strtotime($appointment_date)));
		}
	}
	
	
	/* for($i = 1; $i<=$no_of_days; $i++){
		if($i > 1){
			$j = $i - 1;
			$appointment_date	 = date("Y-m-d",strtotime($_REQUEST['appointment_date']." + ".$j."days"));
		}
		$sql= "INSERT INTO appointment (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('$job_id','$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(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($conn,$sql_notes);
		} */
		/********************* End Adding appointment notes *****************************************/
	/* } */
	
	
	
	//$consultant_email = utility::getTableFieldById('admin','email_admin','id',$consultant_id);
	//$consultant_email = "jaydenlewistaylor@gmail.com, adityaprakash89@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 = "&".$query_string;
	
	//$_SESSION['message']	= ucfirst("Appointment added sucessfully");
	$redirect = "index?page=view_calendar_for_appointment$query_string";
	header("Location: $redirect");
	exit();
}
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$quotation_area_hide = "block";
	$submit_url = $file_name."?page=add_appointment_for_calender&action=update";
	$button_value 	= "Update";
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM appointment WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysql_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'];
	
	$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);
}
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){
 
	utility::addslashesOnAllInput(array("query_string","admin_id"));
	unset($_SESSION["update_not_done"]);
	$id= $_REQUEST['id'];
    $job_id= $_REQUEST['job_id'];
    $admin_id= implode(",",$_REQUEST['admin_id']);
    $appointment_text= $_REQUEST['appointment_text'];
	
	$old_appointment_date = utility::getTableFieldById('appointment','appointment_date','id',$id);
	$old_appointment_date = utility::getFormatedDateReturn($old_appointment_date);
	$appointment_date	 = utility::setFormatedDate($_REQUEST['appointment_date']);
	$old_appointment_time = utility::getTableFieldById('appointment','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'];

    $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($conn,$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_name = utility::getTableFieldById('job','first_name','id',$job_id);
		$last_name = utility::getTableFieldById('job','last_name','id',$job_id);
		$customer_array = array();
		$name = ucfirst($first_name)." ".ucfirst($last_name);
		$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@kingsleyroofers.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_calendar_for_appointment$query_string";
	header("Location: $redirect");
	exit();
	
}
?>
<div style="clear:both;"></div>
<!----------------------- Message ------------------------------->
	<? if(isset($_SESSION['message'])){ ?>
	<section class="content-header">
	  <div class="alert alert-info alert-dismissable" style="margin-bottom:10px;">
		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
		<? echo $_SESSION['message'];
			unset($_SESSION['message']);
		?>
	  </div>
	</section>
	<div style="clear:both;"></div>
	<? } ?>
<!----------------------- End Message ------------------------------->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="panel box box-primary" id="booke_appointment_area">
	<div class="box-header with-border">
		<form action="<?php echo $submit_url;?>" method="post" name="add_form" id="add_form">
			<div class="col-sm-3">
				<label for="Notes" class="control-label">Notes</label>
				<textarea class="form-control" rows="4" id="appointment_text" name="appointment_text" required><?php echo stripslashes($appointment_text);?></textarea>
				
				<label for="Job" class="control-label">Job</label>
				<? $krscrm->getEnqQuoteJobList("job_id",$job_id,"100%",false,"form-control select2","required"); ?>
				
				<!--<label for="Document" class="control-label">Document</label>
				<i class="fa fa-upload" style="font-size: 17px;cursor:pointer;" id="document"></i>
				<i style="display:block;color:red;font-size: 12px;">(doc type pdf/doc/docx/xls/xlsx)</i><br>
				<i class="fa fa-check pull-right" id="upload_complete" style="color:#bad23a;font-size: 20px;display:none;"></i>
				<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="page_load_div"></i><br><br>-->
				<div style="overflow:hidden;" class="hide">
					<?
						/* $appointment_doc_calend = "";
						if($_REQUEST['id']!=""){
							$sql_for_doc_calend = "SELECT * FROM documents WHERE appointment_id = '".$_REQUEST['id']."' ";
							$rs_for_doc_calend = mysqli_query($conn,$sql_for_doc_calend);
							if(mysql_num_rows($rs_for_doc_calend) > 0){
								while($data_calend = mysql_fetch_assoc($rs_for_doc_calend)){
									$appointment_doc_calend .= "<p style='clear:both;width:100%;margin: 0;' title='".$data_calend["document_name"]."' id='doc_div".$data_calend["id"]."'>".utility::ellipsis(strtoupper(strip_tags($data_calend["document_name"])),15)." <i class='fa fa-close pull-right document_delete_list' alt='".$data_calend["id"]."' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>";
								}
								$appointment_doc_calend = substr($appointment_doc_calend,0,-4);
							}
							echo $appointment_doc_calend;
						} */
					?>
				</div>
				<div id="document_div" class="hide">
					<?
						//unset($_SESSION['uploadfileArray']);
						/* if(isset($_SESSION['uploadfileArray'])){
							//print_r($_SESSION['uploadfileArray']);
							foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
								$doc_no = $key + 1;
								echo "<p id='document_p".$doc_no."'>".$uploadfile."<i class='fa fa-close pull-right document_delete' alt='".$uploadfile."' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>";
							}
						} */
					?>
				</div>
				<!--<label for="Document" class="control-label">Image</label>
				<input type="file" id="fileinput" />
				<img id="source_image"  style="width:100%" class="hide" >
				<input type="button" id="compress" value="Compress" class="btn-primary" style="display: none;">
				<img id="compressed_image"  style="width:100%" class="hide" >
				<input type='text' id="orientation"  class="hide" >
				<input type="button" id="upload" class="btn-success" value="Upload" style="display: none;">
				<i style="display:block;color:red;font-size: 12px;">(doc type jpg/jpeg/png)</i><br>-->
			</div>
			
			<div class="hideshowonmob_2" style="margin: 15px 0;">
			
			<div class="col-sm-3">
				
				
				<label for="Staff Member" class="control-label">Staff Member</label>
				<div id="admin_id_div">
				<? 
					$admin_ids = "";
					$sql_for_admin = "SELECT * FROM job_admin_mapping WHERE job_id = $job_id";
					$rs_for_admin = mysqli_query($conn,$sql_for_admin);
					if(mysql_num_rows($rs_for_admin) > 0){
						while($row_for_admin = mysql_fetch_assoc($rs_for_admin)){
							$admin_ids .= $row_for_admin["admin_id"].",";
						}
						$admin_ids = substr($admin_ids,0,-1);
					}
					Admin::getAdminList("admin_id",$admin_id,"100%",true,"form-control select_admin_id","required",$admin_ids); 
				?>
				</div>
				
				<label for="Appointment" class="control-label">Date <? if(!(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit')){ ?>From<? } ?></label>
				<input type="text" class="form-control datepicker" id="appointment_date" name="appointment_date" value="<?php (isset($appointment_date) && $appointment_date !="") ? utility::getFormatedDate($appointment_date) : utility::getFormatedDate(date($config->dateFormat));?>" required>
			</div>
			<div class="col-sm-2">
				<label for="Appointment Time" class="control-label">Time From</label>
				<div class="bootstrap-timepicker">
					<!--<input type="text" class="form-control timepicker" id="appointment_time" name="appointment_time" value="<?php //echo $appointment_time;?>">-->
					<? utility::getTimeList("appointment_time", $appointment_time, "Time From", "100%");?>
				</div>
				
				<label for="Appointment Time" class="control-label">Time To</label>
				<div class="bootstrap-timepicker">
					<!--<input type="text" class="form-control timepicker" id="appointment_time_to" name="appointment_time_to" value="<?php //echo $appointment_time_to;?>">-->
					<? utility::getTimeList("appointment_time_to", $appointment_time_to, "Time To", "100%");?>
				</div>
				
				<? if(!(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit')){ ?>
					<label for="Appointment" class="control-label">Date To</label>
					<input type="text" class="form-control datepicker" id="appointment_date_to" name="appointment_date_to" value="<?php (isset($appointment_date) && $appointment_date !="") ? utility::getFormatedDate($appointment_date) : utility::getFormatedDate(date($config->dateFormat));?>" required>
				<? } ?>
			</div>
			
			</div>
			<a style="margin-left: 15px;margin-top: 15px;" class="hideshowonmob_btn_2">Show Details</a>
			<a style="margin-left: 15px;margin-top: 15px;" class="hideshowonmob_hide_btn_2">Hide Details</a>
			
			<div class="col-sm-4">
				<!--<label for="Addess" class="control-label">Address</label>
				<? 
					// $jobtypetext = utility::getTableFieldById("job","client_industry","id",$job_id);
					// $jobtypefeild = $krscrm->getkrsJobTypeById($jobtypetext);
					//echo $jobtypefeild;
					// $secondaddress_ap = utility::getTableFieldById("job","second_address","id",$job_id);				
					// if($jobtypefeild == 'Domestic' or $secondaddress_ap == ''){
				?>
				<input type="text" class="form-control" id="addess" name="addess" value="<?php echo $addess;?>"><br />
				<?//}else{?>
				<input type="text" class="form-control" id="addess" name="addess" value="<?php echo $secondaddress_ap;?>"><br />-->
				<?//}?>
				<!--<input type="text" class="form-control" id="addess" name="addess" value="<?php //echo $addess;?>"><br />-->
				
				<!--<label for="Location" class="control-label">Location</label>
				<input type="text" class="form-control" id="appointment_location" name="appointment_location" value="<?php //echo $appointment_location;?>">-->
				
				<!--<div style="width:80px;float:left;clear:right;border:0px solid;">
					<label for="Full Day" class="control-label">Full Day</label><br>
					<input class="flat-red" type="checkbox" id="is_full_day" name="is_full_day" <? //echo ($is_full_day) ? "checked" : ""; ?>>
				</div>-->
				<div style="display:<?=$quotation_area_hide;?>;">
					<!--<div class="form-group">
						<input class="flat-red" type="checkbox" id="attended" name="attended" <? echo ($attended) ? "checked" : ""; ?>>&nbsp;&nbsp;<b>Attended</b>
					</div>
					
					<div class="form-group">
						<input class="flat-red" type="checkbox" id="client_not_in" name="client_not_in" <? echo ($client_not_in) ? "checked" : ""; ?>>&nbsp;&nbsp;<b>Client not in</b>
					</div>
					
					<hr />-->
					<div class="form-group">
						<input type="checkbox" class="flat-red quotation_status" id="to_quote" name="to_quote" value="1"  <? echo ($to_quote ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>To Quote</b>						
						<i class="fa fa-check pull-right" id="to_quote_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
						<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="to_quote_refresh"></i>
					</div>
					<div class="form-group">
						<input type="checkbox" class="flat-red quotation_status" id="quoted" name="quoted" value="1"  <? echo ($quoted ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Quoted</b>						
						<i class="fa fa-check pull-right" id="quoted_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
						<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="quoted_refresh"></i>
					</div>
					<div class="form-group">
						<input type="checkbox" class="flat-red quotation_status" id="quotation_accepted" name="quotation_accepted" value="1"  <? echo ($quotation_accepted ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Quotation Accepted</b>						
						<i class="fa fa-check pull-right" id="quotation_accepted_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
						<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="quotation_accepted_refresh"></i>
					</div>
					<div class="form-group">
						<input type="checkbox" class="flat-red quotation_status" id="accepted_date_given" name="accepted_date_given" value="1"  <? echo ($accepted_date_given ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Accepted Date Given</b>
						<i class="fa fa-check pull-right" id="accepted_date_given_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
						<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="accepted_date_given_refresh"></i>
					</div>
					<div class="form-group">	
						<input type="checkbox" class="flat-red quotation_status" id="quotation_declined" name="quotation_declined" value="1"  <? echo ($quotation_declined ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Quotation Declined</b>
						<i class="fa fa-check pull-right" id="quotation_declined_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
						<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="quotation_declined_refresh"></i>
					</div>
				</div>
			</div>
			
			<?if($action != 'edit'){?>
			<div class="col-sm-3">
				<label for="Date of event" class="control-label">Frequency</label>				  
				<? $krscrm->getTypeOfAppointmentList("type_of_appointment",$type_of_appointment,"100%",false,"form-control select2","required"); ?>
				<?
				$fre_display = 'block';
				if($type_of_appointment==1){
					$fre_display = 'none';
				}?>
				
				<div class="form-group the_day_options" style="display:<?=$fre_display?>;margin-top:10px">
                  <div class="radio">
                    <label>
                      <input type="radio" name="dayOptions" id="optionsDay" value="day">
						Day	
					  </label>		
					  <label>		
					   <input type="radio" name="dayOptions" id="optionsThe" value="the">
						The
					  </label>
                  </div>
                </div>
				
				<div class="for_monthly " style="display:<?=$fre_display?>;margin-top:10px">
					
					<div class="form-group day_option">
						<label>Day of Month</label>
						<? $krscrm->getDayOfMonthList("day_of_month",$day_of_month,"100%",true,"form-control select2 day_of_month"); ?>
					</div>
					
					<div class="the_monthly_option">
						<div class="form-group">
							<label>Week</label>
							<? $krscrm->getWeekList("week_of_month",$week_of_month,"100%",true,"form-control select2 week_of_month"); ?>
						</div>
						
						<div class="form-group">
							<label>Day</label>
							<? $krscrm->getDayOfWeekList("frequency_checklist1",$frequency_checklist,"100%",true,"form-control select2 frequency_checklist1"); ?>
						</div>
					</div>
				</div>
				
				<div class="form-group occurrence" style="display:<?=$fre_display?>">
					<!--<label for="Date of event" class="control-label">Frequency</label>-->
					<div class="" style="padding-top:8px">
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="first_week" class="week_checkbox" name="frequency_checklist[]" value="1" <?php echo ($frequency_checklist=="1")?" checked='checked' ":"";?>/>&nbsp;Mon</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="second_week" class="week_checkbox" name="frequency_checklist[]" value="2" <?php echo ($frequency_checklist=="2")?" checked='checked' ":"";?>/>&nbsp;Tue</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="third_week" class="week_checkbox" name="frequency_checklist[]" value="3" <?php echo ($frequency_checklist=="3")?" checked='checked' ":"";?>/>&nbsp;Wed</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="fourth_week" class="week_checkbox" name="frequency_checklist[]" value="4" <?php echo ($frequency_checklist=="4")?" checked='checked' ":"";?>/>&nbsp;Thu</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="fifth_week" class="week_checkbox" name="frequency_checklist[]" value="5" <?php echo ($frequency_checklist=="5")?" checked='checked' ":"";?>/>&nbsp;Fri</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="sixth_week" class="week_checkbox" name="frequency_checklist[]" value="6" <?php echo ($frequency_checklist=="6")?" checked='checked' ":"";?>/>&nbsp;Sat</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="seventh_week" class="week_checkbox" name="frequency_checklist[]" value="7" <?php echo ($frequency_checklist=="7")?" checked='checked' ":"";?>/>&nbsp;Sun</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="every_week"  name="frequency_checklist[]" value="8" <?php echo ($frequency_checklist=="8")?" checked='checked' ":"";?>/>&nbsp;Every Day</div>
					</div>
				</div>
		
			</div>
			<?}?>

			
			<!--<div class="col-sm-3">
				<label for="Notes" class="control-label">Notes</label>
				<textarea class="form-control" rows="4" id="notes" name="notes"><?php //echo stripslashes($notes);?></textarea>
			</div>-->
			<div style="clear:both;margin-top:5px;"></div>
			<div class="col-sm-3">
				<label for="Full Day" class="control-label">&nbsp;</label><br>
				<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
				<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
				<input type="hidden" id="source" name="source" value="<?php echo $source;?>">
				<button type="submit" name="add_master_data" id="submit_form" class="btn btn-primary"><?=$button_value;?>
					<i class="fa fa-refresh fa-spin" style="display:none;" id="page_load_div"></i>
				</button>
			</div>
		</form>
	</div>
</div>
</div>
</div>
</section>
<style>
label {
    margin-top: 5px;
}
.wrapper{
	background-color:inherit !important;
}
.content-wrapper{
	min-height: 380px  !important;
}
.hideshowonmob_btn_2{
	display:none;
	margin-bottom: 15px;
	text-decoration: underline;
    cursor: pointer;
    font-size: 15px;
}
.hideshowonmob_hide_btn_2{
	display:none;
	margin-bottom: 15px;
    text-decoration: underline;
    cursor: pointer;
    font-size: 15px;
}
@media only screen and (max-width: 640px){
	.hideshowonmob_2{
		/* display:none; */
	}
	.hideshowonmob_btn_2{
		/* display:block; */
	}
	.document_delete_list{
		font-size:18px;
	}
}
</style>
<script type="text/javascript">
$(function(){
	$('#add_form').submit(function(){
		$("#add_master_data").attr("disabled", true);
		$('#page_load_div').show();
	});
	
	$("#add_form").on("click","#every_week",function(){
		if($("#every_week:checked").length == 1){
			$('.week_checkbox').prop( "checked", true );
		}else{
			$('.week_checkbox').prop( "checked", false );
		}
	});
	
	$("#add_form").on("change","#type_of_appointment",function(){
		var type_of_appointment = $(this).val();
		
		if(type_of_appointment == 3 || type_of_appointment == 2 ){
			if(type_of_appointment == 2){
				
				$('.the_day_options').show();
				//$('.for_monthly').show();
				$('.occurrence').hide();
			}else{
				$('.occurrence').show();
				$('.the_day_options').hide();
				$('.for_monthly').hide();
				
				$('input[name="dayOptions"]').prop('checked', false);
				$('.week_of_month').select2("val", "");
				$(".frequency_checklist1").select2("val", "");
			}
		}else{
			
			//$('#day_of_week').select2("val", "");
			$('.week_checkbox').prop( "checked", false );
			$('.occurrence').hide();
			$('.for_monthly').hide();
			$(".the_day_options").hide();
			
			$('input[name="dayOptions"]').prop('checked', false);
			$('.week_of_month').select2("val", "");
			$(".frequency_checklist1").select2("val", "");
		}
	});
		
	$("#add_form").on("click", "#optionsDay,#optionsThe",function() {
		$('.for_monthly').show();
		if($(this).val()=='day'){			
			$(".day_option").show();
			$(".the_monthly_option").hide();
			$('.week_of_month').select2("val", "");
			$(".frequency_checklist1").select2("val", "");
		}else{			
			$('.day_of_month').select2("val", "");
			$(".day_option").hide();
			$(".the_monthly_option").show();
		}
	});
	
	
	<? if($_REQUEST['action'] == 'edit'){ ?>
	if(window.matchMedia("(max-width: 640px)").matches){
	$(".hideshowonmob_2").hide('slow');
	$(".hideshowonmob_hide_btn_2").hide();
	$(".hideshowonmob_btn_2").show();
	
	$(".hideshowonmob_btn_2").on("click",function() {
		$(".hideshowonmob_2").show('slow');
		$(".hideshowonmob_hide_btn_2").show();
		$(".hideshowonmob_btn_2").hide();
	});
	
	$(".hideshowonmob_hide_btn_2").on("click",function() {
		$(".hideshowonmob_2").hide('slow');
		$(".hideshowonmob_hide_btn_2").hide();
		$(".hideshowonmob_btn_2").show();
	});
	}
	<?}?>
	
	function getOrientation(file, callback) {
	  var reader = new FileReader();

	  reader.onload = function(event) {
		var view = new DataView(event.target.result);

		if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

		var length = view.byteLength,
			offset = 2;

		while (offset < length) {
		  var marker = view.getUint16(offset, false);
		  offset += 2;

		  if (marker == 0xFFE1) {
			if (view.getUint32(offset += 2, false) != 0x45786966) {
			  return callback(-1);
			}
			var little = view.getUint16(offset += 6, false) == 0x4949;
			offset += view.getUint32(offset + 4, little);
			var tags = view.getUint16(offset, little);
			offset += 2;

			for (var i = 0; i < tags; i++)
			  if (view.getUint16(offset + (i * 12), little) == 0x0112)
				return callback(view.getUint16(offset + (i * 12) + 8, little));
		  }
		  else if ((marker & 0xFF00) != 0xFF00) break;
		  else offset += view.getUint16(offset, false);
		}
		return callback(-1);
	  };

	  reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
	};
	
	var output_format = null;
	var file_name = null;
	function readFile(evt) {
		$("#page_load_div").show();
		$("#upload_complete").hide();
		var file = evt.target.files[0];
		getOrientation(file, function(orientation) {			
			$("#orientation").val(orientation);
			console.log("orientation : "+orientation);
		 });
		var reader = new FileReader();
	    reader.onload = function(event) {
			var i = document.getElementById("source_image");
			console.log(i);
	            i.src = event.target.result;
	            i.onload = function(){
	                
	                console.log("Image loaded");
	            }
	    };
		output_format = file.name.split(".").pop();
		file_name = file.name;
	    console.log("Filename:" + file.name);
	    console.log("Fileformat:" + output_format);
	    console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
	    console.log("Type:" + file.type);
	    reader.readAsDataURL(file);
		
		//$("#compress").show();
		setTimeout(function(){
			$("#compress").trigger('click');
		},2000);
		
	    return false;
	}
 // compress image
 	$( "#compress" ).click(function() {
        var source_image = document.getElementById("source_image");
        if (source_image.src == "") {
            alert("You must load an image first!");
            return false;
        }

        var quality = 30;
       	
        console.log("process start...");
        console.log("process start compress ...");
	    compressed_image.src = jic.compress(source_image,quality,output_format).src;
		//$("#upload").trigger('click');
		//$("#upload").show();
		$("#upload").trigger('click');
    	
	});
	// upload imange
	$( "#upload" ).click(function() {
        var compressed_image = document.getElementById("compressed_image");
        if (compressed_image.src == "") {
            alert("You must compress image first!");
            return false;
        }

	    var successCallback= function(response){
			var resultObj = jQuery.parseJSON(response);
		    $.each(resultObj.uploadfileArray, function(key,value) {
				
				id = key+1;
				$("<p id='document_p"+id+"'>"+value+"<i class='fa fa-close pull-right document_delete' alt='"+value+"' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>").appendTo("#document_div");
			});
			$("#page_load_div").hide();
			$("#upload_complete").show();
			setTimeout(function(){
				$("#upload_complete").hide();
			},2000);	
			console.log("image uploaded successfully! :)");
            console.log(response);       
        }

        var errorCallback= function(response){
            console.log("image Filed to upload! :)");
            console.log(response);
			$("#page_load_div").hide();
			$("#upload_complete").hide();	
        }
    	
		var orientation = $("#orientation").val();
    	console.log("process start upload ...");
    	jic.upload(compressed_image, "<?php echo $siteURL?>/appointment/index?page=ajax_actions&action=upload_image&orientation="+orientation, "file", file_name,successCallback,errorCallback);
    	
    });

	var el = document.getElementById("fileinput")
	if(el){
		el.addEventListener("change", readFile, 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();
						}
					}
				});	
			}
		}
	});
	
	$("#add_form").on("click",".select_admin_id",function(){
		if($("#job_id").val() == ""){
			alert("First select Enquiry/Quote/Job");
			$(this).val("");
			return false;
		}
	});
	/* $("#job_id").change(function(){	
		var job_id = $(this).val();
		if(job_id != ""){
		var form_data   = {'job_id':job_id};       
			$.ajax({
				async: false,
				type: "POST",
				url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=get_admin_by_job",
				data: form_data,
				success: function(result){  
					if(result){
						$("#admin_id_div").html(result);
					}else{
						alert("No consultant assign to this job. First assign consultant.");
						$("#admin_id_div").html(result);
					}
				}
			});
			$.ajax({
				async: false,
				type: "POST",
				url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=get_address_by_job",
				data: form_data,
				success: function(result){  
					if(result){
						$("#addess").val(result);
					}
				}
			});
		}
	}); */
	$("#submit_form").click(function(){	
		if($("#span").text() == "No consultant assign to this job. First assign consultant."){
			alert("First select Consultant");
			return false;
		}
	});
	////////////////// DOCUMENT DELETE //////////////////////////////////////
	$("#add_form").on("click",".document_delete",function(){
		if(confirm("Do you want to delete the document?")){
			var document_p_id = $(this).parent().attr("id");
			//alert(document_p_id);
			var document_name = $(this).attr("alt");
			if(document_name != ""){
				var form_data   = {'document_name':document_name};  
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=delete_document",
					data: form_data,
					success: function(result){
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$("#"+document_p_id).hide();
						}
					}
				});	
			}
		}
	});
	
	$('.quotation_status').on('ifClicked', function(){
		
		$('.quotation_status').iCheck('uncheck');
		$(this).iCheck('check');
		
		if($(this).attr("name") == "to_quote"){
			$("#to_quote_refresh").show();
		}else if($(this).attr("name") == "quoted"){
			$("#quoted_refresh").show();
		}else if($(this).attr("name") == "quotation_accepted"){
			$("#quotation_accepted_refresh").show();
		}else if($(this).attr("name") == "accepted_date_given"){
			$("#accepted_date_given_refresh").show();
		}else if($(this).attr("name") == "quotation_declined"){
			$("#quotation_declined_refresh").show();
		}
		
		var quotation_status = $(this).attr("name");
		var job_id = $("#job_id").val();
		//alert('aaaaaaaaaaa'+job_id);
		var form_data   = {'job_id':job_id,'quotation_status':quotation_status};       
		$.ajax({
			async: true,
			type: "POST",
			url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=update_quotation",
			data: form_data,
			success: function(r){    
				$("#to_quote_refresh").hide();
				$("#quoted_refresh").hide();
				$("#quotation_accepted_refresh").hide();
				$("#accepted_date_given_refresh").hide();
				$("#quotation_declined_refresh").hide();
				
				if(r == "to_quote"){
					$("#to_quote_check").show();
					setTimeout(function(){
						$("#to_quote_check").hide();
					},2000);
				}else if(r == "quoted"){
					$("#quoted_check").show();
					setTimeout(function(){
						$("#quoted_check").hide();
					},2000);
				}else if(r == "quotation_accepted"){
					$("#quotation_accepted_check").show();
					setTimeout(function(){
						$("#quotation_accepted_check").hide();
					},2000);
				}else if(r == "accepted_date_given"){
					$("#accepted_date_given_check").show();
					setTimeout(function(){
						$("#accepted_date_given_check").hide();
					},2000);
				}else if(r == "quotation_declined"){
					$("#quotation_declined_check").show();
					setTimeout(function(){
						$("#quotation_declined_check").hide();
					},2000);
				}
			}
		});
	});
	
	////////////////// AJAX UPLOAD //////////////////////////////////////
	var btnUpload=$('#document');
	//$("#document").click(function(){
		//var identification_span_id = $(this).attr("alt");
		var form_data   = {'job_id':'1'};    
		new AjaxUpload(btnUpload, {
			action: '<?php echo $siteURL?>/appointment/index?page=ajax_actions&action=upload_document',
			name: 'uploadfile[]',
			data: form_data,
			onSubmit: function(file, ext){
				if (! (ext && /^(jpg|png|jpeg|pdf|doc|docx|xls|xlsx|csv)$/.test(ext))){ 
					// extension is not allowed 
					alert('Only JPG, PNG, PDF, xls, xlsx, DOC or DOCX files are allowed');
					return false;
				}
				$("#page_load_div").show();
				$("#upload_complete").hide();
				/* if(confirm("Do you want to upload")){
					$("#page_load_div").show();
					$("#upload_complete").hide();
				}else{
					return false;
				} */
			},
			onComplete: function(file, response){
				var resultObj = jQuery.parseJSON(response); 
				if(resultObj.status == "success"){
					console.log(response);
					$("#page_load_div").hide();
					$("#upload_complete").show();
					setTimeout(function(){
						$("#upload_complete").hide();
					},2000);
					
					$.each(resultObj.uploadfileArray, function(key,value) {
						//alert(key+" "+value);
						id = key+1;
						$("<p id='document_p"+id+"'>"+value+"<i class='fa fa-close pull-right document_delete' alt='"+value+"' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>").appendTo("#document_div");
					});
				} else{
					$("#page_load_div").hide();
					$("#upload_complete").hide();
					alert("There is some error to upload file.");
				}
				$("input[name='uploadfile[]']").attr("multiple","multiple");
			}
		});
	//});
	
	$("input[name='uploadfile[]']").attr("multiple","multiple");
	
	
});
</script>
<script type="text/javascript" src="<?php echo $siteURL?>/modules/appointment/js/ajaxupload.3.5.js" defer ></script>
<script type="text/javascript" src="<?php echo $siteURL?>/modules/appointment/js/jic.js" defer ></script>