
<?php
$LeaveAnnounce          = new Announcement();
$employee                = new Employee();
$absence_employees = $employee->viewEmployee();
$ViewLeave = $LeaveAnnounce->viewAllAssignLeave();

if(isset($_GET["GetLeaveID"])){
	$LeaveAnnounce          = new Announcement;
	$Content = $LeaveAnnounce->viewLeaveByID($_GET["GetLeaveID"]);
	die($Content ? json_encode($Content) : "");
}

if(isset($_POST["Employee_ID"])){
	session_start();
	$logged_id      = Session::getUserID();
	array_push($_POST,$logged_id);

	$Check = $LeaveAnnounce->setData($_POST)->checkExistLeave(); 
	if(is_array($Check)){
		die (json_encode($Check));
	}
	else{
		if($Check){
			

			
			
			die ("success");
		}
		else die("error");
	}





}

//include("xhr/calendar.php");

/* Status

    0  Planned      > orange
	1  Declined     > red
	2  Approved     > green
	3  Done         > blue
    4  Deleted      > Gray

    */

?>
<script>var Events = <?php echo json_encode($Update) ;?>;</script>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title><?php print CommonLanguage::getMessage('leave');?></title>

	<!-- Vendor CSS -->
	<link href="vendors/bower_components/animate.css/animate.min.css" rel="stylesheet">
	<link href="vendors/bower_components/bootstrap-sweetalert/lib/sweet-alert.css" rel="stylesheet">
	<link href="vendors/bower_components/material-design-iconic-font/dist/css/material-design-iconic-font.min.css" rel="stylesheet">
	<link href="vendors/bower_components/fullcalendar/dist/fullcalendar.min.css" rel="stylesheet">
	<link href="vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.min.css" rel="stylesheet">        

	<!-- CSS -->
	<link href="css/app.min.1.css" rel="stylesheet">
	<link href="css/app.min.2.css" rel="stylesheet">
	<link href="<?php echo THEME_PATH; ?>plugins/bootstrap-timepicker/css/bootstrap-timepicker.min.css" rel="stylesheet" type="text/css"/>
</head>
<script src="<?php echo THEME_PATH; ?>plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.js"></script>
<body>


	<section id="main">



		<section id="content">
			<div class="container c-alt">


				<div id="calendar" style="border: 1px solid #000"></div>

				<!-- Add event -->
				<div class="modal fade" id="addNew-event" data-backdrop="static" data-keyboard="false">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<h4 class="modal-title"><?php print CommonLanguage::getMessage('add_event');?></h4>
							</div>
							<div class="modal-body">
								<form class="addEvent" role="form">
									<div class="form-group col-md-6">
										<label for="eventName"><?php print CommonLanguage::getMessage('employee_name');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" data-value=0 id="Add_Employee_Name" >
										</div>
									</div>
									<div class="form-group col-md-6">
										<label for="eventName"><?php print CommonLanguage::getMessage('leave_name');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="eventName" >
										</div>
									</div>

									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('start_date');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="AssignLeave_From_Date" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('end_date');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="AssignLeave_To_Date" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('from_time');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="AssignLeave_Start_Time" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('to_time');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="AssignLeave_End_Time" />
										</div>
									</div>


									<div class="form-group col-md-12">
										<label for="eventName"><?php print CommonLanguage::getMessage('color');?></label>
										<div class="event-tag">
											<span value="0" data-tag="bgm-orange" class="bgm-orange selected" ></span>
											<span value="1" data-tag="bgm-red" class="bgm-red"></span>
											<span value="2" data-tag="bgm-green" class="bgm-green"></span>
											<span value="3" data-tag="bgm-blue" class="bgm-blue" ></span>
											<span value="4" data-tag="bgm-gray" class="bgm-gray"></span>
										</div>
									</div>

									<input type="hidden" id="getStart" />
									<input type="hidden" id="getEnd" />
								</form>
							</div>

							<div class="modal-footer">
								<button type="submit" class="btn btn-success" id="addEvent"><?php print CommonLanguage::getMessage('Save');?></button>
								<button type="button" class="btn btn-danger" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close');?></button>
							</div>
						</div>
					</div>
				</div>



				<div class="modal fade" id="EditLeave" data-backdrop="static" data-keyboard="false">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<h4 class="modal-title"><?php print CommonLanguage::getMessage('edit_event');?></h4>
							</div>
							<div class="modal-body">
								<form class="EditLeave" role="form">
									<div class="form-group col-md-6">
										<label for="eventName"><?php print CommonLanguage::getMessage('employee_name');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control Employee_Name" id="Employee_Name" />
										</div>
									</div>
									<div class="form-group col-md-6">
										<label for="eventName"><?php print CommonLanguage::getMessage('leave_name');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="Title" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('start_date');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="EditAssignLeave_From_Date" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('end_date');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="EditAssignLeave_To_Date" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('from_time');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="EditAssignLeave_Start_Time" />
										</div>
									</div>
									<div class="form-group col-md-3">
										<label for="eventName"><?php print CommonLanguage::getMessage('to_time');?></label>
										<div class="fg-line">
											<input type="text" class="input-sm form-control" id="EditAssignLeave_End_Time" />
										</div>
									</div>


									<div class="form-group col-md-12">
										<label for="eventName"><?php print CommonLanguage::getMessage('color');?></label>
										<div class="event-tag Edit">

											<span value=0 data-tag="bgm-orange" class="bgm-orange" ></span>
											<span value=1 data-tag="bgm-red" class="bgm-red"></span>
											<span value=2 data-tag="bgm-green" class="bgm-green"></span>
											<span value=3 data-tag="bgm-blue" class="bgm-blue" ></span>
											<span value=4 data-tag="bgm-gray" class="bgm-gray"></span>



										</div>
									</div>


								</form>
							</div>

							<div class="modal-footer">
								<button type="button" class="btn btn-success" id="SumbitEdit"><?php print CommonLanguage::getMessage('Save');?></button>
								<button type="button" class="btn btn-danger" id="CancelEdit"data-dismiss="modal"><?php print CommonLanguage::getMessage('Close');?></button>
							</div>
						</div>
					</div>
				</div>





			</div>
		</section>
	</section>



	<!-- Page Loader -->
	<div class="page-loader">
		<div class="preloader pls-blue">
			<svg class="pl-circular" viewBox="25 25 50 50">
				<circle class="plc-path" cx="50" cy="50" r="20" />
			</svg>

			<p><?php print CommonLanguage::getMessage('plz_wait');?></p>
		</div>
	</div>

	<div class="modal fade stick-up " id="ModalToAssignByForce" tabindex="-1" role="dialog" aria-hidden="true" style="    width: 50%;
																													  margin: 0 auto;">
		<div class="modal-dialog ">
			<div class="modal-content">
				<div class="modal-header clearfix text-left">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>
					<h5><span class="semi-bold"> <?php print CommonLanguage::getMessage('assign_leave_force');?> </span></h5>
				</div>
				<div class="modal-body">
					<form>
						<div class="row">
							<div class="col-md-12 ">
								<div class="col-md-12" style="margin-top: 20px;">
									<p><strong class="Name"></strong><?php print CommonLanguage::getMessage('common_leave_dur');?> </p>
									<p><?php print CommonLanguage::getMessage('Proceed_Delete');?></p>
								</div>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close');?></button>
					<button type="button" class="btn btn-success" id="ConfirmAssign" style="width:auto"><?php print CommonLanguage::getMessage('Save');?></button>
				</div>
			</div>
		</div>
	</div>


	<div class="modal fade bs-example-modal-md" id="ErrorModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
		<div class="modal-dialog" style="width:50%">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
					<h4 class="modal-title" id="mySmallModalLabel"><?php print CommonLanguage::getMessage('edit_event');?></h4>
				</div>
				<div class="modal-body">
					<div class="row">
						<div class="col-md-12 ">
							<div class="col-md-12" style="margin-top: 20px;text-align: center">
								<p style=";display: block;" class="alert alert-danger"><?php print CommonLanguage::getMessage('edit_event_hint');?> <span class="bold Status"></span></p>

							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
				</div>
			</div>
		</div>
	</div>









	<!-- Javascript Libraries -->


	<script src="vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js"></script>
	<script src="vendors/bower_components/Waves/dist/waves.min.js"></script>
	<script src="vendors/bootstrap-growl/bootstrap-growl.min.js"></script>
	<script src="vendors/bower_components/bootstrap-sweetalert/lib/sweet-alert.min.js"></script>
	<script src="vendors/bower_components/moment/min/moment.min.js"></script>
	<script src="vendors/bower_components/fullcalendar/dist/fullcalendar.min.js"></script>

	<!-- Placeholder for IE9 -->
	<!--[if IE 9 ]>
<script src="vendors/bower_components/jquery-placeholder/jquery.placeholder.min.js"></script>
<![endif]-->

	<script src="functions.js"></script>


	<script type="text/javascript">
        var MonthViewLang = <?php echo json_encode(CommonLanguage::getMessage('month_view'));?>,
            WeekViewLang = <?php echo json_encode(CommonLanguage::getMessage('week_view'));?>,
            AgendaWeekViewLang = <?php echo json_encode(CommonLanguage::getMessage('agenda_week_view'));?>,
            DayViewLang = <?php echo json_encode(CommonLanguage::getMessage('day_view'));?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit'));?>,
            AgendaDayViewLang = <?php echo json_encode(CommonLanguage::getMessage('agenda_day_view'));?>;
		var CurrentLeave = <?php echo json_encode($ViewLeave) ?>;
		$(document).ready(function() {

			EnableAutoComplete($("#Add_Employee_Name"));
			var Color = ["orange","red","green","blue","gray"];








			var leave_id ;
			window.current_Employee;
			window.Events = [];
			console.log(CurrentLeave);

			$('#AssignLeave_Start_Time,#AssignLeave_End_Time').timepicker({
				showMeridian:true,
				maxHours:60,
				minuteStep:30
			})

			$("#AssignLeave_From_Date,#AssignLeave_To_Date").datepicker({autoclose:true}).on("changeDate",function(e){
				$(this).keyup();
			})

			$("body").on("click",".fc-content",function(){

				leave_id = $(this).attr("leave_id"); 
				Status_leave = $(this).attr("leave_status")

				console.log(leave_id)
				console.log(Status_leave)

				if( Status_leave == 1 || Status_leave == 4 ){
					var status = '';
					if(Status_leave == 1){

						status = 'Declined';
					}
					else{
						status = 'Deleted';
					}

					$("#ErrorModal").modal('show')
					$("#ErrorModal").find('.Status').empty().append(status)



				}
				else{





					$.ajax({
						url:"Views/HRM/calendarmaterial.php?GetLeaveID="+leave_id,
						dataType:"json",
						complete:function(v,vv){

							if(vv == "success"){
								if( v.responseJSON.length > 0){  
									var Content = v.responseJSON[0];
									console.log(Content)
									var status = Content['LeaveRequest_Status'];
									$("#EditLeave").modal("show")
									$("#EditLeave").on("shown.bs.modal",function(){

										$(".Edit > span").removeClass('selected')

										$("#Employee_Name").val(Content['Employee_Name'])
										$("#Title").val(Content['AssignLeave_Reason'])
										$("#EditAssignLeave_From_Date").val(Content['AssignLeave_From_Date'])
										$("#EditAssignLeave_To_Date").val(Content['AssignLeave_To_Date'])
										$("#EditAssignLeave_Start_Time").val(Content['AssignLeave_Start_Time'])
										$("#EditAssignLeave_End_Time").val(Content['AssignLeave_End_Time'])

										$(".Edit > span.bgm-"+Color[Content['LeaveRequest_Status']]).addClass('selected')



									})
								}
							}
						}
					})
				}
				EnableAutoComplete($("#Employee_Name"));





			})












			var date = new Date();
			var d = date.getDate();
			var m = date.getMonth();
			var y = date.getFullYear();

			var cId = $('#calendar'); //Change the name if you want. I'm also using thsi add button for more actions


			for (var x = 0; x < CurrentLeave.length; x++) {
				var CA = CurrentLeave[x];

//				if (CA["LeaveRequest_Status"] != 4) { //not deleted	

					Events.push({
						title: CA["AssignLeave_Reason"],
						status:CA["LeaveRequest_Status"],
						start: CA["AssignLeave_From_Date"] ,
						end: CA["AssignLeave_To_Date"],
						StartTime: CA["AssignLeave_Start_Time"],
						id: CA["Leave_ID"],
						Employee_ID:CA["Employee_ID"],
						Employee_Name:CA["Employee_Name"],
						className: 'bgm-'+Color[CA["LeaveRequest_Status"]]

					})


//				}
			}
			//Generate the Calendar
			cId.fullCalendar({
				header: {
					right: '',
					center: 'prev, title, next',
					left: ''
				},

				theme: true, //Do not remove this as it ruin the design
				selectable: true,
				selectHelper: true,
				editable: true,

				//Add Events
				events:Events,
				
				//On Day Select
				select: function(start, end, allDay) {
					$('#addNew-event').modal('show');   
					$('#addNew-event input:text').val('');
					$('#getStart').val(start);
					$('#getEnd').val(end);
				}
			});


			//Create and ddd Action button with dropdown in Calendar header. 
			var actionMenu = '<ul class="actions actions-alt" id="fc-actions">' +
				'<li class="dropdown">' +
				'<a href="" data-toggle="dropdown"><i class="zmdi zmdi-more-vert"></i></a>' +
				'<ul class="dropdown-menu dropdown-menu-right">' +
				'<li class="active">' +
				'<a data-view="month" href="">'+MonthViewLang+'</a>' +
				'</li>' +
				'<li>' +
				'<a data-view="basicWeek" href="">'+WeekViewLang+'</a>' +
				'</li>' +
				'<li>' +
				'<a data-view="agendaWeek" href="">'+AgendaWeekViewLang+'</a>' +
				'</li>' +
				'<li>' +
				'<a data-view="basicDay" href="">'+DayViewLang+'</a>' +
				'</li>' +
				'<li>' +
				'<a data-view="agendaDay" href="">'+AgendaDayViewLang+'</a>' +
				'</li>' +
				'</ul>' +
				'</div>' +
				'</li>';


			cId.find('.fc-toolbar').append(actionMenu);

			//Event Tag Selector
			(function(){
				$('body').on('click', '.event-tag > span', function(){
					$('.event-tag > span').removeClass('selected');
					$(this).addClass('selected');
				});
			})();

			//Add new Event
			$('body').on('click', '#addEvent', function(){


				$("#AssignLeaveValidationAlert").remove();
				var AlertBox = $('<div id="AssignLeaveValidationAlert" class="WizardValidationAlert alert"></div>');
				AlertBox.insertAfter($("#addNew-event").find(".modal-dialog .modal-header").find("h4"))	


				$("#AssignLeaveIsBusy").remove();
				$("#addNew-event").append('<div id="AssignLeaveIsBusy" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:9999;opacity:0"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>');
				$("#AssignLeaveIsBusy").animate({opacity:1});





				var eventName = $('#eventName').val(),
					tagColor = $('.event-tag > span.selected').attr('data-tag');






				if (eventName != '' &&  $("#Add_Employee_Name").attr('data-value') != '0') {

					var Data = {

						Employee_ID                    :  $("#Add_Employee_Name").attr("data-value"),
						AssignLeave_Reason             : eventName,
						AssignLeave_From_Date          : $("#AssignLeave_From_Date").val(),
						AssignLeave_To_Date            : $("#AssignLeave_To_Date").val(),
						AssignLeave_Start_Time         : $("#AssignLeave_Start_Time").val(),
						AssignLeave_End_Time           : $("#AssignLeave_End_Time").val(),
						LeaveRequest_Status			   : $('.event-tag > span.selected').attr('value')
					}

					$.ajax({

						url:"Views/HRM/calendarmaterial.php",
						method:"POST",
						data:Data,
						complete:function(v1,v2){
							console.log(Data)

							if(v2 == 'success'){

								$("#AssignLeaveIsBusy").remove();
								$("#AssignLeaveValidationAlert").addClass("alert-success").empty().html(Submitted_Successfully);
								setTimeout(function(){
									$("#addNew-event").modal('hide')
									$("#AssignLeaveValidationAlert").hide()
								},5000)

							}
							else {
								var Row = $.parseJSON(v1.responseText);
								var name ='';
								for(var i=0;i<Row.length;i++){
									name += Row[i]['Employee_Name']+', '
								}
								$("#ModalToAssignByForce").find(".Name").append(name)
								$("#AssignLeaveValidationAlert").addClass("alert-danger").empty().html(Failed_Submit);
								$("#ModalToAssignByForce").modal('show');
							}
							$("#AssignLeaveIsBusy").remove();

						}

					})






					//Render Event
					$('#calendar').fullCalendar('renderEvent',{
						title: eventName,
						id :d,
						start: $('#getStart').val(),
						end:  $('#getEnd').val(),
						allDay: $("#AssignLeave_Start_Time").val() == "" ? true : false,
						className: tagColor

					},true ); //Stick the event

					$('#addNew-event form')[0].reset()
					//					$('#addNew-event').modal('hide');
				}

				else {
					$("#AssignLeaveIsBusy").remove();
					$("#AssignLeaveValidationAlert").addClass("alert-danger").empty().html(Failed_Submit);
					$('#eventName,#Add_Employee_Name').closest('.form-group').addClass('has-error');
				}
			});   

			//Calendar views
			$('body').on('click', '#fc-actions [data-view]', function(e){
				e.preventDefault();
				var dataView = $(this).attr('data-view');

				$('#fc-actions li').removeClass('active');
				$(this).parent().addClass('active');
				cId.fullCalendar('changeView', dataView);  
			});



		});       


		function EnableAutoComplete(who){
			if(!who.hasClass("AutoAdded")){
				who.autocomplete({
					source: 'xhr/ajaxEmployee.php?' ,
					minLength: 2,
					select: function(event, ui){
						var Name = $(this);
						Name.val(ui.item.Employee_Name)

						current_Employee = ui.item.Employee_ID;

						$("#Add_Employee_Name").attr("data-value",current_Employee)
						return false;

					}

				}).autocomplete("instance")._resizeMenu = function( ul, items ) {
					this.menu.element.outerWidth((who.width()) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
				}
				who.autocomplete("instance")._renderItem = function(ul,item){
					var MyType =  item.Employee_Name;
					return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>"+MyType+"</td></tr></table>").appendTo(ul)
				}
				who.addClass("AutoAdded")
			}
			$(document).keydown(function(e){
				if(e.which == 8 && e.target.tagName.toLowerCase() != "input"){
					e.preventDefault()
				}
			})
		}
		$("#ConfirmAssign").on("click",function(){
			var AlertBox = $('<div id="AssignLeaveValidation" class="WizardValidationAlert alert"></div>');
			AlertBox.insertAfter($("#ModalToAssignByForce").find(".modal-dialog .modal-header").find("h5"))
			var Data = {
				Employee_ID                    : $("#Add_Employee_Name").attr('data-value'),
				AssignLeave_Reason             : $("#AssignLeave_Reason_ID").val(),
				AssignLeave_From_Date          : $("#AssignLeave_From_Date").val(),
				AssignLeave_To_Date            : $("#AssignLeave_To_Date").val(),
				AssignLeave_Start_Time         : $("#AssignLeave_Start_Time").val(),
				AssignLeave_End_Time           : $("#AssignLeave_End_Time").val()
			} 
			$.ajax({
				url:"Views/HRM/calendarmaterial.php",
				method:"POST",
				data:Data,
				complete:function(v1,v2){
					if(v2 == "success"){
						$("#AssignLeaveValidation").addClass("alert-success").empty().html(Submitted_Successfully);
						setTimeout(function(){
							$("#AssignLeave").modal('hide')
							$("#ModalToAssignByForce").modal('hide')
							$("#AssignLeaveValidation,#AssignLeaveValidationAlert").hide()
						},1000)
					}else{
						$("#AssignLeaveValidation").addClass("alert-danger").empty().html(Failed_Submit);
					}
				}
			})
		})


	</script>
</body>


</html>