<!-- JUMBOTRON -->
<section class="container" style="padding-bottom: 2rem;">
	<div class="card bg-light-transparent">
		<div class="card-body">
			<div class="card no-shadow" style="padding-top: 3rem; padding-bottom: 3rem;">
				<div class="card-body">
					<div class="row">
						<div class="col-md-4 text-center align-self-center">
							<img class="image-responsive" src="<?php echo base_url($user['file_location'].$user['file_name']); ?>" style="max-height: 15rem; max-width: 15rem;">
						</div>
						<div class="col-md-8">
							<h3><?php echo $user['name'] ?></h3>
							<p><?php echo $user['position_name'] ?></p>
							<p>Department: <?php echo $user['department_name'] ?> (<?php echo $user['branch_name'] ?>)</p>
							<hr class="my-4">
                            <div class="row">
                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="">
                                        <div class="card-body">
                                            <h6 class="card-title">Total</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveTotal'])?$leave_info['leaveTotal']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="pending">
                                        <div class="card-body">
                                            <h6 class="card-title">Pending</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leavePending'])?$leave_info['leavePending']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="approved">
                                        <div class="card-body">
                                            <h6 class="card-title">Approved</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveApproved'])?$leave_info['leaveApproved']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="rejected">
                                        <div class="card-body">
                                            <h6 class="card-title">Rejected</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveRejected'])?$leave_info['leaveRejected']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="col">
                                    <div class="card text-white bg-dark leave-info-card" data-v="cancelled">
                                        <div class="card-body">
                                            <h6 class="card-title">Cancelled</h6>
                                            <p class="card-text float-right" style="font-size: 2rem;">
                                                <?php echo ($leave_info['leaveCancelled'])?$leave_info['leaveCancelled']:0; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- LIST OF LEAVE APPLICATION -->
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-light">
            <div class="float-left">
                <button onclick="openApplicationModal();" type="button" class="btn btn-outline-dark btn-sm"><i class="fa fa-plus"></i> New Application</button>
				<button onclick="goToLeaveDashboard('<?php echo base_url('hr/leave_v2'); ?>')" type="button" class="btn btn-outline-dark btn-sm"><i class="fas fa-columns"></i> Leave Dashboard</button>
				<button onclick="openAllocationModal();" type="button" class="btn btn-outline-dark btn-sm"><i class="fas fa-tools"></i> Leave Allocation</button>
<?php if ($this->logged_module['role'] != 'user') { ?>
		<a  href="<?php echo base_url('hr/leave/department/').$this->logged_user['department_id']; ?>" class="btn btn-outline-dark btn-sm" data-tooltip="tooltip"  data-trigger="hover" title="Go To My Department's Applications" style="margin-right: 3px;">My Dept</a><?php } ?>
                <a target="_blank" href="<?php echo base_url('hr/leave/application/'.$user['id'].'/'.$year.'/print'); ?>" class="btn btn-outline-dark btn-sm"><i class="fa fa-print"></i> Print</a>
                <!-- <button id="btnShowLeaveFilters" type="button" class="btn btn-outline-dark btn-sm" data-toggle="collapse" data-target="#collapseLeaveFilter"><i class="fas fa-filter"></i> Show Filters</button> -->
                &nbsp;&nbsp;&nbsp;<span style="vertical-align: middle;">Allowed Annual Leave for the current month, <?php echo $today->format('F, Y'); ?>: <b><?php echo number_format($prorate['allowed_leave'],1).' - '.number_format(($leave_info['leavePending'])?$leave_info['leavePending']:0,1); ?>(pending)</b> day(s)</span>
            </div>
            <div class="float-right">
                <button onclick="openSummaryModal();" type="button" class="btn btn-outline-dark btn-sm" data-tooltip="tooltip"  data-trigger="hover" title="Leave Summary"><i class="fa fa-info"></i></button>
            </div>
            <div class="col-sm-3 float-right">
                <div class="row">
                    <label class="col text-right" for="entitlementYear">Year: </label>
                    <select class="form-control col mr-3" id="entitlementYear">
                    <?php foreach($years as $year): ?>
                        <option <?php if($year['year'] == $curr_year) echo 'selected'; ?> value="<?php echo $year['year'] ?>"><?php echo $year['year'] ?></option>
                    <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
        <!--div class="collapse" id="collapseLeaveFilter">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card no-shadow">
                            <div class="card-body">
                                Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, sed. Veritatis fugiat quasi expedita accusantium inventore quo dolor magnam. Ex soluta itaque quibusdam illum veritatis earum odio porro corrupti enim.
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card no-shadow">
                            <div class="card-body">
                                Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae a, quae fugiat tempora animi ipsam? Vero distinctio et tenetur earum quod, rem, adipisci hic explicabo ipsam dolore nulla cumque magnam.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div-->
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="table_applications" class="table table-bordered table-striped table-hover">
                            <thead>
                                <th>No.</th>
                                <th>Status</th>
                                <th>Leave Type</th>
                                <th>Date</th>
                                <th>Day(s)</th>
                                <!-- <th>Period Start</th>
                                <th>Date End</th>
                                <th>Period End</th> -->
                                <th>Attachment</th>
                                <!-- <th>Date Applied</th> -->
                                <th></th>
                            </thead>
                            <tbody>
                                <?php if(isset($applications)): ?>
                                    <?php $i = 1; ?>
                                    <?php foreach($applications as $application): ?>
                                        <tr id="application-<?php echo $application['id']; ?>" data-leave="<?php echo htmlspecialchars(json_encode($application), ENT_QUOTES, 'UTF-8'); ?>">
                                            <td><?php echo $i++; ?></td>
                                            <td class="text-center">
                                                <?php if ($application['status'] == 1): ?>
                                                    <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-warning" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                <?php endif; ?>
                                                <?php if ($application['status'] == 2): ?>
                                                    <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-success" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                <?php endif; ?>
                                                <?php if ($application['status'] == 3): ?>
                                                    <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-danger" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                <?php endif; ?>
                                                <?php if ($application['status'] == 4): ?>
                                                    <a href="javascript:openApplicationModal(<?php echo $application['id']; ?>)" class="badge badge-secondary" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $application['leave_type']; ?></td>
                                            <td><?php echo date_format(date_create($application['date_from']),"d/m/Y").' - '.date_format(date_create($application['date_to']),"d/m/Y"); ?></td>
                                            <td><?php echo $application['days_applied']; ?></td>
                                            <!-- <td><?php echo $application['period_from']; ?></td>
                                            <td><?php echo date_format(date_create($application['date_to']),"d/m/Y (l)"); ?></td>
                                            <td><?php echo $application['period_to']; ?></td> -->
                                            <td class="text-center"><?php if ($application['file_name']): ?><a target="_blank" href="<?php echo base_url($application['file_location'].$application['file_name']); ?>"><i class='fas fa-file fa-2x'></i></a><?php endif; ?></td>
                                            <!-- <td><?php echo date_format(date_create($application['created_ts']),"d/m/Y"); ?></td> -->
                                            <td class="text-center">
                                                <button type="button" <?php if ($application['status'] != 1) echo "hidden" ?> class="btn btn-sm btn-danger" onclick="deleteApplication(<?php echo $application['id']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete Application"><i class="fas fa-trash"></i></button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- <section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-light">
            <div class="float-left">
                <button onclick="openRequestModal();" type="button" class="btn btn-outline-dark btn-sm" <?php echo ($curr_year < date('Y'))?'disabled':''; ?>><i class="fa fa-plus"></i> Request Allocation</button>
            </div>
        </div>
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="table_applications" class="table table-bordered table-striped table-hover">
                            <thead>
                                <th>No</th>
                                <th>Leave Type</th>
                                <th class="text-center">Status</th>
                                <th></th>
                            </thead>
                            <tbody>
                                <?php if ($requests): ?>
                                    <?php $i = 0; foreach($requests as $req): ?>
                                        <tr>
                                            <td><?php echo ++$i; ?></td>
                                            <td><?php echo $req['type']; ?></td>
                                            <td class="text-center">
                                                <?php if ($req['status'] == 1) {  ?>
                                                    <a href="#" class="badge badge-success">Approved</a>
                                                <?php } else { ?>
                                                    <a href="#" class="badge badge-secondary">Pending</a>
                                                <?php } ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($req['status'] == 0): ?>
                                                    <button type="button" class="btn btn-sm btn-danger" onclick="deleteRequest(<?php echo $req['id']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete Request"><i class="fas fa-trash"></i></button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section> -->

<!-- application MODALS -->
<div class="modal fade" id="applicationModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="application-modal-title">New Leave Application</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="applicationForm" class="form">
                <div class="modal-body">
                    <h6 class="mb-3" style="text-decoration: underline;">Leave Information</h6>
                    <div class="form-group" hidden>
                        <label for="applicationID">ID</label>
                        <input type="text" class="form-control" name="applicationID" id="applicationID" value="">
                    </div>
                    <div class="form-row">
                        <div class="col">
                            <div class="form-group">
                                <label for="dateFrom">From</label>
                                <input required data-parsley-error-message="Date is required." type="text" class="form-control leave_date" id="dateFrom" placeholder="From" onchange="checkDateFromYear()">
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select required data-parsley-error-message="Period is required." class="form-control" id="periodFrom">
                                    <option selected value="">Select Period</option>
                                    <?php foreach($leave_periods as $period): ?>
                                        <option value="<?php echo $period['id']; ?>"><?php echo $period['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <label for="dateTo">To</label>
                                <input required data-parsley-error-message="Date is required." type="text" class="form-control leave_date" id="dateTo" placeholder="To" >
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <label for="periodTo">Period</label>
                                <select required data-parsley-error-message="Period is required." class="form-control" id="periodTo">
                                    <option selected value="">Select Period</option>
                                    <?php foreach($leave_periods as $period): ?>
                                        <option value="<?php echo $period['id']; ?>"><?php echo $period['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="col">
                            <div class="form-group">
                                <label for="leaveType">Leave Type</label>
<?php if ($mode=='debug') { echo '<br>select leave type<br>'; var_dump($allocations); }?>                               
                                <select required data-parsley-error-message="Type is required." class="form-control" id="leaveType" onchange="checkExam();">
                                    <option selected value="">Select Type</option>
                                    <?php if(!empty($allocations)) foreach($allocations as $type): ?>
                                        <option value="<?php echo $type['type_id']; ?>" data-name="<?php echo $type['name']; ?>"><?php echo '['.$type['code'].'-'.$type['year']; ?>] <?php echo $type['name']; ?> (<?php echo number_format($type['balance_entitle'],1,'.',','); ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col"> 
                            <div class="form-group">
                                <label for="reliefPerson">Relief Person</label>
                                <select required data-parsley-error-message="Person is required." class="form-control" id="reliefPerson">
                                    <option selected value="">Select Person</option>
                                    <?php foreach($relief_persons as $person): ?>
                                        <option value="<?php echo $person['id']; ?>"><?php echo $person['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-row" id="examForm" style="display: none;">
                        <div class="col">
                            <div class="form-group">
                                <label for="examList">Exam List</label>                             
                                <select required data-parsley-error-message="Exam is required." class="form-control" id="examList">
                                    <option selected value="">Select Exam</option>
                                    <?php if(!empty($exam_list)) foreach($exam_list as $value): ?>
                                        <option value="<?php echo $value['id']; ?>" data-exam_date="<?php echo date("d-m-Y", strtotime($value['exam_date'])); ?>"><?php echo $value['programme']; ?> [<?php echo $value['paper_code']; ?> - <?php echo $value['title']; ?>] : <?php echo date("d M Y", strtotime($value['exam_date'])); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="leaveReason">Reason</label>
                        <textarea required data-parsley-error-message="Reason is required." class="form-control" id="leaveReason" placeholder="Enter reason"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="leaveAttachment">Attachment</label>
                        <input type="file" class="form-control-file" id="leaveAttachment">
                    </div>
                    <hr>
                    <h6 class="mb-3" style="text-decoration: underline;">Contact Information</h6>
                    <div class="form-row mb-3">
                        <div class="col">
                            <div class="form-group">
                                <label for="userAddress">Address</label>
                                <input required data-parsley-error-message="Address is required." type="text" class="form-control" id="userAddress" placeholder="Enter address">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="userContact">Contact No.</label>
                                <input required data-parsley-error-message="Contact No. is required." type="text" class="form-control" id="userContact" placeholder="Enter contact no.">
                            </div>
                        </div>
                    </div>
                    <div class="container" id="errorContainer" style="border: 1px solid red;">
                        <ol id="errorList" style="color: red;"></ol>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="btn-group float-right">
						<button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
						<button type="button" id="applicationModalSubmitBtn" onclick="createApplication();" class="btn btn-light">Save</button>
					</div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="allocationModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="allocation-modal-title">Leave Allocation</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="col">
                    <div class="form-group">
                        <label for="allocationTypeRequest">Leave Type</label>
                        <select required data-parsley-error-message="Type is required." class="form-control" id="allocationTypeRequest">
                            <option selected value="">Select Type</option>
                            <?php foreach($leave_types as $type): ?>
                                <option value="<?php echo $type['id']; ?>">[<?php echo $type['code']; ?>] <?php echo $type['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
           </div>
           <div class="modal-footer">
                <div class="btn-group float-right">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                    <button type="button" id="allocationModalSubmitBtn" onclick="createAllocation();" class="btn btn-light">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="summaryModal">
    <div class="modal-dialog"  style="max-width: 90%;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="summary-modal-title">Leave Summary</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
           <div class="modal-body">
                <div class="table-responsive">
                    <table id="table_allocations" class="table table-bordered table-striped table-hover">
                        <thead>
                            <th>Year</th>
                            <th>Leave Type</th> 
                            <th>Leave Allocated </th>
                            <th>Leave Taken</th>
                            <th>Balance</th>
							<th>Leave Expiry</th>
							<th>BF Available</th>							
                        </thead>
                        <tbody>
                            <?php /* if(isset($allocations)): ?>
                                <?php foreach($allocations as $allocation): ?>
                                    <tr>
                                        <td><?php echo $allocation['year']; ?></td>
                                        <td><?php echo $allocation['name']; ?></td>
                                        <td><?php echo $allocation['bring_forward_entitled']; ?></td>
                                        <td><?php echo $allocation['balance_entitled']; ?></td>
                                        <td><?php echo $allocation['leave_taken']; ?></td>
                                        <td><?php echo $allocation['bring_forward']; ?></td>
                                        <td><?php echo $allocation['leave_balance']; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; */?>
                        </tbody>
                    </table>
                </div>
           </div>
        </div>
    </div>
</div>
<script>
    /* *
     * PHP Array Variables to JSON
     */
    <?php
        $json_user        = json_encode($user);
        $json_allocations = json_encode($allocations);
        $json_prorate     = json_encode($prorate);
    ?>

    var user        = <?php echo $json_user ?>;
    var allocations = <?php echo $json_allocations ?>;
    var prorate     = <?php echo $json_prorate ?>;
	
	
//	console.log(allocations);
	
	
	
    var startDate = moment(['<?php echo $curr_year - 1; ?>']).startOf('year').format('DD-MM-YYYY');
    var endDate   = moment(['<?php echo $curr_year + 1; ?>']).endOf('year').format('DD-MM-YYYY');

    $(".leave-info-card").click(function(){
        $("#table_applications").DataTable().search($(this).attr('data-v')).draw();
    });

    $(function() {
        $( ".leave_date" ).datepicker({
            uiLibrary: 'bootstrap4',
            format: 'dd-mm-yyyy',
            autoclose: true,
            changeMonth: true, 
            changeYear: true,
            startDate :startDate,
            endDate: endDate
        }); 

        $('#entitlementYear').change(() => {
            var year = $(this).find(':selected').val();
            location.href = "<?php echo base_url('hr/leave_v2/application/'); ?>"+user.id+'/'+year;
        });
    });

    $('#collapseLeaveFilter').on('show.bs.collapse', function () {
        $('#btnShowLeaveFilters').addClass('active');
    })
    $('#collapseLeaveFilter').on('hide.bs.collapse', function () {
        $('#btnShowLeaveFilters').removeClass('active');
    })

/*    // function holidays() {
    //     $.ajax({
    //         url: 'https://www.googleapis.com/calendar/v3/calendars/en.malaysia%23holiday%40group.v.calendar.google.com/events?key=AIzaSyDpE2GWla6h5Rv_wH7lzI0MHHD0vr8O1L4?singleEvents=true?orderBy=startTime',
    //         type: 'GET',
    //         dataType: 'JSON',
    //         success: (data) => {
    //             console.log(data);
    //         }
    //     });
    // } */

    function checkExam() {
        var selectBox = document.getElementById("leaveType");
        var selectedValue = selectBox.options[selectBox.selectedIndex].value;
        if(selectedValue == 7){ //study leave
            document.getElementById("examForm").style.display="block";
            document.getElementById("examList").required = true;
        }else{
            document.getElementById("examForm").style.display="none";
            document.getElementById("examList").required = false;
        }
    }

    function openAllocationModal() {
		var year = $('#entitlementYear').find(':selected').val(); 
		$('#allocation-modal-title').html('');
		$('#allocation-modal-title').html('Leave Allocation For The Year :' + year);
		
		$.ajax({
            type: "POST",
            dataType: "json", 
            url: "<?php echo base_url(); ?>hr/leave_v2/AJAX_getSelfAllocation",
             data: {
                year : year,
            },
            success: (data) => {
                if ($.trim(data.status) == "success") {
					console.log(data.sql );
					console.log(  data.rs); 
                    // $.each(data.rs, function(i, v) {
                    // });
                }
            }
        });		
        $('#allocationModal').modal('show');
    }

    function createAllocationRequest() {
        toastConfirm("Are you sure you want to send this request?", () => {
            $.ajax({
                url: '<?php echo base_url('hr/leave/createRequest') ;?>',
                type: 'POST',
                data: {
                    user_id: <?php echo $user['id']; ?>,
                    type_id: $('#allocationTypeRequest').val(),
                    year: '<?php echo $curr_year;  ?>'
                },
                dataType: 'JSON',
                success: (data) => {
                    localStorage.setItem("status", data.status);
                    localStorage.setItem("msg", data.msg);

                    location.reload();
                }
            });
        });
    }
    
    function deleteRequest(id) {
        toastConfirm("Are you sure you want to delete this request?", function(){
			$.ajax({
				type: 'POST',
				url: '<?php echo base_url('hr/leave/deleteRequest'); ?>',
				data: {
					'id' : id
				},
				dataType: 'JSON',
				success: function(data) {
					if(data.status == 'Success') {
						localStorage.setItem("status",data.status);
						localStorage.setItem("msg",data.msg);

						location.reload();
					}
				}
			});
		});
    }

    function openApplicationModal(id) {
        $('#errorContainer').hide();

        if(id) {
            // Update: Load leave by id and populate form
            var data      = $('#application-'+id).data('leave');
            var dateFrom  = moment(data.date_from, "YYYY-MM-DD").format("DD-MM-YYYY");
            var dateTo    = moment(data.date_to, "YYYY-MM-DD").format("DD-MM-YYYY");

            $('#applicationID').val(data.id);
            $('#dateFrom').val(dateFrom);
            $('#periodFrom').val(data.period_from_id).trigger('change');
            $('#dateTo').val(dateTo);
            $('#periodTo').val(data.period_to_id).trigger('change');
            $('#leaveType').val(data.type_id).trigger('change');
            $('#reliefPerson').val(data.absent_relief_id).trigger('change');
            $('#leaveReason').val(data.reason);
            $('#userAddress').val(data.absent_address);
            $('#userContact').val(data.absent_contact);
            $('#examList').val(data.exam_id);

            (data.status == 1) ? $('#applicationForm :input').attr('disabled', false) : $('#applicationForm :input').attr('disabled', true);
            // $('#leaveAttachment').val();
            $('#application-modal-title').html('Update Leave Application');
            $('#applicationModalSubmitBtn').attr('onclick', 'updateApplication()');
        } else {
            // Create new: Clear form
            clearForm('#applicationForm');
        
            if (user.address) $('#userAddress').val(user.address);
            if (user.phone)   $('#userContact').val(user.phone);

            $('#application-modal-title').html('New Leave Application');
            $('#applicationModalSubmitBtn').attr('onclick', 'createApplication()');
        }

        $('#applicationModal').modal('show');
    }

    function openSummaryModal() { 
//        $('#summaryModal').modal('show');
//	    function viewLeaveSummary(user_id) {
//		var user_id = <?php echo $this->logged_user['id']; ?>;
		var user_id = <?php echo $user_id; ?>;
//        var year  = <?php echo $curr_year; ?>; // $('#entitlementYear').find(':selected').val();
        var staff = `<?php echo $user['name']; ?>`; // $('#staff-'+user_id).data('staff');
        
        $("#summary-modal-title").text("Leave Summary (" + staff + ")");

        $.ajax({
            url: "<?php echo base_url('hr/leave_v2/AJAX_getAllocation_currentYear'); ?>",
            // url: "<?php echo base_url('hr/leave/getLeaveSummary'); ?>",
            type: "POST",
            data: { 
                user_id: user_id,
//                year: year  
            },
            dataType: "JSON",
            success: (data) => {
console.log(data); 
                if(data.status.toLowerCase() == 'success') {
                    var allocations  = data.allocation;
                    // var applications = data.applications;
                    
                    var allocationTable  = $("#table_allocations").DataTable();
                    // var applicationTable = $("#table_applications").DataTable();
console.log(allocations) ;                   
                    allocationTable.clear();
                    // applicationTable.clear();

                    $.each(allocations, (i, v) => {
 console.log('ini nilai v'); console.log(v);
						let balance_brought_forward = 0;
						let balance_entitle = 0;
						if(v.balance_entitle != null) {
							balance_entitle = parseFloat(v.balance_entitle);
						}
						allocationTable.row.add([
                            v.year,
                            v.name,
                            v.leave_entitled,
                            v.leave_taken,
							balance_entitle.toFixed(1),
							v.expiry_date,
							"0.0"
                        ]);
                    })

                    allocationTable.draw();

                    $('#summaryModal').modal('show');
                } else {
                    alert('Allocation has not been setup or Current allocation has expired.');
					console.log(data.sql);
                }
            } 
        })
    }

    function getNumWorkDays(startDate, endDate) {
        var numWorkDays = 0;
        var currentDate = new Date(startDate);

        while (currentDate <= endDate) {
            // Skips Sunday and Saturday
            if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
                numWorkDays++;
            }

            currentDate.setDate(currentDate.getDate() + 1);
        }
        return numWorkDays;
    }

    function createApplication() {
        validateForm("#applicationForm", "Are you sure you want to submit this leave application?", async function() {
            // var start_time = new Date().getTime();

            await checkLeaveAvailability('new');

            // var check_date_time = new Date().getTime();
            // var check_date_duration =  check_date_time - start_time;

            // console.log(`Check Leave Availability function done in ${ check_date_duration / 1000 } seconds`);
            
            if ($('#errorList li').length > 0) {
                iziToast.error({
					position: 'bottomRight',
					title: "Application Error",
					message: $('#errorList li').length + " errors. Please fix to proceed."
				});
            } else {

                var fd = new FormData();
            
                fd.append("user_name", "<?php echo $user['name']; ?>");
                fd.append("leave_name", $('#leaveType').find(':selected').data('name'));
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                fd.append("date_from", $('#dateFrom').val());
                fd.append("period_from_id", $('#periodFrom').val());
                fd.append("date_to", $('#dateTo').val());
                fd.append("period_to_id", $('#periodTo').val());
                fd.append("type_id", $('#leaveType').val());
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());

                if($('#leaveType').val() == 7){ //study leave
                    if(moment($("#dateTo").val(), "DD-MM-YYYY") > moment($('#examList').find(':selected').data('exam_date'), "DD-MM-YYYY")){
                        $("#errorList").append("<li>"+"Your study leave application exceed exam date. Please check again."+"</li>");
                        $('#errorContainer').show();
                        return false;
                    }else{
                        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
                        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
                        var daysApply = getNumWorkDays(dateFrom, dateTo);

                        if(daysApply <= 5 ){
                            fd.append("exam_id", $('#examList').val());
                        }else{
                            $("#errorList").append("<li>"+"Only Five(5) consecutive working days per paper . Please check again."+"</li>");
                            $('#errorContainer').show();
                            return false;
                        }
                    }
                }

                if($('#leaveAttachment').prop('files').length > 0) {
                    var attachment = $('#leaveAttachment').prop('files')[0];
                    
                    fd.append("attachment", attachment);
                }

                // var ajax_start_time = new Date().getTime();

                $.ajax({
                    url: "<?php echo base_url('hr/leave/createApplication'); ?>",
                    type: "POST",
                    data: fd,
                    dataType: "JSON",
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);

                        // var ajax_end_time = new Date().getTime();
                        // var ajax_duration =  ajax_end_time - ajax_start_time;

                        // console.log(`AJAX function done in ${ ajax_duration / 1000 } seconds`);

                        // var end_time = new Date().getTime();
                        // var function_duration = end_time - start_time;

                        // console.log(`Leave Application done in ${ function_duration / 1000 } seconds`);

                        location.reload();
                    }
                })
            }
        });
    }

    function updateApplication() {
        validateForm("#applicationForm", "Are you sure you want to submit this leave application?", async function() {
            await checkLeaveAvailability();
            
            if ($('#errorList li').length > 0) {
                iziToast.error({
					position: 'bottomRight',
					title: "Application Error",
					message: $('#errorList li').length + " errors. Please fix to proceed."
				});
            } else {
                var fd = new FormData();
            
                fd.append("id", $('#applicationID').val());
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                fd.append("date_from", moment($('#dateFrom').val(), 'DD-MM-YYYY').format('YYYY-MM-DD'));
                fd.append("period_from_id", $('#periodFrom').val());
                fd.append("date_to", moment($('#dateTo').val(), 'DD-MM-YYYY').format('YYYY-MM-DD'));
                fd.append("period_to_id", $('#periodTo').val());
                fd.append("type_id", $('#leaveType').val());
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());

                if($('#leaveType').val() == 7){ //study leave
                    if(moment($("#dateTo").val(), "DD-MM-YYYY") > moment($('#examList').find(':selected').data('exam_date'), "DD-MM-YYYY")){
                        $("#errorList").append("<li>"+"Your study leave application exceed exam date. Please check again."+"</li>");
                        $('#errorContainer').show();
                        return false;
                    }else{
                        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
                        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
                        var daysApply = getNumWorkDays(dateFrom, dateTo);

                        if(daysApply <= 5 ){
                            fd.append("exam_id", $('#examList').val());
                        }else{
                            $("#errorList").append("<li>"+"Only Five(5) consecutive working days per paper . Please check again."+"</li>");
                            $('#errorContainer').show();
                            return false;
                        }
                    }
                }

                if($('#leaveAttachment').prop('files').length > 0) {
                    var attachment = $('#leaveAttachment').prop('files')[0];
                    
                    fd.append("attachment", attachment);
                }

                $.ajax({
                    url: "<?php echo base_url('hr/leave/updateApplication'); ?>",
                    type: "POST",
                    data: fd,
                    dataType: "JSON",
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        if(data.status == "Success") {
                            localStorage.setItem("status", data.status);
                			localStorage.setItem("msg", data.msg);

                			location.reload();
                        }
                    }
                })
            }
            
            
        });
    }

    function deleteApplication(id) {
        toastConfirm("Are you sure you want to delete this application?", function(){
			$.ajax({
				type: 'POST',
				url: '<?php echo base_url('hr/leave/deleteApplication'); ?>',
				data: {
					'id' : id
				},
				dataType: 'JSON',
				success: function(data) {
					if(data.status == 'Success') {
						localStorage.setItem("status",data.status);
						localStorage.setItem("msg",data.msg);

						location.reload();
					}
				}
			});
		});
    }

    // LEAVE APPLICATION RULES
    async function checkLeaveAvailability(mode) {
        await clearError();                                 // Clear error container
        await checkDate();                                  // Check if dateTo is before dateFrom
		console.log('overlap');
        if (mode == 'new') await checkOverlappingLeave();   // Check if applied leave is overlapping with previous approved leave
		console.log('after overlap');
        var type_id  = + $('#leaveType').val();

        switch (type_id) {
            case 1:                       // ANNUAL LEAVE
//                console.log('check backdated');
				await checkBackdated();   // Check if leave applied is backdated
//				console.log('check 3 days');
                await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
				console.log('check balance');
                await checkBalance();     // Check leave balance by leave type
				console.log('check prorate');
                await checkProRate();     // Check proRate
                break;
            
            case 2:                       // EMERGENCY LEAVE
                await checkBalance();     // Check leave balance by leave type
                await checkProRate();     // Check proRate
                break;
            
            case 3:                       // MEDICAL LEAVE
                await checkBalance();     // Check leave balance by leave type
                await checkAttachment();  // Check if attachment is included

            case 4:                       // UNPAID LEAVE
                // await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
                break;

            default:                      // OTHERS
                // await check3DaysBefore(); // Check if application date is 3 days before actual applied leave date
                await checkBalance();     // Check leave balance by leave type
                return;
        }
    }

    function clearError() {
        $('#errorList').empty();
        $('#errorContainer').hide();
    }

    function checkDate() {
        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");

        if (dateTo.isBefore(dateFrom)) {
            $("#errorList").append("<li>"+"Your chosen end date is before the start date. Please check again."+"</li>");
            $('#errorContainer').show();
        }
    }

	async function checkOverlappingLeave() {
    	var startDate   = $("#dateFrom").val();
        var endDate     = $("#dateTo").val();
        var leavePeriod = $("#periodFrom").val();

        var postData = {
            'user_id': <?php echo $user['id']; ?>,
            'date_from' : startDate,
            'date_to' : endDate
        };
        
        await $.ajax({
            type: "POST",
            dataType: "json",
            url: "<?php echo base_url(); ?>hr/leave/getLeaveBetweenDate",
            data: postData,
            success: (data) => {
                if ($.trim(data.status) == "success") {
	      			$.each(data.leave_date, function(i, v) {
                        if(leavePeriod == 1 || v.leavePeriod == 1) {
                            $("#errorList").append("<li>"+"You have already applied "+v.leave_type+" for "+parseFloat(v.days_applied)+" day(s) from "+moment(v.date_from, "YYYY-MM-DD").format('LL')+" to "+moment(v.date_to, "YYYY-MM-DD").format('LL')+"."+"</li>");
                            $('#period').val(0);

                            $('#errorContainer').show();
                        } else {
                                // check if days apply included both morning and afternoon half day
                            if(leavePeriod == v.leavePeriod) {
                                $("#errorList").append("<li>"+"You have applied for leave during this period."+"</li>");
                                $('#period').val(0);

                                $('#errorContainer').show();
                            }
                        }
	      			});
                }
            }
        });
    }

    function checkBackdated() {
        var startDate = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var today = moment();

        if(startDate.isBefore(today, 'days')) {
            $("#errorList").append("<li>"+"Backdated leave application is not allowed for Annual Leave. Otherwise, apply for Emergency Leave."+"</li>");
            $('#errorContainer').show();
        }
    }

    function check3DaysBefore() {
		var startDate = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var today = moment().startOf('day');

        var diff = startDate.diff(today, 'days');

        if(diff < 3) {
            $("#errorList").append("<li>"+"Please apply 3 days before date of leave. Otherwise, apply for Emergency Leave."+"</li>");
            $('#errorContainer').show();
        }
    }
    
    function checkBalanceOld() {
        // todo: check by weekend
        var type_id  = $('#leaveType').val();

        var dateFrom  = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var dateTo    = moment($("#dateTo").val(), "DD-MM-YYYY");
        var daysApply = dateTo.diff(dateFrom, 'days');

        // if EL (type == 2), use AL (type == 1) allocation
        var filter = {
            'type_id' : (type_id == 2) ? 1 : type_id,
            'year' : dateTo.format('YYYY')
        }
		console.log('allocations' );
		console.log(allocations);
		
        allocation = allocations.filter((allocation) => {
			
            for (var key in filter) {
                if (allocation[key] === undefined || allocation[key] != filter[key]){
					return false;
				}
            }
            return true;
        });
		console.log('allocation');
		console.log(allocation);
		
        allocation = allocation[0];
        console.log(allocation);
		
        if (!allocation) {
            $("#errorList").append("<li>"+"Allocation for this leave type has not been setup for this user. Please contact Administrator for further enquiries."+"</li>");
            $('#errorContainer').show();
        }

        if (parseFloat(allocation.leave_balance) < daysApply) {
            $("#errorList").append("<li>"+"Your selected leave balance is less than applied number of days."+"</li>");
            $('#errorContainer').show();
        }
    }

//akmal 20191226 use ajax to check balance to solve cross year check balance problem 
    function checkBalance() {
        var dateFrom    = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var dateTo      = moment($("#dateTo").val(), "DD-MM-YYYY");
		var year 		= dateFrom.format('YYYY'); 
        var type_id  = $('#leaveType').val();
        var daysApply = dateTo.diff(dateFrom, 'days');
console.log('leave type ' + type_id);
console.log('Year ' + year);
        // if EL (type == 2), use AL (type == 1) allocation
        var filter = {
            'type_id' : (type_id == 2) ? 1 : type_id,
            'year' : dateTo.format('YYYY')
        }
		
        $.ajax({
            async: false,
            url: "<?php echo base_url(); ?>hr/leave/checkBalanceAJAX",
            type: "POST",
            data: {
                user_id : user.id,
				year	: year,
                date_from : $("#dateFrom").val(),
                date_to : $("#dateTo").val(),
				type_id  : type_id, //$('#leaveType').val(),
                daysApply: dateTo.diff(dateFrom, 'days'),
				period_from_id: $('#periodFrom').val(),
				period_to_id: $('#periodTo').val(),
            },
            dataType: "JSON",
            success: (data) => {
				console.log(data);
                if (data.mesg != "") {
                   $('#errorList').append("<li>"+"Allocation for this leave type has not been setup for this user. Please contact Administrator for further enquiries."+"</li>");
                   $('#errorContainer').show();
				   console.log('sql ' + data.sql);
                } else if (data.showErrorMsg!="") {
					$('#errorList').append(data.showErrorMsg);
					$('#errorContainer').show();
				} else if (data.balance < daysApply) {
                   $('#errorList').append("<li>"+"Insufficient Leave Balance. Your Leave Balance = "+data.balance+". Please contact Administrator for further enquiries."+"</li>");
				   console.log('sql ' + data.sql);
                   $('#errorContainer').show();
                }
            }
        })
    }
	
	function checkProRate() {
        var dateFrom    = moment($("#dateFrom").val(), "DD-MM-YYYY");
        var dateTo      = moment($("#dateTo").val(), "DD-MM-YYYY");
        // var daysApplied = dateTo.businessDiff(dateFrom, 'days') + 1;

        $.ajax({
            async: false,
            url: "<?php echo base_url(); ?>hr/leave/getProRateAJAX",
            type: "POST",
            data: {
                user_id : user.id,
                date_from : $("#dateFrom").val(),
                period_from_id: $('#periodFrom').val(),
                date_to : $("#dateTo").val(),
                period_to_id: $('#periodTo').val()
            },
            dataType: "JSON",
            success: (data) => {
                if (data.status == "success") {
                    console.log(data);
                    var prorate = data.prorate;
                    if (data.days_applied > prorate.allowed_leave) {
                        $('#errorList').append("<li>"+"Based on our leave policy, you are only allowed to take "+prorate.allowed_leave+" day(s) of annual leave this month. If you wish to take additional leave, please apply for Unpaid Leave."+"</li>");
                        $('#errorContainer').show();
                    }
                }
            }
        })
    }

/*    // function checkProRate() {
    //     var dateFrom    = moment($("#dateFrom").val(), "DD-MM-YYYY");
    //     var dateTo      = moment($("#dateTo").val(), "DD-MM-YYYY");
    //     var dateFromEnd = moment(dateFrom).endOf('month');
    //     var monthFrom   = parseInt(dateFrom.format('M')); 
    //     var monthTo     = parseInt(dateTo.format('M')); 
    //     var year        = dateTo.year();
    //     var april       = moment("4-"+year, "M-YYYY");
    //     var daysApplied = dateTo.businessDiff(dateFrom, 'days');
    //     var allocation = allocations.filter((alloc) => alloc.type_id == 1 || alloc.type_id == 2);
        
    //     var AL = allocation[0];
    //     var EL = allocation[1];
        
    //     var entitledLeave = parseFloat(AL.leave_entitled);
    //     var leaveBalance  = parseFloat(AL.leave_balance);
    //     var bringForward  = parseFloat(AL.bring_forward);
    //     var entitledBF    = parseFloat(AL.bring_forward_entitled);
    //     var leaveTaken    = parseFloat(AL.leave_taken);
        
    //     if (user.position_id == 21 && user.contract_term < 12) {
    //         var proRatePerMonth = entitledLeave / user.contract_term;

    //         var commencementDate = moment(user.date_commencement);
    //         var months           = dateFrom.diff(commencementDate, 'months');
    //         var proRate          = proRatePerMonth * months;
    //     } else {
    //         var proRatePerMonth = entitledLeave / 12;
    //         var proRate         = proRatePerMonth * monthFrom;
    //     }

    //     var leaveToDate = 0;
    //     var leaveAppliedThisMonth = 0;

    //     var prevLeave;

    //     $.ajax({
    //         async: false,
    //         url: '<?php echo base_url(); ?>hr/leave/getLeaveUntilMonth',
    //         type: 'POST',
    //         data: {
    //             user_id: user.id,
    //             date_to: $("#dateTo").val()
    //         },
    //         dataType: 'JSON',
    //         success: (data) => {
    //             if ($.trim(data.status) == "success") {
    //                 prevLeave = data.leave_date;
    //             }
    //         }
    //     });

    //     if (prevLeave) {
    //         $.each(prevLeave, function(i, v){
    //             var start = moment(v.date_from, "DD-MM-YYYY");
    //             var startMonth = parseInt(start.format('M'));

    //             leaveToDate += parseFloat(v.days_applied);

    //             if(startMonth == monthFrom)
    //             {
    //                 leaveAppliedThisMonth += parseFloat(v.days_applied);
    //             }
    //         })
    //     }

    //     var takenBF = entitledBF - bringForward;
    //     var takenAL = leaveToDate - takenBF;

    //     var allowedBF = (monthFrom < 4 && monthTo < 4) ? bringForward : 0;
    //     var allowedAL = proRate - takenAL;
    //     var allowedLeave = allowedBF + allowedAL;
        
    //     if (allowedLeave < 0) allowedLeave = 0;

    //     if (daysApplied > allowedLeave) {
    //         $('#errorList').append("<li>"+"Based on our leave policy, you are only allowed to take "+allowedLeave+" day(s) of annual leave this month. If you wish to take additional leave, please apply for Unpaid Leave."+"</li>");
    //         $('#errorContainer').show();
    //     }
    // }    */

    function checkAttachment() {
        if ($('#leaveAttachment').get(0).files.length === 0) {
            $("#errorList").append("<li>"+"Attachment is required."+"</li>");
            $('#errorContainer').show();
        }
    }

    function clearForm(e) {
		$(e).parsley().reset();
        
		$(e).find("select").val('').trigger('change');
		$(e).find("input, textarea").val("");
	}
	
    function checkDateFromYear(){
        var currentYear = moment().year();
        var dateFrom    = $('#dateFrom').val()
        if(dateFrom != '' && dateFrom != null && dateFrom != undefined) 
        {
            change_leave_date_to("dateFrom","dateTo");

            var dateFromYear = moment(dateFrom,"DD-MM-YYYY").year();
            
            if(dateFromYear != currentYear)
            {
                load_allocation(dateFromYear);
            }

        }
	}

    function load_allocation(year)
    {
        $.ajax({
            type: "POST",
            dataType: "json", 
            url: "<?php echo base_url(); ?>hr/leave_v2/getLeaveBetweenDate",
            data: postData,
            success: (data) => {
                if ($.trim(data.status) == "success") {
                    // $.each(data.leave_date, function(i, v) {
                    // });
                }
            }
        });
    }
	
	function goToLeaveDashboard(url) {
		window.location.href = url;
    }
</script>
