<style>
    .profile{
        margin-top: 25px;
    }
    .profile h1{
        font-weight: normal;
        font-size: 20px;
        margin:10px 0 0 0;
    }
    .profile h2{
        font-size: 14px;
        font-weight: lighter;
        margin-top: 5px;
    }
</style>
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-body">
            <div class="row">
                <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>
</section>
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-light">
            <div class="float-left">
                <a target="_blank" href="<?php echo base_url('hr/leave/department/'.$department['id'].'/'.$year.'/print'); ?>" class="btn btn-outline-dark btn-sm"><i class="fa fa-print"></i> Print</a>
            </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="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="table_forms" class="table table-bordered table-striped table-hover">
                            <thead>
                                <th>No</th>
                                <th>Status</th>
                                <th>Name</th>
                                <th>Leave Type</th>
                                <th width="20%">Date [Days]</th>
                                <!-- <th>Period Start</th> -->
                                <!-- <th>Reason</th> -->
                                <th>Attachment</th>
                                <th>Date Applied</th>
                                <th>Action</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:viewApplication(<?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:viewApplication(<?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:viewApplication(<?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:viewApplication(<?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><a href="<?php echo base_url('hr/leave/application/'.$application['user_id']); ?>" data-tooltip="tooltip"  data-trigger="hover" title="View Staff"><?php echo $application['user_name']; ?></a></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").' ['.$application['days_applied'].']'; ?></td>
                                            <!-- <td><?php echo $application['period_from']; ?></td> -->
                                            <!-- <td><?php echo $application['reason']; ?></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">
                                                <?php if ($application['user_id'] != $this->logged_user['id']): ?>
                                                    <?php if ($application['status'] == 1): ?>
                                                        <div class="btn-group btn-group-sm">
                                                            <button type="button" onclick="leaveApproval(<?php echo $application['id']; ?>, 'approve');" class="btn btn-success" data-trigger="hover" data-tooltip="tooltip" title="Approve"><i class="far fa-thumbs-up"></i></button>
                                                            <button type="button" onclick="leaveApproval(<?php echo $application['id']; ?>, 'reject');" class="btn btn-danger" data-trigger="hover" data-tooltip="tooltip" title="Reject"><i class="far fa-thumbs-down"></i></button>
                                                            <!-- <button type="button" onclick="deleteApplication(<?php echo $application['id']; ?>);" class="btn btn-sm btn-danger" data-trigger="hover" data-tooltip="tooltip" title="Delete"><i class="fa fa-trash"></i></button> -->
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if ($application['status'] == 2): ?>
                                                        <button type="button" onclick="leaveApproval(<?php echo $application['id']; ?>, 'cancel');" class="btn btn-sm btn-secondary" data-trigger="hover" data-tooltip="tooltip" title="Cancel"><i class="fas fa-ban"></i></button>
                                                    <?php endif; ?>
                                                    <?php if ($application['status'] == 3): ?>
                                                        <button type="button" onclick="leaveApproval(<?php echo $application['id']; ?>, 'approve');" class="btn btn-sm btn-success" data-trigger="hover" data-tooltip="tooltip" title="Approve"><i class="far fa-thumbs-up"></i></button>
                                                    <?php endif; ?>
                                                    <?php if ($application['status'] == 4): ?>
                                                        <button type="button" onclick="leaveApproval(<?php echo $application['id']; ?>, 'approve');" class="btn btn-sm btn-success" data-trigger="hover" data-tooltip="tooltip" title="Approve"><i class="far fa-thumbs-up"></i></button>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </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">
            <h5 class="card-title">Staffs Leave Summary</h5>
        </div>
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="row pt-md">
                        <?php if (isset($staffs)): ?>
                        <?php foreach($staffs as $staff): ?>
                            <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 profile text-center" id="staff-<?php echo $staff['id']; ?>" data-staff="<?php echo htmlspecialchars(json_encode($staff), ENT_QUOTES, 'UTF-8'); ?>">
                                <div class="float-right">
                                    <button onclick="viewLeaveSummary(<?php echo $staff['id']; ?>);" type="button" class="btn btn-outline-dark btn-sm" data-tooltip="tooltip"  data-trigger="hover" title="View Leave Summary"><i class="fa fa-info"></i></button>
                                </div>
                                <div class="border border-secondary img-responsive rounded-circle m-auto" style=" background-image: url(<?php echo base_url($staff['file_location'].$staff['file_name']); ?>);background-position:50% 50%; background-size: cover; width: 6rem; height: 6rem;"></div>
                                <a href="<?php echo base_url("hr/leave/application/".$staff['id']);?>" data-tooltip="tooltip"  data-trigger="hover" title="View Staff"><h1><?php echo $staff['name']; ?></h1></a>
                                <h2><?php echo $staff['position_category']; ?> / <?php echo $staff['position_name']; ?></h2>
                            </div>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 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">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" readonly class="form-control" name="applicationID" id="applicationID" value="">
                    </div>
                    <div class="form-group">
                        <label for="leaveApplicant">Applicant Name</label>
                        <input type="text" readonly class="form-control" name="leaveApplicant" id="leaveApplicant" value="">
                    </div>
                    <div class="form-row">
                        <div class="col">
                            <div class="form-group">
                                <label for="leaveType">Leave Type</label>
                                <select disabled required data-parsley-error-message="Type is required." class="form-control" id="leaveType">
                                    <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 class="col">
                            <div class="form-group">
                                <label for="reliefPerson">Relief Person</label>
                                <select disabled 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 disabled required data-parsley-error-message="Exam is required." class="form-control" id="examList">
                                    <option selected value="">Select Exam</option>
                                    <?php if(!empty($exam_list_all)) foreach($exam_list_all 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-row">
                        <div class="col">
                            <div class="form-group">
                                <label for="dateFrom">From</label>
                                <input disabled required data-parsley-error-message="Date is required." type="text" class="form-control datepicker" id="dateFrom" placeholder="From">
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select disabled 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 disabled required data-parsley-error-message="Date is required." type="text" class="form-control datepicker" id="dateTo" placeholder="To">
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <label for="periodTo">Period</label>
                                <select disabled 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-group">
                        <label for="leaveReason">Reason</label>
                        <textarea disabled 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 disabled type="file" class="form-control" 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 disabled 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 disabled required data-parsley-error-message="Contact No. is required." type="text" class="form-control" id="userContact" placeholder="Enter contact no.">
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="summaryModal">
    <div class="modal-dialog modal-lg">
        <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_applications" class="table table-bordered table-striped table-hover">
                    <thead>
                        <th>Application Date</th>
                        <th>Leave Type</th>
                        <th>Date Start</th>
                        <th>Date End</th>
                        <th>Reason</th>
                        <th>Status</th>
                    </thead>
                    <tbody>
                    </tbody>
                    </table>
                </div>
           </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>Carried Forward</th>
                            <th>Entitled Leave</th>
                            <th>Leave Taken</th>
                            <th>Carried Forward Balance</th>
                            <th>Entitled Balance</th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
           </div>
        </div>
    </div>
</div>
<div class="modal fade" id="remarksModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="summary-modal-title">Leave Approval</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form class="form" id="remarksForm">
                    <div class="form-group" hidden>
                        <label for="remarks-application-id">ID</label>
                        <input type="text" class="form-control" id="remarks-application-id">
                    </div>
                    <div class="form-group" hidden>
                        <label for="approval-type">Approval Type</label>
                        <input type="text" class="form-control" id="approval-type">
                    </div>
                    <div class="form-group">
                        <label for="remarks">Remarks</label>
                        <input type="text" class="form-control" id="remarks">
                    </div>
                </form>
           </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="submitApproval();" class="btn btn-light">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

    function viewApplication(application_id) {
        var data = $('#application-'+application_id).data('leave');
        console.log(data);
        $('#leaveApplicant').val(data.user_name);
        $('#dateFrom').val(moment(data.date_from).format('DD-MM-YYYY'));
        $('#periodFrom').val(data.period_from_id).trigger('change');
        $('#dateTo').val(moment(data.date_to).format('DD-MM-YYYY'));
        $('#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);

        if(data.type_id == 7){ //study leave
            document.getElementById("examForm").style.display="block";
            $('#examList').val(data.exam_id);
        }else{
            document.getElementById("examForm").style.display="none";
            $('#examList').val(data.exam_id);
        }

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

    function viewLeaveSummary(user_id) {
        var year  = $('#entitlementYear').find(':selected').val();
        var staff = $('#staff-'+user_id).data('staff');
        
        $("#summary-modal-title").text("Leave Summary (" + staff.name + ")");

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

                    $.each(allocations, (i, v) => {
                        allocationTable.row.add([
                            v.year,
                            v.name,
                            v.bring_forward_entitled,
                            v.leave_entitled,
                            v.leave_taken,
                            v.bring_forward,
                            v.leave_balance
                        ]);
                    })

                    // $.each(applications, (i, v) => {
                    //     applicationTable.row.add([
                    //         v.date_apply,
                    //         v.leave_type,
                    //         v.date_from,
                    //         v.date_to,
                    //         v.reason,
                    //         v.leave_status
                    //     ]);
                    // })
                    
                    allocationTable.draw();
                    // applicationTable.draw();

                    $('#summaryModal').modal('show');
                } else {
                    alert('Allocation has not been setup.');
                }
            }
        })
    }

    function leaveApproval(id, func) {
        clearForm('#remarksForm');

        $('#remarks-application-id').val(id);
        $('#approval-type').val(func);
        $('#remarksModal').modal('show');
    }

    function submitApproval() {
        var msg;
        var url;

        var func = $('#approval-type').val();

        var id = $('#remarks-application-id').val();
        var remarks = $('#remarks').val();
//		console.log(id);

        if(func == 'approve') {
            msg = "Are you sure you want to approve this leave application?";
            url = "<?php echo base_url('hr/leave/approveApplication'); ?>";
        }

        if(func == 'reject') {
            msg = "Are you sure you want to reject this leave application?";
            url = "<?php echo base_url('hr/leave/rejectApplication'); ?>";
        }

        if(func == 'cancel') {
            msg = "Are you sure you want to cancel this leave application?";
            url = "<?php echo base_url('hr/leave/cancelApplication'); ?>";
        }

        toastConfirm(msg, () => {
            $('#remarksModal').modal('hide');

            $.ajax({
                url: url,
                type: "POST",
                data: { id, remarks },
                dataType: "JSON",
                success: (data) => {
                    if(data.status.toLowerCase() == '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();
					}
				}
			});
		});
    }
</script>