<section class="container-fluid" style="padding-bottom: 2rem;">
	<div class="row">
        <div class="col-md-6">
            <div class="card bg-light-transparent" style="margin-bottom: 2rem;">
                <div class="card-header bg-white">
                    <div class="float-left">
                        <h5 class="card-title">Calendar</h5>
                    </div>
                </div>
                <div class="card-body">
                    <div class="card bg-white no-shadow" style="height: 58rem;">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-12">
                                    <div id="calendar"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
			<div class="card bg-light-transparent" style="margin-bottom: 2rem;">
				<div class="card-header bg-white">
					<h5 class="card-title">Upcoming training request</h5>
				</div>
				<div class="card-body">
					<div class="card bg-white no-shadow">
						<div class="card-body">
							<div class="row">
								<table id="table_training_request" class="table table-hover mx-1">
									<thead>
										<?php if(!empty($upcoming_request)) foreach($upcoming_request as $upcoming){ ?>
											<tr>
												<th data-trigger="hover" data-tooltip="tooltip" title="<?php echo $upcoming['business_entity']; ?>" width="60%" style="border: none; font-weight: normal;"><?php echo $upcoming['topic']; ?></th>
												<th class="text-center" width="40%" style="border: none; font-weight: normal;"><?php echo date('d-m-Y',strtotime($upcoming['proposed_date'])); ?></th>
											</tr>
										<?php } ?>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<section class="container" style="padding-bottom: 2rem;">
	<div class="row">
		<div class="col-md-12">
			<div class="tab-content" id="tabContent">
				<div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
					<div class="card bg-light-transparent">
						<div class="card-header bg-light">
							<h4 class="card-title float-left"><?php echo (empty($ID))?'New ':'Edit '; ?>Training Request Form</h4>
						</div>
						<form action="<?php echo (!empty($ID))?base_url('hr/serviceform/training_request_edit'):base_url('hr/serviceform/training_request_save'); ?>" id="requestForm" enctype="multipart/form-data" class="form" method="POST" onsubmit="return confirm('Confirm to <?php echo (!empty($ID))?'update this form':'submit this form'; ?>?')">
							

							<input type="text" class="form-control" name="trainingRequestID" id="trainingRequestID" value="<?php echo ($ID)?$ID:''; ?>" hidden>
							<input type="text" class="form-control" name="upload_id" id="upload_id" value="<?php echo ($ID)?$trainingRequestDetails[0]['uploadID']:'';?>" hidden>
							

							<div class="card-body">
								<div class="card no-shadow">
									<div class="card-body">
										<div class="row">
											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label>Name</label>
													<input type="text" class="form-control" name="reqName" id="reqName" value="<?php echo ($ID)?$trainingRequestDetails[0]['requestor']:$_SESSION['user']['name']; ?>" readonly>
													<input type="text" class="form-control" name="reqNameID" id="reqNameID" value="<?php echo ($ID)?$trainingRequestDetails[0]['createdBY']:$_SESSION['user']['id']; ?>" readonly hidden>
												</div>
											</div>
											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label>Email Address</label>
													<input type="text" class="form-control" name="email" id="email" value="<?php echo ($ID)?$trainingRequestDetails[0]['email']:$_SESSION['user']['email']; ?>" readonly>
												</div>
											</div>
											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label for="department">Department</label>
													<input type="text" class="form-control" name="department" id="department" value="<?php echo ($ID)?$trainingRequestDetails[0]['dept_name'].' ['.$trainingRequestDetails[0]['branchName'].']':$_SESSION['user']['department_name'].' ['.$_SESSION['user']['branch_name'].']'; ?>" readonly>
													<input type="text" class="form-control" name="department_id" id="department_id" value="<?php echo ($ID)?$trainingRequestDetails[0]['department_id']:$_SESSION['user']['department_id']; ?>" readonly hidden>
												</div>
											</div>
											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label for="datereq">Date Requested</label>
													<input type="text" class="form-control" name="datereq" id="datereq" value="<?php echo ($ID)?date('d-m-Y',strtotime($trainingRequestDetails[0]['createdTS'])):date("d-m-Y"); ?>" readonly>
												</div>
											</div>
										</div>

										<div class="form-row">
											<div class="col-12">
												<div class="form-group">
													<div class="row">
														<div class="col-12 col-sm-6">
															<div class="form-group">
																<label for="department">Business Entity</label>
																<select  class="form-control" name="business_entity" id="business_entity">
																	<option value="" disabled selected>-- Please Select --</option>
																	<?php if(!empty($rsBusiness_entities)) foreach($rsBusiness_entities as $row){ ?>
																		<option value="<?php echo $row['id']; ?>" <?php echo ($ID && $trainingRequestDetails[0]['business_entity_id'] == $row['id'])?'selected':''; ?>><?php echo $row['name']; ?></option>
																	<?php } ?>
																</select>											
															</div>
														</div>

														<div class="col-12 col-sm-6">
															<div class="form-group">
																<label for="title">Training Title/Topic</label>
																<input type="text" class="form-control" name="topic" id="topic" value="<?php echo ($ID)?$trainingRequestDetails[0]['topic']:''; ?>" required>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>

										<div class="form-row">
											<div class="col-12">
												<div class="form-group">
													<div class="row">
														<div class="col-12 col-sm-6">
															<div class="form-group">
																<label for="venue">Venue</label>
																<input type="text" class="form-control" name="venue" id="venue" value="<?php echo ($ID)?$trainingRequestDetails[0]['venue']:''; ?>" required>
															</div>
														</div>
														<div class="col-12 col-sm-6">
															<div class="form-group">
																<label for="org">Organizer</label>
																<input type="text" class="form-control" name="organizer" id="organizer" value="<?php echo ($ID)?$trainingRequestDetails[0]['organizer']:''; ?>" required>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>

										<div class="form-row">
											<div class="col-12">
												<div class="form-group">
													<div class="row">
														<div class="col-12 col-md-2">
															<div class="form-group">
																<label for="date_from">Date From</label>
																<input type="text" class="form-control datepicker" name="date_from" id="date_from" value="<?php echo ($ID)?date('d-m-Y',strtotime($trainingRequestDetails[0]['date_from'])):''; ?>" required onchange="calculate_request_hour()">
															</div>	
														</div>
														<div class="col-12 col-md-2">
															<div class="form-group">
																<label for="date_to">Date To</label>
																<input type="text" class="form-control datepicker" name="date_to" id="date_to" value="<?php echo ($ID)?date('d-m-Y',strtotime($trainingRequestDetails[0]['date_to'])):''; ?>" required onchange="proposed_sharing_date_control()">
															</div>	
														</div>
														<div class="col-12 col-md-2">
															<div class="form-group">
																<label for="cost">Cost</label>
																<input type="text" class="form-control" name="cost" id="cost" value="<?php echo ($ID)?$trainingRequestDetails[0]['cost']:''; ?>" required>
															</div>	
														</div>
														<div class="col-12 col-md-6">
															<div class="form-group">
																<label for="participant">Participant</label>
																<select class="form-control selectric" id="participant" name="participant[]" multiple>
																	<option value="-1">-- Please Select --</option>
																	<?php if($user_list) foreach($user_list as $key => $row){ ?>
																		<option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
																	<?php } ?>
																</select>
															</div>	
														</div>
													</div>
												</div>
											</div>
										</div>

										<div class="form-row">
											<div class="col-12">
												<div class="form-group">
													<div class="row">
														<div class="col-12 col-md-6">
															<div class="form-group">
																<label for="date">Proposed Sharing Session Date <i class="text-danger" style="font-size: 15px;">*Must not exceed 1 month after training event</i></label>
																<input type="text" class="form-control" name="proposed_date" id="proposed_date" value="<?php echo ($ID)?date('d-m-Y',strtotime($trainingRequestDetails[0]['proposed_date'])):''; ?>" required>
															</div>
														</div>

														<div class="col-12 col-md-6">
															<div class="form-group">
																<label>For training request and registration , kindly attach :- </label>
																<br>
																<small for="file" class="text-danger">
																	&emsp;a) Staff Development Plan <br> 
																	&emsp;b) Training brochure & information & registration form
																</small>
																<br><br>
																<input type="file" id="picture_upload" name="picture_upload" value="" aria-describedby="attachmentHelp">
																<br><br>	

																<div class="form-group form-inline <?php echo ($ID)?'':'d-none'; ?>">
																	<label for="curr_picture_upload" style="padding-right: 12px;">Current picture :</label>
																	<input class="form-control" style="width: 76%;" type="text" name="curr_picture_upload" id="curr_picture_upload" value="<?php echo ($ID)?$trainingRequestDetails[0]['photo_title']:''; ?>" aria-describedby="attachmentHelp" readonly>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>

										<?php if($ID){ ?>
											<?php if($_SESSION['user']['id'] == $trainingRequestDetails[0]['createdBY']){ ?>	
												<div class="form-row" <?php echo (isset($mode) && ($mode == 'view'))?'style="display: none;"':''; ?>>
													<div class="col-12" style="padding-top: 2rem;">
														<div class="float-left <?php echo ($ID)?'d-none':''; ?>">
															<table>
																<tbody>
																	<tr>
																		<td class="text-center">
																			<label class="switch" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Send me a copy of this form">
																				<input type="checkbox" name="send_email_checkbox">
																				<span class="slider round"></span>
																			</label>
																		</td>
																		<td class="p-3 py-1"><b><h6 style="">Send me a copy of this form</h6></b></td>
																	</tr>
																</tbody>
															</table>
														</div> 
														<div class="float-right">
															<a class="btn btn-light" href="<?php echo base_url('hr/serviceform/qr_code_list/'); ?>">Cancel</a>
															<button type="submit" id="submitBtn" class="btn btn-primary text-right">Submit</button>
														</div> 
													</div>
												</div>
											<?php } ?>
										<?php }else{ ?>
											<div class="form-row" <?php echo (isset($mode) && ($mode == 'view'))?'style="display: none;"':''; ?>>
												<div class="col-12" style="padding-top: 2rem;">
													<div class="float-left <?php echo ($ID)?'d-none':''; ?>">
														<table>
															<tbody>
																<tr>
																	<td class="text-center">
																		<label class="switch" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Send me a copy of this form">
																			<input type="checkbox" name="send_email_checkbox">
																			<span class="slider round"></span>
																		</label>
																	</td>
																	<td class="p-3 py-1"><b><h6 style="">Send me a copy of this form</h6></b></td>
																</tr>
															</tbody>
														</table>
													</div> 
													<div class="float-right">
														<a class="btn btn-light" href="<?php echo base_url('hr/serviceform/qr_code_list/'); ?>">Cancel</a>
														<button type="submit" id="submitBtn" class="btn btn-primary text-right">Submit</button>
													</div> 
												</div>
											</div>
										<?php } ?>
									</div>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<?php echo (!empty($approval))?$approval:''; ?>

<style type="text/css">
	.tooltipevent
	{
		width:auto;
		height:auto;
		background:rgba(0,0,0,0.75);
		position:absolute;
		color: #fff;
		z-index:10001;
		padding:10px 10px 10px 10px ;  
		line-height: 200%;
	}
</style>

<script type="text/javascript">
	$(document).ready(function(){
		$('#table_training_request').DataTable().destroy();
		var fc_event= '';
		var resource = <?php echo $resource;?>;

		var fullcalendar = $('#calendar').fullCalendar({ 
			themeSystem: 'bootstrap4',
			header: 
			{
				left: 'prev,next today',
				center: 'title',
				right: 'month,listMonth'
			},
			buttonText: {
				today: 'Today',
				month: 'Calendar',
				listMonth: 'List'
			},

            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            events: <?php echo $fc_event; ?>,
            eventMouseover: function (data, event, param, resource = <?php echo $resource;?>) {
            	var js_res = JSON.parse(JSON.stringify(resource));
                // console.log(js_res);
                var hover_item = js_res[data.id];
                var title = JSON.stringify(data.title);
                var start = moment(hover_item.proposed_date).format('DD-MM-YYYY');

                console.log(hover_item);

                tooltip = '<div class="tooltipevent"> Requester : '+hover_item.requestor+'['+hover_item.staff_id+']'+'<br/> Email : '+hover_item.email+'<br/> Department : '+hover_item.dept_name+'/'+hover_item.branchName+'<br/> Date : '+start+'<br/> Time : '+hover_item.time+'<br/> Business Entity : '+hover_item.business_entity+'</div>';

                // console.log(tooltip);
                $("body").append(tooltip);
                $(this).mouseover(function (e) {
                	$(this).css('z-index', 10000);
                	$('.tooltipevent').fadeIn('500');
                	$('.tooltipevent').fadeTo('10', 1.9);
                }).mousemove(function (e) {
                	$('.tooltipevent').css('top', e.pageY + 10);
                	$('.tooltipevent').css('left', e.pageX + 20);
                });
            },

            eventMouseout: function(data, event) {
            	$(this).css('z-index', 8);
            	$('.tooltipevent').remove();
            },
        });

		fullcalendar.fullCalendar();

		if('<?php echo $ID; ?>' > 0) selected_participant('<?php echo $trainingRequestDetails[0]['participant_user_id']; ?>');
	});

	function confirmation() {
		confirm('Do you really want to submit the form?');
	}

	function selected_participant(participant_id)
	{
		var participant_id = participant_id.split(',');

		$('#participant').val(participant_id).selectric('refresh');
	}

	function proposed_sharing_date_control()
	{
		var training_date_to_ori = ($('#date_to').val()).split('-');
		if(training_date_to_ori.length == 3)
		{
			$("#proposed_date").datepicker("destroy");

			var training_date_to 		= training_date_to_ori[2]+'-'+training_date_to_ori[1]+'-'+training_date_to_ori[0];
			var training_date_to_year 	= moment(training_date_to).format('YYYY');
		    var training_date_to_month 	= moment(training_date_to).format('MM');
		    var training_date_to_day 	= moment(training_date_to).format('DD');

			var date 					= new Date();
		    var full_date 				= date.setFullYear(training_date_to_year,training_date_to_month-1,training_date_to_day);
		    var start_training_date_to	= moment(full_date).add(1,'weeks').format('DD-MM-YYYY');
		    var end_training_date_to    = moment(full_date).add(1,'months').subtract(1,'day').format('DD-MM-YYYY');

		    // contoh utk leave
		    // var balance_month 			= 12 - training_date_to_month;
			// var start_training_date_to	= moment(full_date).format('DD-MM-YYYY');
		    // var end_training_date_to    = moment(full_date).add(balance_month,'months').endOf('month').format('DD-MM-YYYY');

		    $( "#proposed_date" ).attr('required','required');
			$( "#proposed_date" ).removeAttr('disabled');
			$( "#proposed_date" ).css("cursor","text");

		    $( "#proposed_date" ).datepicker({
	            uiLibrary: 'bootstrap4',
	            format: 'dd-mm-yyyy',
	            autoclose: true,
	            changeMonth: true, 
	            changeYear: true,
	            startDate :start_training_date_to,
	            endDate:end_training_date_to
	        });
		}else{
			$( "#proposed_date" ).attr('disabled','disabled');
			$( "#proposed_date" ).removeAttr('required');
			$( "#proposed_date" ).css("cursor","not-allowed");
		}
	}

	function calculate_request_hour()
	{
		var date_from 		= $('#date_from').val();
		var server_date		= '<?php echo date("Y-m-d H:i"); ?>';

		if(date_from != '' && date_from != null)
		{
			$.ajax({
				url:'<?php echo base_url('hr/serviceform/change_date_format') ?>',
				data: {
					checkin_date : date_from,
					// checkin_time : checkin_time
				},
				type: 'post',
				dataType: 'json',
				success: (data) => {
					if(data.status == "success") {

						var date_request 	= moment(data.date_time); 
						var date_server 	= moment(server_date); 
						var date_diff		= Math.floor((date_request-date_server)/36e5);

						if(date_diff < 48)
						{
							iziToast.error({
								title: 'Error',
								message: "Training date less than 48 hours. Please update to new date. Thank you.",
							});

							$('#submitBtn').attr('disabled','disabled');
							$('#submitBtn').css("cursor","not-allowed");
						}else{
							iziToast.success({
								title: 'Success',
								message: "Success",
							});

							$('#submitBtn').removeAttr('disabled');
							$('#submitBtn').css("cursor","pointer");
						}
	                }
	          	}
	       	});
		}
	}
</script>