<?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"];
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	    
	utility::addslashesOnAllInput(array("query_string","admin_id"));
    $job_id = $_REQUEST['job_id'];	
    $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");
		
	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.";
	}
	
	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')";
		mysql_query($sql);
		$appointment_id = mysql_insert_id();
		if(isset($_SESSION['uploadfileArray'])){
			foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
				$sql= "INSERT INTO appointment_document(appointment_id,appointment_document) VALUES('$appointment_id','$uploadfile')";
				mysql_query($sql);
			}
			unset($_SESSION['uploadfileArray']);
		}
	}
	
	$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'){
	$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 = mysql_query($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'];
}
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'];
	$appointment_date	 = utility::setFormatedDate($_REQUEST['appointment_date']);
	$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'];

    $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";
    mysql_query($sql);
	if(isset($_SESSION['uploadfileArray'])){
		foreach($_SESSION['uploadfileArray'] as $key => $uploadfile){
			$sql= "INSERT INTO appointment_document (appointment_id,appointment_document) VALUES('$id','$uploadfile')";
			mysql_query($sql);
		}
		unset($_SESSION['uploadfileArray']);
	}
	
	$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="Appointment Text" class="control-label">Description</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"); ?>
			</div>
			<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 = mysql_query($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-3">
				<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;?>">
				</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;?>">
				</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 class="col-sm-3">
				<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="width:80px;float:left;clear:right;border:0px solid;">
					<label for="Attended" class="control-label">Attended</label><br>
					<input class="flat-red" type="checkbox" id="attended" name="attended" <? echo ($attended) ? "checked" : ""; ?>>
				</div>
				
				<label for="Client not in" class="control-label">Client not in</label><br>
				<input class="flat-red" type="checkbox" id="client_not_in" name="client_not_in" <? echo ($client_not_in) ? "checked" : ""; ?>>
			</div>
			
			<div class="col-sm-3">
				<label for="Addess" class="control-label">Address</label>
				<input type="text" class="form-control" id="addess" name="addess" value="<?php echo $addess;?>">
			</div>

			<div class="col-sm-3" style="word-break: break-all;">
				<label for="Document" class="control-label">Document</label>
				(doc type jpg/jpeg/png/pdf/doc/docx/xls/xlsx)<br>
				<i class="fa fa-upload" style="font-size: 17px;cursor:pointer;" id="document"></i>
				<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 id="document_div">
					<?
						//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>
			</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;?></button>
			</div>
		</form>
	</div>
</div>
</div>
</div>
</section>
<style>
.wrapper{
	background-color:inherit !important;
}
.content-wrapper{
	min-height: 380px  !important;
}
</style>
<script type="text/javascript">
$(function(){
	$("#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();
						}
					}
				});	
			}
		}
	});
	////////////////// 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)$/.test(ext))){ 
					// extension is not allowed 
					alert('Only JPG, PNG, PDF, DOC or DOCX files are allowed');
					return false;
				}
				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" ></script>