<!-- JUMBOTRON -->
<style>
    .text-divider {
        margin: 10px 0px 20px 0px;
        display: flex;
        align-items: center;
        --text-divider-gap: 1rem;
        font-size: smaller;
    }

    .text-divider::before,
    .text-divider::after {
        content: '';
        height: 1px;
        background-color: silver;
        flex-grow: 1;
    }

    .text-divider::before {
        margin-right: var(--text-divider-gap);
    }

    .text-divider::after {
        margin-left: var(--text-divider-gap);
    }

    .hl-row{
        /* background-color: grey;
        color: white; */
    }

    .chart-container {
        position: relative;
    }

    .chart-center {
        position:absolute;
        top: 59%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .text-center{
        text-align: center;
    }

</style>

<section class="mx-auto" style="width: 90%; padding-bottom: 2rem;">
    <div class="row">
        <!-- left col. application list -->
        <div class="col-7">
            <div class="card bg-light-transparent">
                <div class="card-body">
                    <div class="card no-shadow">
                        <div class="card-body">
                            <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <a class="nav-link active" id="pills-calendar-tab" data-toggle="pill" href="#pills-calendar" role="tab" aria-controls="pills-calendar" aria-selected="true">Calendar</a>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <a class="nav-link"  id="pills-list-tab" data-toggle="pill" href="#pills-list" role="tab" aria-controls="pills-list" aria-selected="false">List</a>
                                </li>
                            </ul>
                            <div class="tab-content" id="pills-tabContent">
                                <!-- calendar view -->
                                <div class="tab-pane fade show active" id="pills-calendar" role="tabpanel" aria-labelledby="pills-calendar-tab">
                                    <div class="container">
                                        <div class="row" style="margin-top: 20px;">
                                            <div class="col-12" >
                                                <div id="leaveContainer" class="mx-2 mt-2 mb-2 d-flex justify-content-center"></div>
                                                <div class="mt-2 d-flex justify-content-center">
                                                    <p class="text-danger" id="calendar-error"></p>
                                                </div>
                                                <div id="calendar"></div>
                                                <div id="legendContainer" class="mt-2 d-flex justify-content-center"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- history/list view -->
                                <div class="tab-pane fade" id="pills-list" role="tabpanel" aria-labelledby="pills-list-tab">
                                    <div class="table-responsive">
                                        <table id="table_applications" class="table table-bordered table-striped table-hover">
                                            <thead>
                                            <th style="width: 5%; text-align: center;">No.</th>
                                            <th style="width: 10%; text-align: center;">Status</th>
                                            <th style="width: 23%;">Leave Type</th>
                                            <th style="width: 27%;">Date</th>
                                            <th style="width: 10%; text-align: right;">Day(s)</th>
                                            <th style="width: 15%; text-align: center;">Attachment</th>
                                            <th style="width: 10%; text-align: center;"></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  style="width: 5%; text-align: center;"><?php echo $i++; ?></td>
                                                            <td style="width: 10%; text-align: center;">
                                                                <?php if ($application['status'] == 1): ?>
                                                                    <a class="badge" style="background-color:#FFD93D; color:#fff;"><?php echo $application['leave_status'] ?></a>
                                                                <?php endif; ?>
                                                                <?php if ($application['status'] == 2): ?>
                                                                    <a href="javascript:loadImmutableModal(<?php echo $application['id']; ?>)" class="badge" style="background-color:#6BCB77; color:#fff;" 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:loadImmutableModal(<?php echo $application['id']; ?>)" class="badge" style="background-color:#FF6B6B; color:#fff;" 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:loadImmutableModal(<?php echo $application['id']; ?>)" class="badge" style="background-color:#4D96FF; color:#fff;" data-trigger="hover" data-tooltip="tooltip" title="View Leave Detail"><?php echo $application['leave_status'] ?></a>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td style="width: 23%;"><?php echo $application['leave_type']; ?></td>
                                                            <td style="width: 27%;">
                                                                <?php
                                                                echo date_format(date_create($application['date_from']), "d/m/Y") .
                                                                ($application['period_from_id'] == 2 ? ' (AM)' : ($application['period_from_id'] == 3 ? ' (PM)' : '')) .
                                                                ' - ' .
                                                                date_format(date_create($application['date_to']), "d/m/Y") .
                                                                ($application['period_to_id'] == 2 ? ' (AM)' : ($application['period_to_id'] == 3 ? ' (PM)' : ''));
                                                                ?>
                                                            </td>
                                                            <td style="width: 10%; text-align: right;"><?php echo $application['days_applied']; ?></td>
                                                            <td style="width: 15%; text-align: 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 style="width: 10%; text-align: center;">
                                                                <button type="button" <?php if ($application['status'] != 1) echo "hidden" ?> class="btn btn-sm btn-danger" onclick="javascipt:deleteApplication({type: 'applications', status: 1, id: <?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>
                </div>
            </div>
        </div>            
        <!-- right col. summary, form -->           
        <div class="col-5">
            <!-- user info. summary -->
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-4 ">
                            <img id="avatar" onerror="javascript: loadDefaultAvatar()" class="img-fluid" src="<?php echo base_url($user['file_location'] . $user['file_name']); ?>" >
                        </div>
                        <div class="col-8">
                            <!-- user -->
                            <div style="position: relative;top: 50%;transform: translateY(-50%);">
                                <div style="background-color: #F7F5F2; padding: 15px; border-radius: 10px;">
                                    <h5>
                                        <?php echo strtoupper($user['name']); ?>
                                    </h5>
                                    <p style="padding: 0;margin: 0;">
                                        <?php echo $user['position_name'] ?>
                                    </p>
                                    <p style="padding: 0;margin: 0;">
                                        Department: <?php echo $user['department_name'] ?> (<?php echo $user['branch_name'] ?>)
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--summary-->
                    <div class="row mt-2">
                        <?php if(intval($leave_info['leaveTotal']) > 0){ ?>
                        <div class="col">
                            <div style="position: relative;top: 50%;transform: translateY(-50%);">
                                <!-- upcoming -->
                                <div style="background-color: #F7F5F2; padding: 15px; border-radius: 10px;">
                                    <h5>
                                        <?php echo 'UPCOMING LEAVE'; ?>
                                    </h5>
                                    <?php if($upcoming){ ?>
                                        <p style="padding: 0;margin: 0;">
                                            <?php echo ($upcoming['date_from'] == $upcoming['date_to'] ? 
                                                (date('d/m/Y', strtotime($upcoming['date_from']))) : 
                                                (date('d/m/Y', strtotime($upcoming['date_from'])) . ' - ' . date('d/m/Y', strtotime($upcoming['date_to'])))) 
                                                . ' <span class="text-muted">(' . $upcoming['status'] . ')</span>' ?>
                                        </p>
                                        <p style="padding: 0;margin: 0;">
                                            <a href="#">
                                                <?php echo $upcoming['name']; ?>
                                            </a>
                                        </p>
                                    <?php }else{ ?>
                                        <p style="padding: 0;margin: 0;">
                                            None
                                        </p>
                                    <?php } ?>
                                </div>
                                <!-- leave taken (allocated). taken / allowed -->
                                <div id="leave-taken-container" class="text-center mt-2">
                                </div> 
                            </div>
                        </div>
                      </div>
                      <div class="row mt-3">  
                        <div class="col">
                            <?php if(intval($leave_info['leaveTotal']) > 0){ ?>
                            <div class="chart-container">
                                <canvas id="h-chart" width="400" height="400"></canvas>
                                <div class="chart-center text-center">
                                    <p style="padding: 0; margin:0; font-size: x-large; font-weight: bold;">
                                        <?php echo $leave_info['leaveTotal']; ?>
                                    </p>
                                    <p style="padding: 0; margin:0; font-size: small;">Applications</p>
                                </div>
                            </div>
                            <?php } ?>
                        </div>
                        <?php } else { ?>
                        <div class="col-12 mt-2">
                            <div style="position: relative;top: 50%;transform: translateY(-50%);">
                                <!-- leave taken (allocated). taken / allowed -->
                                <div id="leave-taken-container" class="text-center mt-2">
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>                              
                </div>
            </div> 

            <!-- error -->
             <?php if (!$allocations || ($allocations && count(array_filter(array_column($allocations, 'alloc_complete'), function($v){ return $v == '0'; })) > 0)) { ?> 
                 <div class="row mt-3">
                    <div class="col-12">
                        <div class="card text-white bg-danger">
                            <div class="card-body">
                                <p style="margin:0; padding: 0; text-align: center;">One or more of your leave allocation is incomplete. Please contact HR for support</p>
                            </div>
                        </div>
                    </div>
                </div> 
            <?php } ?>    

            <!-- form -->
            <!-- application-card -->
            <div class="card mt-4" id="application-card" style="display: none;">
                <form id="applicationForm" class="form">
                <div class="modal-header">
                    <div class="float-left" style="margin-right: auto;">
                        <h5 class="modal-title" id="application-card-title"></h5>
                        <p style="padding: 0;margin: 0;" class="text-muted" id="application-type"></p>
                        <p style="padding: 0;margin: 0;font-size: small;" class="text-danger" id="application-error"></p>
                    </div>
                    <div class="float-right">
                        <button type="button" class="btn btn-secondary app-form" id="applicationCardCancelBtn">Cancel</button>
                        <button id="applicationCardSubmitBtn" type="button" class="btn btn-primary">Save</button>
                        <button class="btn btn-primary" type="button" disabled style="display: none;" id="loaderButton">
                            <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            Saving...
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- <form id="applicationForm" class="form"> -->
                        <input type="hidden" id="appId">
                        <input type="hidden" id="periodNdAdj">
                        <input type="hidden" id="deleteAtt" value="0">
                        <!-- dates -->
                        <div class="row">
                            <!-- single -->
                            <div class="col-10" id="singleContainer">
                                <div class="row">
                                    <div class="col-6">
                                        <div class="form-group">
                                            <label for="dateFrom">On</label>
                                            <input required type="text" class="form-control leave_date" id="dateOn" name="dateOn" readonly>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="form-group">
                                            <label for="periodFrom">Period</label>
                                            <select required class="form-control app-form" id="periodOn" name="periodOn">
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- range -->
                            <div class="col-10" id="rangeContainer">
                                <div class="row">
                                    <div class="col-3">
                                        <div class="form-group">
                                            <label for="dateFrom">From</label>
                                            <input required type="text" class="form-control leave_date" id="dateFrom" name="dateFrom" readonly>
                                        </div>
                                    </div>
                                    <div class="col-3">
                                        <div class="form-group">
                                            <label for="periodFrom">Period</label>
                                            <select required class="form-control app-form" id="periodFrom" name="periodFrom" onchange="adjustPeriod(event)">
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-3">
                                        <div class="form-group">
                                            <label for="dateTo">To</label>
                                            <input required type="text" class="form-control leave_date" id="dateTo" name="dateTo" readonly>
                                        </div>
                                    </div>
                                    <div class="col-3">
                                        <div class="form-group">
                                            <label for="periodTo">Period</label>
                                            <select required class="form-control app-form" id="periodTo" name="periodTo" onchange="adjustPeriod(event)">
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- duration -->
                            <div class="col-2">
                                <div class="form-group">
                                    <label for="leaveType">Duration</label>
                                    <input required type="text" class="form-control leave_date" id="duration" name="duration" readonly>
                                </div>
                            </div>
                        </div>
                        <!-- reason -->
                        <div class="form-group">
                            <label for="leaveReason">Reason</label>
                            <!-- <textarea class="form-control required-input app-form" id="leaveReason" placeholder="Enter reason"></textarea> -->
                            <input type="text" class="form-control required-input app-form" id="leaveReason" 
                                        placeholder="State your reason">
                        </div>
                        <!-- attachment and relief person -->
                        <div class="row">
                            <div class="col-md-6">
                                <label for="leaveAttachment">Attachment</label>
                                <div class="row">
                                    <div class="col" id="fileContainer">
                                        <div class="float-left" id="fileBox">
                                            <a target="_blank">
                                                <span style="font-size: 75px; "><i class="fas fa-file text-primary"></i></span>
                                            </a>
                                        </div>  
                                        <div class="float-left align-middle" style="margin-left: 10px; vertical-align: middle;">
                                            <button type="button" onclick="deleteAttachment()">
                                                <i class="fas fa-times text-primary"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col" id="attachmentContainer">
                                        <div class="row">
                                            <div class="col">
                                                <input type="file" class="form-control-file required-input app-form" id="leaveAttachment" accept="image/*, .pdf, .doc, .docx">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reliefPerson">Relief Person</label>
                                    <select class="form-control selectpicker required-input app-form" data-style="btn-light" data-live-search="true" id="reliefPerson">
                                    <!-- <select required class="form-control" id="reliefPerson"> -->
                                        <option value="">Select a person</option>
                                        <?php foreach ($relief_persons as $person): ?>
                                            <option value="<?php echo $person['id']; ?>"><?php echo strtoupper($person['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <!--exam-->
                        <div class="row" id="exam-container" style="display: none;">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="exam-name">Examination</label>
                                    <input disabled type="text" class="form-control" id="exam-name">
                                </div>
                            </div>
                        </div> 
                        <!-- contact -->
                        <div class="row ">
                            <div class="col-md-9">
                                <div class="form-group">
                                    <label for="userAddress">Address</label>
                                    <input type="text" class="form-control required-input app-form" id="userAddress" 
                                        placeholder="Enter address" value="<?php echo $user['address']; ?>" autocomplete="true">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="userContact">Contact No.</label>
                                    <input required type="text" class="form-control required-input app-form" id="userContact" 
                                        placeholder="Enter contact no." value="<?php echo $user['phone']; ?>" autocomplete="true">
                                </div>
                            </div>
                        </div> 
                    <!-- </form>                         -->
                </div>
                </form> 
            </div>
        </div>
    </div>


</section>

<?php 
$this->load->view('hr/leave/modals/modal_leave-summary', array('user' => $user, 'allocations' => $allocations));
$this->load->view('hr/leave/modals/modal_loader'); 
?>

<!-- MODALS -->
<div class="modal fade" id="requestModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="request-modal-title">Leave Allocation Request</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="requestModalSubmitBtn" onclick="createAllocationRequest();" class="btn btn-light">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="immutableModal">
    <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">
                    <!-- status. status, updated on, approved on, approved by, remarks -->
                    <div class="form-row" style="margin-bottom: 10px; padding: 5px;">
                        <div class="col bg-warning" style="padding: 5px 10px;" id="status-container">
                            <p id="status-info" style="margin: 0;">
                            </p>
                            <p id="status-remark" style="margin: 0;">
                            </p>
                        </div>
                    </div>        
                    <div class="text-divider text-muted">LEAVE INFORMATION</div>           
                    <!-- single date -->
                    <div class="row" id="isingleContainer">
                        <div class="col-6">
                            <div class="form-group">
                                <label for="dateFrom">On</label>
                                <input required type="text" class="form-control leave_date" id="idateOn" name="dateOn" readonly>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select required class="form-control app-form" id="iperiodOn" name="periodOn">
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- range date -->
                    <div class="row" id="irangeContainer">
                        <div class="col-3">
                            <div class="form-group">
                                <label for="dateFrom">From</label>
                                <input required type="text" class="form-control leave_date" id="idateFrom" name="dateFrom" readonly>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="periodFrom">Period</label>
                                <select required class="form-control app-form" id="iperiodFrom" name="periodFrom" onchange="adjustPeriod(event)">
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="dateTo">To</label>
                                <input required type="text" class="form-control leave_date" id="idateTo" name="dateTo" readonly>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="periodTo">Period</label>
                                <select required class="form-control app-form" id="iperiodTo" name="periodTo" onchange="adjustPeriod(event)">
                                </select>
                            </div>
                        </div>
                    </div>
                    <!-- type and person -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="leaveType">Leave Type</label>
                                <input required type="text" class="form-control" id="ileaveType" readonly>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="leaveType">Duration</label>
                                <input required type="text" class="form-control leave_date" id="iduration" name="duration" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="ireliefPerson">Relief Person</label>
                                <select disabled class="form-control selectpicker app-form" data-style="btn-light" data-live-search="true" id="ireliefPerson">
                                <!-- <select required class="form-control" id="reliefPerson"> -->
                                    <option value="">Select a 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>
                    <!--exam-->
                    <div class="row" id="iexam-container" style="display: none;">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="iexam-name">Examination</label>
                                <input disabled type="text" class="form-control" id="iexam-name">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="ileaveReason">Reason</label>
                        <textarea disabled required data-parsley-error-message="Reason is required." class="form-control" id="ileaveReason" placeholder="Enter reason" /></textarea>
                    </div>
                    <div class="form-group">
                        <label for="ileaveAttachment">Attachment</label>
                        <!-- <input disabled type="file" class="form-control" id="leaveAttachment"> -->
                        <div class="row">
                            <div class="col" id="ifileContainer">
                                <div class="float-left" id="ifileBox">
                                    <a target="_blank">
                                        <span style="font-size: 75px; "><i class="fas fa-file text-primary"></i></span>
                                    </a>
                                </div>  
                            </div>
                            <div class="col" id="iattachmentContainer">
                                <input type="text" class="form-control" readonly value="Not available">
                            </div>
                        </div>
                    </div>

                    <div class="text-divider text-muted">CONTACT INFORMATION</div>
                    <div class="form-row mb-3">
                        <div class="col">
                            <div class="form-group">
                                <label for="iuserAddress">Address</label>
                                <input disabled required data-parsley-error-message="Address is required." type="text" class="form-control" id="iuserAddress" placeholder="Enter address">
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label for="iuserContact">Contact No.</label>
                                <input disabled required data-parsley-error-message="Contact No. is required." type="text" class="form-control" id="iuserContact" placeholder="Enter contact no.">
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="<?php echo base_url(); ?>assets/themes/web/js/moment-with-locales.min.js"></script>
<script>
                                    
    var user = <?php echo json_encode($user) ?>;
    var allocations = <?php echo json_encode($allocations) ?>;
    var userApplications = <?php echo json_encode($applications) ?>;
    var examList = <?php echo json_encode($exam_list) ?>;
    var pubHolidays = <?php echo json_encode($holidays) ?>;
    var leaveInfo = <?php echo json_encode($leave_info) ?>;

    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');

    // vars for cal
    moment.locale('en-sg');
    var incompleteAlloc = false;
    var abnormalOffdayStates = ['kedah', 'kelantan', 'terengganu'];
    var typeSelected = 0;
    var selectedLeaveObj = null;
    var selectedDates = null;
    var calLabels = {
        holidays: {
            color: '#61a8ff',
            name: 'Public holidays'
        },
        exams: {
            color: '#FFA1C9',
            name: 'Exams'
        },
        pending: {
            color: '#FFD93D',
            name: 'Pending applications'
        },
        approved: {
            color: '#6BCB77',
            name: 'Approved applications'
        }
    };
    var threshold = 3; // in day
    var cal;
    var calSource = [];
    var loadedApplication = null;
    data = {
        datasets: [{
            data: [leaveInfo.leaveApproved, leaveInfo.leavePending, leaveInfo.leaveRejected, leaveInfo.leaveCancelled],
            backgroundColor: [
                '#6BCB77',
                '#FFD93D',
                '#FF6B6B',
                // '#4D96FF'
                '#800080'
            ],
        }],
        labels: [
            'Approved',
            'Pending',
            'Rejected',
            'Canceled'
        ]
    };
    var myDoughnutChart = new Chart($('#h-chart'), {
        type: 'doughnut',
        data: data,
    });

    // main
    $(document).ready(function () {
        console.log('DOMContentLoaded');

        if (pubHolidays) {
            console.log('pubHoliday counts: ' + pubHolidays.length);
            pubHolidays.forEach(ph => {
                calSource.push({
                    id: ph.id,
                    name: ph.name,
                    type: 'holidays',
                    color: calLabels.holidays.color,
                    startDate: new Date(new Date((ph.is_moved == 1) ? ph.moved_start_date : ph.original_start_date).getFullYear(), new Date((ph.is_moved == 1) ? ph.moved_start_date : ph.original_start_date).getMonth(), new Date((ph.is_moved == 1) ? ph.moved_start_date : ph.original_start_date).getDate()),
                    startHalfDay: false,
                    endDate: new Date(new Date((ph.is_moved == 1) ? ph.moved_end_date : ph.original_end_date).getFullYear(), new Date((ph.is_moved == 1) ? ph.moved_end_date : ph.original_end_date).getMonth(), new Date((ph.is_moved == 1) ? ph.moved_end_date : ph.original_end_date).getDate()),
                    endHalfDay: false
                });
            });
        }

        // populate calendar with exams
        if (examList) {
            console.log('exam counts: ' + examList.length);
            examList.forEach(ex => {
                calSource.push({
                    id: ex.id,
                    name: `Exam: ${ex.title} (${ex.paper_code})`,
                    type: 'exams',
                    color: calLabels.exams.color,
                    startDate: new Date(new Date(ex.exam_date).getFullYear(), new Date(ex.exam_date).getMonth(), new Date(ex.exam_date).getDate()),
                    startHalfDay: false,
                    endDate: new Date(new Date(ex.exam_date).getFullYear(), new Date(ex.exam_date).getMonth(), new Date(ex.exam_date).getDate()),
                    endHalfDay: false
                });
            });
        }

        // pre-populate leave types
        $('#leaveContainer').append(
                `<select class="form-control" id="leave-type">
                    <option selected value="">Select leave type here to start a new application</option>
                </select>`
                );
        
        // populate calendar with applications
        userApplications.forEach(appArr => {
                if (appArr.is_delete == 0 && ['1', '2'].includes(appArr.status)) {
                    startHalf = false;
                    endHalf = false;
                    if (appArr.date_from == appArr.date_to) {
                        if (appArr.period_from_id == 2 || appArr.period_from_id == 3) {
                            startHalf = true;
                        }
                    } else {
                        if (appArr.period_from_id != 1) {
                            startHalf = true;
                        }
                        if (appArr.period_to_id != 1) {
                            endHalf = true;
                        }
                    }

                    if (appArr.date_from == appArr.date_to)
                        console.log(appArr.period_from_id + ' ' + startHalf + ' ' + endHalf);

                    calSource.push({
                        id: appArr.id,
                        name: appArr.leave_type,
                        duration: appArr.days_applied,
                        type: 'applications',
                        isEL: appArr.is_el,
                        status: appArr.status,
                        color: (appArr.status == 2 ? calLabels.approved.color : calLabels.pending.color),
                        startId: appArr.period_from_id,
                        startDate: new Date(new Date(appArr.date_from).getFullYear(), new Date(appArr.date_from).getMonth(), new Date(appArr.date_from).getDate()),
                        // startHalfDay: (appArr.period_from_id == 1 ? false : true),
                        startHalfDay: startHalf,
                        endId: appArr.period_to_id,
                        endDate: new Date(new Date(appArr.date_to).getFullYear(), new Date(appArr.date_to).getMonth(), new Date(appArr.date_to).getDate()),
                        // endHalfDay: (appArr.period_to_id == 1 ? false : true)
                        endHalfDay: endHalf
                    });
                }
        });

        // iterate user allocations
        allocations.forEach(allArr => {
            // populate leave type select
            if(allArr.require_exam == 1){
                // adjustment for leave with exam
                tName = allArr.name;
                tExam1 = examList.find(elmt => elmt.id == allArr.paper_id);
                tName += ' - ' + tExam1.paper_code;
            }else{
                tName = allArr.name;
            }
            appendStr = `<option value="${allArr.allocation_id}">${tName} <span>(Pending: ${(parseFloat(allArr.pending)).toFixed(1)})${(allArr.expiry_date != null && allArr.expiry_date != '0000-00-00') ? (" (Validity: " + moment(allArr.date_from).format('DD/MM/YYYY') + ' to ' + moment(allArr.expiry_date).format('DD/MM/YYYY') + ")") : ""}</span></option>`;                               
            $('#leave-type').append(appendStr);
            
            // populate taken buttons
            summWithEntitled = true;
            if(allArr.require_allocation_value == 0){
                summWithEntitled = false;
            }
            
            $('#leave-taken-container').append(`
                <button onclick="openSummaryModal()" type="button" class="btn btn-sm mt-1" style="background-color:${allArr.colour}">
                    ${tName} <span class="badge badge-light"><span id="badge-taken-type-${allArr.type_id}">${allArr.leave_taken}</span>` + (summWithEntitled ? (' / ' + allArr.allowed_entitled) : '') + (allArr.is_prorate == 1 ? (' (' + allArr.leave_entitled + ')') : '') + `</span>
                </button>
            `);

        });

        // load calendar with source
        cal = new Calendar('#calendar', {
            style: 'background',
            dataSource: calSource,
            enableContextMenu: true,
            contextMenuItems: [
                {
                    text: 'Delete',
                    click: deleteApplication
                },
                {
                    text: 'Update',
                    click: reroute
                }
            ],
            enableRangeSelection: true,
            mouseOnDay: function (e) {
                if (e.events.length > 0) {
                    var content = '';

                    for (var i in e.events) {
                        let dateStr = (moment(e.events[i].startDate).format("L")) + 
                                (e.events[i].type == 'applications' ? (' (' + (e.events[i].startId == 1 ? 'F' : (e.events[i].startId == 2 ? 'H AM' : 'H PM')) + ')') : '');
                        if(moment(e.events[i].startDate).format("L") != moment(e.events[i].endDate).format("L")){
                            dateStr += ' - ' + (moment(e.events[i].endDate).format("L")) +
                                (e.events[i].type == 'applications' ? (' (' + (e.events[i].endId == 1 ? 'F' : (e.events[i].endId == 2 ? 'H AM' : 'H PM')) + ')') : '');
                        }
                        content += '<div class="event-tooltip-content">'
                                + '<div class="event-name" style="color:' + e.events[i].color + '">' + e.events[i].name
                                + (e.events[i].isEL == 1 ? ' (Emergency)' : '')
                                + (e.events[i].type == 'applications' ? ' (' + e.events[i].duration + ' d)' : '')
                                + '</div>'
                                + '<div class="event-dates">'
                                + dateStr
                                + '</div>'
                                + '</div>';
                    }

                    $(e.element).popover({
                        trigger: 'manual',
                        container: 'body',
                        html: true,
                        content: content
                    });

                    $(e.element).popover('show');
                }
            },
            mouseOutDay: function (e) {
                if (e.events.length > 0) {
                    $(e.element).popover('hide');
                }
            },
            selectRange: function (e) {
                processSelection2({startDate: e.startDate, endDate: e.endDate});
            },
        });

        // populate legends 
        console.log('size of legends: ' + Object.keys(calLabels).length);
        for (const clk in calLabels) {
            console.log(`${calLabels[clk].name}`);
            $('#legendContainer').append(
                    `<span style="border-radius: 5px; padding: 5px 0; text-align: center; width: 170px; margin: 0 5px; background-color: ${calLabels[clk].color};">${calLabels[clk].name}</span>`
                    );
        }

    });

    // listeners
    $('#applicationCardCancelBtn').on('click', function(){
        // reset
        if(loadedApplication){
            setupEdit(false);
        }
        loadedApplication = null;
        resetElements();
        prepareEdit(false); // if edit
        // hide
        // $('#application-card').hide();
    });
    $('#applicationModal').on('hidden.bs.modal', function () {
        resetElements();
    });
    
    $('#immutableModal').on('hidden.bs.modal', function(){
        if(loadedApplication){
            loadedApplication = null;
            resetElements();
        }
    });

    $('#leaveContainer').on('change', '#leave-type', function () {
        selectedLeaveObj = null;
        $('#calendar-error').empty(); // remove error
        resetElements(); 

        // use allocation id instead of type id to handle multiple alloc
        // typeSelected = ($(this).val() ? parseInt($(this).val()) : 0);
        allocationSelected = ($(this).val() ? parseInt($(this).val()) : 0);

        // select leave
        // selectedLeaveObj = allocations.find(obj1 => parseInt(obj1.type_id) == typeSelected);
        selectedLeaveObj = allocations.find(obj1 => parseInt(obj1.allocation_id) == allocationSelected);

        // check completion status of allocation
        if(selectedLeaveObj){
            incompleteAlloc = (selectedLeaveObj.alloc_complete == 0 ? true : false);
            if (incompleteAlloc)
                return showErrorDialog(`Allocation for ${selectedLeaveObj.name} is incomplete. Please contact HR for support.`);

            console.log('selected leave: ' + JSON.stringify(selectedLeaveObj));
        }
        
    });

    $('#periodOn').on('change', function () {
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodOn').val(), 0);
    });

    $('#periodFrom').on('change', function () {
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodFrom').val(), $('#periodTo').val());
    });

    $('#periodTo').on('change', function () {
        calculateDuration(selectedDates.start, selectedDates.end, $('#periodFrom').val(), $('#periodTo').val());
    });

    $('.required-input').on('change', function () {
        $('#application-error').html('');
    });

    // clear modal stuff
    function resetElements() {
        $('#application-card').hide();

        $('#periodFrom').empty();
        $('#periodTo').empty();
        $('#periodOn').empty();
        // $('#leaveType').empty();
        $('#application-type').empty();
        $('#leaveAttachment').empty();

        $('#calendar-error').empty();
        $('#leaveReason').val("");
        $('#periodTo').attr('disabled', false);
        $('#periodFrom').attr('disabled', false);
        $('#periodOn').attr('disabled', false);

        $('#deleteAtt').val('0');
        $('#application-error').html('');
        $('#exam-container').hide();

        $('#leaveAttachment').val("");
        $('#fileContainer').hide();
        $('#attachmentContainer').show();
        $('#reliefPerson').selectpicker('val', ['']);

        if(!loadedApplication){
            selectedDates = null;
        }
    }

    // if more than 1 day, start can be 1 or 3 and end can be 1 or 2 only.
    function processSelection2(event) {
        $('#calendar-error').empty();
        isEL = false;

        // check if an event
        // if(event.id) console.log('viewing event: ' + event.name);

        // check if type selected
        if (!selectedLeaveObj)
            return showErrorDialog('Please select a leave type first');
        if (incompleteAlloc)
            return showErrorDialog(`Allocation for ${selectedLeaveObj.name} is incomplete. Please contact HR for support.`);
        console.log('type selected: ' + selectedLeaveObj.type_id);

        // check if within allocation date and expiry date
        if (!checkAllocationDate(event.startDate, event.endDate))
            return showErrorDialog(`Invalid selection. Please select date that falls within allocated dates`);

        // check backdated
        if (checkBackdated(event.startDate)) {
            if (selectedLeaveObj.type_id == 1) {
                isEL = true;
            }
        }

        // check start date against cooling off period
        if (selectedLeaveObj.cooling_period != 0 && checkCoolingPeriod(event.startDate)) {
            if (selectedLeaveObj.type_id == 1) {
                isEL = true;
            }
        }

        // check off day for holiday-exclusive leave
        if (selectedLeaveObj.include_holiday == 0 && checkOffDay(event.startDate, event.endDate))
            return showErrorDialog('Invalid selection. Please only select working days for start and end dates.');

        // check balance. consider minimum duration
        resObj = checkLeaveBalance(event.startDate, event.endDate);
        if (!resObj.balOk)
            return showErrorDialog('Insufficient Leave Balance. Please contact Administrator for further enquiries.');

        // check for exam leave
        if (selectedLeaveObj.require_exam == 1) {
            if (!checkExam2(event.startDate, event.endDate))
                return showErrorDialog('Invalid selection. Please make sure that date selected before exam date.');
        }

        console.log('selection: ' + event.startDate + ' ##### ' + event.endDate);

        // check early slot availability
//        startAmAvailable = cal.isThereFreeSlot(event.startDate, false);
//        startPmAvailable = cal.isThereFreeSlot(event.startDate, true);
        startAmAvailable = checkSlotAvailability(event.startDate, false);
        startPmAvailable = checkSlotAvailability(event.startDate, true);
        console.log('start am: ' + startAmAvailable);
        console.log('start pm: ' + startPmAvailable);

        // check late slot availability
//        endAmAvailable = cal.isThereFreeSlot(event.endDate, false);
//        endPmAvailable = cal.isThereFreeSlot(event.endDate, true);
        endAmAvailable = checkSlotAvailability(event.endDate, false);
        endPmAvailable = checkSlotAvailability(event.endDate, true);
        console.log('end am: ' + endAmAvailable);
        console.log('end pm: ' + endPmAvailable);

        selectedDates = {
            start: event.startDate,
            end: event.endDate
        };

        $('#periodNdAdj').val(0);

        if (event.startDate == event.endDate) {
            // single day
            console.log('one date only');
            slots = [];
            slots[1] = 'Full day';
            slots[2] = 'Half day (AM)';
            slots[3] = 'Half day (PM)';
            datesOk = true;
            sAdj = 0;
            if (!startAmAvailable && !startPmAvailable) {
                slots = [];
                datesOk = false;
            } else if (startAmAvailable && startPmAvailable) {
                // do nothing
                sAdj = 1;
            } else if (startAmAvailable) {
                // if am/start available, check that if actually available
                eventsArr = cal.getEventsOnRange(event.startDate, moment(event.endDate).add(1, 'day')); // non-inclusive so add one
                if (eventsArr[0].startId == 2) {
                    // actually pm available
                    slots.splice(1, 2);
                    sAdj = 3;
                } else {
                    // genuine am
                    slots.splice(1, 1);
                    slots.splice(2, 1);
                    sAdj = 2;
                }

            } else if (startPmAvailable) {
                slots.splice(1, 2);
                sAdj = 3;
            }

            if (datesOk) {
                console.log('Valid date. Slots available: ' + slots);
                lD = calculateDuration(event.startDate, event.endDate, sAdj, 0);
                // loadNewModal(event.startDate, event.endDate, false, slots, [], isEL); // old1
                // loadNewCard(event.startDate, event.endDate, false, slots, [], isEL); // old2
                if(loadedApplication){
                    // editing
                    loadEditCard(null, event.startDate, event.endDate, false, slots, [], isEL);
                }else{
                    // creating
                    loadNewCard(event.startDate, event.endDate, false, slots, [], isEL);
                }
            } else {
                return showErrorDialog('Invalid selection. Please select date that does not overlap with exams, public holidays or existing leaves.');
            }
        } else {
            // range of days
            console.log('more than one date');

//            if (checkOverlapping2(event.startDate, event.endDate))
//                return showErrorDialog('Invalid selection. Please select dates that do not overlap with public holidays or existing leaves.');
//            console.log('passed overlapping');
            
            let overlapped = checkOverlapping2(event.startDate, event.endDate);
            if(overlapped) 
                return showErrorDialog('Invalid selection. Please select dates that do not overlap with public holidays or existing leaves.');
            console.log('passed overlapping');
            
            // override slots availability for type that allow overlap
//            if(!overlapped){    
////                startAmAvailable = true;
////                startPmAvailable
////                endAmAvailable
////                endPmAvailable
//            }

            slotsS = [];
            slotsS[1] = 'Full day';
            slotsS[2] = 'Half day (AM)';
            slotsS[3] = 'Half day (PM)';
            datesOk = true;
            sAdj = 0;
            eAdj = 0;
            if (!startAmAvailable && !startPmAvailable) {
                slotsS = [];
                datesOk = false;
            } else if (startAmAvailable && startPmAvailable) {
                // do nothing
                sAdj = 1;
            } else if (startAmAvailable) {
                slotsS.splice(1, 1);
                slotsS.splice(2, 1);
                sAdj = 2;
            } else if (startPmAvailable) {
                slotsS.splice(1, 2);
                sAdj = 3;
            }

            slotsE = [];
            slotsE[1] = 'Full day';
            slotsE[2] = 'Half day (AM)';
            slotsE[3] = 'Half day (PM)';
            if (!endAmAvailable && !endPmAvailable) {
                slotsE = [];
                datesOk = false;
            } else if (endAmAvailable && endPmAvailable) {
                // do nothing
                eAdj = 1;
            } else if (endAmAvailable) {
                slotsE.splice(1, 1);
                slotsE.splice(2, 1);
                eAdj = 2;
            } else if (endPmAvailable) {
                slotsE.splice(1, 2);
                eAdj = 3;
            }

            if (datesOk) {
                console.log('Valid date. Slots start available: ' + slotsS);
                console.log('Valid date. Slots end available: ' + slotsE);
                lD = calculateDuration(event.startDate, event.endDate, sAdj, eAdj);
                adjSlots = durationAdjustment(lD, valFrAsmt, slotsS, slotsE);
                // loadNewModal(event.startDate, event.endDate, true, adjSlots[0], adjSlots[1], isEL); // old 1
                // loadNewCard(event.startDate, event.endDate, true, adjSlots[0], adjSlots[1], isEL); // old 2
                if(loadedApplication){
                    // editing
                    loadEditCard(null,event.startDate, event.endDate, true, adjSlots[0], adjSlots[1], isEL);
                }else{
                    // creating
                    loadNewCard(event.startDate, event.endDate, true, adjSlots[0], adjSlots[1], isEL);
                }
            } else {
                return showErrorDialog('Invalid selection');
            }
        }

    }
    
    function loadDefaultAvatar(){
        defaultAvatar = (user.gender_id == '2') ? 'user-female.png' : 'user.png';
        $('#avatar').attr('src', '<?php echo base_url('/assets/images/'); ?>' + defaultAvatar);
//                                        $('#avatar').attr('src', window.location.origin + '/assets/images/' + defaultAvatar);
    }

    function showErrorDialog(errMsg) {
        // alert(errMsg);
        $('#calendar-error').html(errMsg);
    }

    // after calculation - passed but with adjustment (1) pre-select period from/to, modify items on slots array (2) recalc duration
    function durationAdjustment(calculatedDuration, valueForAdjustment, slotStart, slotEnd) {
        console.log('durationAdjustment()');
        console.log('value for adjustment: ' + valueForAdjustment);

        if (valueForAdjustment == -1) {
            console.log('need both adjustment');
            console.log(slotStart[1] + ' will be removed');
            console.log(slotEnd[1] + ' will be removed');
            // remove full day on both slots array, make it null instead
            slotStart.splice(1, 1, null);
            slotEnd.splice(1, 1, null);
            console.log('slotStart: ' + slotStart);
            console.log('slotEnd: ' + slotEnd);
            $('#periodNdAdj').val(2);
        } else if (valueForAdjustment == -0.5) {
            console.log('need one side adjustment');
            $('#periodNdAdj').val(1);

        } else {
            console.log('need no adjustment');
        }

        return [slotStart, slotEnd];
    }

    function checkAllocationDate(eventStartDate, eventEndDate) {
        eventStartDate = moment(eventStartDate).format("YYYY-MM-DD");
        eventEndDate = moment(eventEndDate).format("YYYY-MM-DD");
        console.log(eventStartDate + ' ' + eventEndDate + ' ' + selectedLeaveObj.date_from + ' ' + selectedLeaveObj.date_to);
        console.log((new Date(eventStartDate)).getTime() + ' ' + (new Date(eventEndDate)).getTime() + ' ' + (new Date(selectedLeaveObj.date_from)).getTime() + ' ' + (new Date(selectedLeaveObj.date_to)).getTime());
        isOk = false;
        if ((new Date(eventStartDate)).getTime() >= (new Date(selectedLeaveObj.date_from)).getTime() && 
                (new Date(eventEndDate)).getTime() <= (new Date(selectedLeaveObj.date_to)).getTime() &&
                (new Date(eventEndDate)).getTime() <= (new Date(selectedLeaveObj.expiry_date)).getTime()) {
            isOk = true;
        }
//        if ((new Date(eventEndDate)).getTime() > (new Date(selectedLeaveObj.expiry_date)).getTime()) {
//            isOk = false;
//        }
        // check expiry if not with exam - expiry treated differently
//        if (selectedLeaveObj.require_exam == 0 && (new Date(eventEndDate)).getTime() > (new Date(selectedLeaveObj.expiry_date)).getTime()) {
//            console.log('pass expiry');
//            isOk = false;
//        }
//        if (!([7].includes(selectedLeaveObj.type_id)) && (new Date(eventEndDate)).getTime() > (new Date(selectedLeaveObj.expiry_date)).getTime()) {
//            console.log('pass expiry');
//            isOk = false;
//        }

        return isOk;
    }

    function checkBackdated(eventStartDate) {
        var startDate = moment(eventStartDate, "DD-MM-YYYY");
        var today = moment();

        bd = false;
        if (startDate.isBefore(today, 'days')) {
            bd = true;
        }
        return bd;
    }

    function checkCoolingPeriod(eventStartDate) {
        console.log('selecting ' + selectedLeaveObj.name + ' with cop: ' + selectedLeaveObj.cooling_period);
        ltDate = moment().add(selectedLeaveObj.cooling_period, 'day');
        cp = false;
        if (moment(event.startDate) <= ltDate) {
            cp = true;
        }
        return cp;
    }

    // check if start and end date fall on off day. only for include_holiday = 0. check for states with abnormal off days
    function checkOffDay(eventStartDate, eventEndDate) {
        od = false;

        sdName = (moment(eventStartDate).format('dddd')).toLowerCase();
        edName = (moment(eventEndDate).format('dddd')).toLowerCase();
        console.log('days: ' + sdName + ' and ' + edName);

        odArr = null;
        if (abnormalOffdayStates.includes(user.state.toLowerCase())) {
            // east coast
            odArr = ['friday', 'saturday'];
            console.log('abnormal');

        } else {
            // everywhere else
            odArr = ['saturday', 'sunday'];
            console.log('normal');

        }
        if (odArr.includes(sdName) || odArr.includes(edName))
            od = true;
        console.log('off day: ' + od);
        return od;
    }

    // check overlapping with public holidays or existing leaves. ok for leave with include_holiday = 1
    function checkOverlapping(date1, date2) {
        console.log('checkOverlapping');
        eventsArr = cal.getEventsOnRange(date1, moment(date2).add(1, 'day')); // non-inclusive so add one
        console.log('events overlapped: ' + eventsArr.length);

        // for each event, check if new dates in between or existing events in between
        // can overlap if include holiday or if type is exams
        canOverlap = selectedLeaveObj.include_holiday == 1 ? true : false;
        overlapped = false;
        allHolidayEvents = 0;
        allExamEvents = 0;
        for (ev of eventsArr) {
            console.log('an event: ' + ev.type);
            
            if (selectedLeaveObj.include_holiday == 1) {
                if (ev.type == 'holidays') {
                    console.log('found holiday');
                    allHolidayEvents++;
                } else {
                    console.log('found non-holiday');
                    if (
                            (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                            (moment(ev.endDate).isBetween(date1, date2, 'day')) ||
                            (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                            ) {
                        console.log('overlapped')
                        overlapped = true;
                    }
                    break;
                }
            } else {
                if (
                        (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) ||
                        (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) ||
                        (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                        (moment(ev.endDate).isBetween(date1, date2, 'day')) ||
                        (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                        ) {
                    console.log('overlapped')
                    overlapped = true;
                }
                break;
            }
        }
        console.log('canOverlap: ' + canOverlap + ' allHolidayEvents: ' + allHolidayEvents);
        if (canOverlap && (eventsArr.length == allHolidayEvents))
            overlapped = false;
        console.log('overlapped: ' + overlapped);
        return overlapped;
    }

    // check overlapping with public holidays or existing leaves. ok for leave with include_holiday = 1 or require_exam = 1
    function checkOverlapping2(date1, date2) {
        console.log('checkOverlapping');
        eventsArr = cal.getEventsOnRange(date1, moment(date2).add(1, 'day')); // non-inclusive so add one
        console.log('events overlapped: ' + eventsArr.length);

        // for each event, check if new dates in between or existing events in between
        // can overlap if include holiday or if type is exams
        canOverlap = (selectedLeaveObj.include_holiday == 1 || selectedLeaveObj.require_exam == 1) ? true : false;
        overlapped = false;
        allHolidayEvents = 0;
        allExamEvents = 0;
        for (ev of eventsArr) {
            console.log('an event: ' + ev.type);
            
            if (selectedLeaveObj.include_holiday == 1) {
                if (ev.type == 'holidays') {
                    console.log('found holiday');
                    allHolidayEvents++;
                } else if(ev.type == 'exams'){
                    console.log('found exams');
                } else {
                    console.log('found non-holiday');
                    if (
                            (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                            (moment(ev.endDate).isBetween(date1, date2, 'day')) 
//                            || (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                            ) {
                        console.log('overlapped')
                        overlapped = true;
                    }
                    break;
                }
            } else if(selectedLeaveObj.require_exam == 1) {
                if (ev.type == 'exams') {
                    console.log('found exam');
                    allExamEvents++;
                } else {
                    console.log('found non-exam');
                    if (
                            (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) ||
                            (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                            (moment(ev.endDate).isBetween(date1, date2, 'day')) 
//                            || (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                            ) {
                        console.log('overlapped')
                        overlapped = true;
                    }
                    break;
                }
            } else {
                if(ev.type == 'exams'){
                    console.log('found exams');
                }else{ 
                    if(
                        (moment(date1).isBetween(ev.startDate, ev.endDate, 'day')) ||
                        (moment(date2).isBetween(ev.startDate, ev.endDate, 'day')) ||
                        (moment(ev.startDate).isBetween(date1, date2, 'day')) ||
                        (moment(ev.endDate).isBetween(date1, date2, 'day')) 
//                        || (moment(date1).isSame(ev.startDate, 'day') || moment(date2).isSame(ev.endDate, 'day'))
                        ) {
                            console.log('overlapped')
                            overlapped = true;
                        }
                }
                break;
            }
        }
        console.log('canOverlap: ' + canOverlap + ' allHolidayEvents: ' + allHolidayEvents + ' allExamEvents: ' + allExamEvents);
        if (canOverlap && (eventsArr.length == allHolidayEvents || eventsArr.length == allExamEvents))
            overlapped = false;
        console.log('overlapped: ' + overlapped);
        return overlapped;
    }

    // for start and end date. app/holiday: nope, exam: ok
    function checkSlotAvailability(tempDate, isPM){
        let isTempAvailable = cal.isThereFreeSlot(tempDate, isPM);
        console.log('check slot: ' + isTempAvailable);
        if(!isTempAvailable){
            // get events on the date
            let tempEvents = cal.getEvents(tempDate);
            if(tempEvents.length > 1){
                let tempOk = true;
                for(let tempEv of tempEvents){
//                    console.log('slot event: ' + JSON.stringify(tempEv));
//                if(tempEv.type == 'applications' || (tempEv.type == 'holidays' && selectedLeaveObj.include_holiday == 0)){
//                    console.log('true false');
//                    tempOk = false;
//                    break;
//                }
                    if((tempEv.type == 'applications' && tempEv.endHalfDay && isPM) || 
                        (tempEv.type == 'applications' && tempEv.startHalfDay && !isPM) || 
                        (tempEv.type == 'holidays' && selectedLeaveObj.include_holiday == 0)){
//                            console.log('true false');
                            tempOk = false;
                            break;
                    }
                
                }
//            console.log('check slot: ' + tempOk);
                return tempOk;
            }
            return false;
        }else{
            return isTempAvailable;
        }
    }

    // if loadedApplication, add that to balance available
    function checkLeaveBalance(date1, date2) {
        console.log('checkBalance()');
        balOk = true;
        valFrAsmt = 99999; // needed for adjustment function
        console.log('date1: ' + date1);
        console.log('date2: ' + date2);

        if (selectedLeaveObj.require_allocation_value == 1) {
                td = (moment(moment(date2).add(1, 'day')).diff(moment(date1), 'days'));

                // subtract .5*2 to assume both start and end half day is hd
                if ((parseFloat(selectedLeaveObj.allowed_balance) - (parseFloat(td) - 1)) < 0) {
                    balOk = false;
                } else {
                    valFrAsmt = parseFloat(selectedLeaveObj.allowed_balance) - parseFloat(td);
                }
        }

        // if td > balance, assume half day in calculation but force half day in modal. for valFrAsmt 0.5 or 1
        return res = {
            balOk: balOk,
            valFrAsmt: valFrAsmt
        };

    }

    // check (1) end date one day before exam (2) exam still incomplete (3) max duration is five days consecutively inclusive of weekend (3). old
    function checkExam2(date1, date2) {
        console.log('checking exam');
        // 0 - ok, 1 - no exam, 2 - not before, 3 - exceed five days

        // get exam from selected allocation
        tExam = examList.find(elmt => elmt.id == selectedLeaveObj.paper_id);

//        return ((moment(date2, "DD-MM-YYYY")).isBefore(moment(selectedLeaveObj.expiry_date), 'days'));
        return !((moment(selectedLeaveObj.expiry_date)).isBefore(moment(date2, "DD-MM-YYYY"), 'days'));
    }

    // half vs full day. include holiday vs non
    function calculateDuration(date1, date2, date1Period, date2Period) {
        console.log('date1: ' + date1 + ' date2: ' + date2);
        console.log('period from: ' + date1Period + ' period to: ' + date2Period);
        td = 0.0;
        if (selectedLeaveObj.include_holiday == 1) {
            td = (moment(moment(date2).add(1, 'day')).diff(moment(date1), 'days'));
            // td -= 2;
        } else {
            td += 1;

            mDate1 = moment(date1);
            // console.log(mDate1);
            while (!mDate1.isSame(date2, 'day')) {
                console.log(mDate1.format('dddd'));
                mDate1 = mDate1.add(1, 'day');
                // console.log(mDate1);
                if (!['saturday', 'sunday'].includes((mDate1.format('dddd')).toLowerCase())) {
                    td += 1;
                    console.log('not off day');
                }
            }
            // td -= 2;
        }
        // adjustment
        td = td - (date1 == date2 ? 1 : 2);

        console.log('td: ' + td);
        td += (date1Period == 1) ? 1 : 0.5;
        console.log('td: ' + td);
        if (date2Period > 0)
            td += ((date2Period == 1) ? 1 : 0.5);
        console.log('td: ' + td);

        // if(date1 == date2){
        //     td += (date1Period == 1) ? 1 : 0.5;
        // }else{
        //     td += (date1Period == 1) ? 1 : 0.5;
        //     td += (date2Period == 1) ? 1 : 0.5;
        // }

        console.log('durations: ' + td);
        $('#duration').val(td);
        return td;

    }

    function adjustPeriod(e) {
        if ($('#periodNdAdj').val() == 1) {
            console.log('period need adjustment. event-driven adjustment');
            console.log('from: ' + $('#periodFrom').val());
            console.log('to: ' + $('#periodTo').val());
            if (e.target.id == 'periodFrom') {
                console.log('change periodTo');
                if ($('#periodFrom').val() == 1 && $('#periodTo').val() == 1)
                    $('#periodTo').val(2);
                // $('#periodTo').val() == 2 ? $('#periodTo').val(1) : $('#periodTo').val(2);
                // if($('#periodTo').val() == 3){
                //     $('#periodTo option:selected').prev().prop('selected', true);
                // }else{
                //     $('#periodTo option:selected').next().prop('selected', true);
                // }
            } else if (e.target.id == 'periodTo') {
                console.log('change periodFrom');
                if ($('#periodTo').val() == 1 && $('#periodFrom').val() == 1)
                    $('#periodFrom').val(3);
                // $('#periodFrom').val() == 3 ? $('#periodFrom').val(1) : $('#periodFrom').val(3);
                // if($('#periodFrom').val() == 3){
                //     $('#periodFrom option:selected').prev().prop('selected', true);
                // }else{
                //     $('#periodFrom option:selected').next().prop('selected', true);
                // }
            }
        }
    }

    function loadImmutableModal(id) {
        console.log('loadImmutableModal() for application: ' + id);
        
        if(loadedApplication){
            setupEdit(false);
            loadedApplication = null;
            resetElements();
            prepareEdit(false);
        }

        // grab the application
            loadedApplication = (userApplications).find(ao => ao.id == id);
            if (loadedApplication) {
                console.log('loaded application: ' + JSON.stringify(loadedApplication));
                slots = [];
                slots[1] = 'Full day';
                slots[2] = 'Half day (AM)';
                slots[3] = 'Half day (PM)';

                if (loadedApplication.date_from == loadedApplication.date_to) {
                    // same day
                    $('#immutableModal input[name="dateOn"]').val(moment(loadedApplication.date_from).format('L'))
                    $('#iperiodOn').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                    $('#iperiodOn').attr('disabled', true);
                    $('#isingleContainer').show();
                    $('#irangeContainer').hide();
                } else {
                    // multiple days
                    $('#immutableModal input[name="dateFrom"]').val(moment(loadedApplication.date_from).format('L'))
                    $('#iperiodFrom').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                    $('#iperiodFrom').attr('disabled', true);
                    $('#immutableModal input[name="dateTo"]').val(moment(loadedApplication.date_to).format('L'))
                    $('#iperiodTo').append(`<option value="${loadedApplication.period_to_id}">${slots[loadedApplication.period_to_id]}</option>`);
                    $('#iperiodTo').attr('disabled', true);
                    $('#isingleContainer').hide();
                    $('#irangeContainer').show();
                }

                // load status
                $('#status-container').removeClass().addClass('col');
                switch (Number(loadedApplication.status)) {
                    case 1:
                        $('#status-info').html('Status: <b>PENDING</b>');
                        $('#status-remark').hide();
                        $('#status-container').addClass('bg-warning');
                        break;
                    case 2:
                        $('#status-info').html(`Status: <b>APPROVED</b> (By <i>${loadedApplication.updated_by_name}</i> on <i>${moment(loadedApplication.updated_ts).format('DD-MM-YYYY')}</i>)`);
                        $('#status-remark').show().html(`Remarks: <i>${loadedApplication.remarks}</i>`);
                        $('#status-container').addClass('bg-success');
                        break;
                    case 3:
                        $('#status-info').html(`Status: <b>REJECTED</b> (By <i>${loadedApplication.updated_by_name}</i> on <i>${moment(loadedApplication.updated_ts).format('DD-MM-YYYY')}</i>)`);
                        $('#status-remark').show().html(`Remarks: <i>${loadedApplication.remarks}</i>`);
                        $('#status-container').addClass('bg-danger');
                        break;
                    case 4:
                        $('#status-info').html(`Status: <b>CANCELED</b> (By <i>${loadedApplication.updated_by_name}</i> on <i>${moment(loadedApplication.updated_ts).format('DD-MM-YYYY')}</i>)`);
                        $('#status-remark').show().html(`Remarks: <i>${loadedApplication.remarks}</i>`);
                        $('#status-container').addClass('bg-secondary');
                        break;
                }

                // load exam 
                if (loadedApplication.type_id == 7) {
                    theExam = examList.find(elmt => elmt.id == loadedApplication.exam_id);
                    $('#iexam-name').val(`${theExam.title} (${theExam.paper_code}) - ${moment(theExam.exam_date).format("MMM Do YYYY")}`);
                    $('#iexam-container').show();
                }

                // load attachement if any
                if (loadedApplication.file_name) {
                    baseUrl = window.location.origin;
                    console.log(baseUrl);
                    $('#ifileBox a').attr('href', `${ baseUrl + '/spserp.dev/' + loadedApplication.file_location + loadedApplication.file_name }`);
                    $('#ifileContainer').show();
                    $('#iattachmentContainer').hide();
                } else {
                    $('#ifileContainer').hide();
                    $('#iattachmentContainer').show();
                }

                // disable calendar
                // $('.leave_date').datepicker({
                //     enableOnReadonly: false
                // });

                $('#iduration').val(loadedApplication.days_applied);
                loadedApplication.is_el == 1 ? $('#ileaveType').val(loadedApplication.leave_type + ' (Emergency)') : $('#ileaveType').val(loadedApplication.leave_type);
                $('#ileaveReason').val(loadedApplication.reason);
                $('#iuserAddress').val(loadedApplication.absent_address);
                $('#iuserContact').val(loadedApplication.absent_contact);
                $('#ireliefPerson').selectpicker('val', [loadedApplication.absent_relief_id]);
                console.log('relief person id: ' + loadedApplication.absent_relief_id);

                $("#immutableModal").modal('show');

            }
    }

    // check input. require labels
    function checkForm() {
        empty = false;
        errorStr = '';
        $('.required-input').each(function () {
            if (this.id != null && this.id != undefined && this.value == '') {
                console.log('id: ' + this.id + ' val length: ' + this.value.length);
                if(this.id == 'leaveAttachment' && selectedLeaveObj.app_require_attachment == 0){
                    return true;
                }
                
                if(this.id == 'leaveAttachment' && loadedApplication && $('#deleteAtt').val() == 0){
                    return true;
                }
                
                console.log('found an empty input: ' + this.id);
                label = $("label[for=" + this.id + "]");
                console.log('label: ' + label.text());
                empty = true;
                errorStr += label.text();
                return false;
            }
        });
        return {
            error: empty,
            msg: errorStr
        };
    }

    function saveApplication() {
        console.log('saveApplication');

        checkRes = checkForm();
        if (checkRes.error)
            return ($('#application-error').html(checkRes.msg + ' is required'));

        toastConfirm("Are you sure you want to submit this leave application?", function () {
            // check for attachment
            // if(selectedLeaveObj.type_id == 3 && !checkAttachment()) return '';

            if ($('#errorList li').length > 0) {
                console.log('error');
                iziToast.error({
                    position: 'bottomRight',
                    title: "Application Error",
                    message: $('#errorList li').length + " errors. Please fix to proceed."
                });
            } else {
                console.log('forming formdata');
                console.log('relief person: ' + $('#reliefPerson').val());
                var fd = new FormData();
                // tlt = $('#leaveType').val();
                tlt = $('#application-type').html();
                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("date_from", moment(selectedDates.start).format('YYYY-MM-DD'));
                fd.append("period_from_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodFrom').val()));
                // fd.append("date_to", $('#dateTo').val());
                fd.append("date_to", moment(selectedDates.end).format('YYYY-MM-DD'));
                fd.append("period_to_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodTo').val()));
                // fd.append("type_id", $('#leaveType').val());
                // fd.append("type_id", typeSelected);
                fd.append("type_id", selectedLeaveObj.type_id);
                fd.append("absent_relief_id", $('#reliefPerson').val());
                fd.append("reason", $('#leaveReason').val());
                fd.append("absent_contact", $('#userContact').val());
                fd.append("absent_address", $('#userAddress').val());
                fd.append('days_applied', $('#duration').val());
                fd.append('allocation_id', selectedLeaveObj.allocation_id);
                fd.append('is_el', (tlt.includes('Emergency')) ? 1 : 0);
                fd.append('exam_id', selectedLeaveObj.paper_id);

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

                    fd.append("attachment", attachment);
                }

                // show loader
                $('#loader-modal').modal('show');

                console.log('sending ajax request');
                $.ajax({
                    // url: "<?php //echo base_url('hr/leave_v3/createApplication'); ?>",
                    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);
                        $("#application-card").hide();
                        // location.reload();
                        window.location.replace(window.location.href);
                    },
                    error: (jqXHR, textStatus, errorThrown) => {
                        $('#application-error').html('Failed to create leave application. Please contact support.');
                        console.log('ajax error');
                        console.log(textStatus);
                        console.log(errorThrown);
                    },
                    complete: (xhr,status) => {
                        $("#loader-modal").modal('hide');
                    }
                });
            }
        });
    }

    function deleteApplication(event) {
        if (event.type == 'applications') {
            if (event.status != 1)
                return console.log('Invalid action');
            toastConfirm("Are you sure you want to delete this application?", function () {

                // show loader
                $('#loader-modal').modal('show');

                $.ajax({
                    type: 'POST',
                    // url: '<?php //echo base_url('hr/leave_v3/deleteApplication'); ?>',
                    url: '<?php echo base_url('hr/leave/deleteApplication'); ?>',
                    data: {
                        'id': event.id
                    },
                    dataType: 'JSON',
                    success: function (data) {
                        if (data.status == 'Success') {
                            localStorage.setItem("status", data.status);
                            localStorage.setItem("msg", data.msg);

                            // location.reload();
                            window.location.replace(window.location.href);
                        }
                    },
                    error: (jqXHR, textStatus, errorThrown) => {
                        $('#application-error').html('Failed to delete leave application. Please contact support.');
                        console.log('ajax error');
                        console.log(textStatus);
                        console.log(errorThrown);
                    },
                    complete: (xhr,status) => {
                        $("#loader-modal").modal('hide');
                    }
                });
            });
        }
    }

    // date, period, type - cannot be change
    function updateApplication() {
        console.log('updateApplication');
        console.log('forming formdata');
        console.log('relief person: ' + $('#reliefPerson').val());
        console.log('updating: ' + $('#appId').val());
        console.log('deleteAtt: ' + $('#deleteAtt').val());

        checkRes = checkForm();
        if (checkRes.error)
            return ($('#application-error').html(checkRes.msg + ' is required'));

        toastConfirm("Are you sure you want to update this leave application?", function () {
            if ($('#errorList li').length > 0) {
                console.log('error');
                iziToast.error({
                    position: 'bottomRight',
                    title: "Application Error",
                    message: $('#errorList li').length + " errors. Please fix to proceed."
                });
            } else {
                var fd = new FormData();

                tlt = $('#application-type').html();
                fd.append("id", $('#appId').val());
                fd.append('delete_att', $('#deleteAtt').val());
                fd.append("user_id", <?php echo $user['id']; ?>);
                fd.append("department_id", <?php echo $user['department_id']; ?>);
                fd.append("date_from", moment(selectedDates.start).format('YYYY-MM-DD'));
                fd.append("period_from_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodFrom').val()));
                fd.append("date_to", moment(selectedDates.end).format('YYYY-MM-DD'));
                fd.append("period_to_id", (selectedDates.start == selectedDates.end ? $('#periodOn').val() : $('#periodTo').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());
                fd.append('days_applied', $('#duration').val());
                fd.append('is_el', (tlt.includes('Emergency')) ? 1 : 0);
                fd.append('exam_id', selectedLeaveObj.paper_id);
                if ($('#leaveAttachment').prop('files').length > 0) {
                    var attachment = $('#leaveAttachment').prop('files')[0];

                    fd.append("attachment", attachment);
                }

                // show loader
                $('#loader-modal').modal('show');

                console.log('sending ajax request');
                $.ajax({
                    // url: "<?php //echo base_url('hr/leave_v3/updateApplication'); ?>",
                    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);
                            $("#application-card").hide();
                            // location.reload();
                            window.location.replace(window.location.href);
                        }
                    },
                    error: (jqXHR, textStatus, errorThrown) => {
                        $("#loader-modal").modal('hide');
                        $('#application-error').html('Failed to update leave application. Please contact support.');
                        console.log('ajax error');
                        console.log(textStatus);
                        console.log(errorThrown);
                    },
                    complete: (xhr,status) => {
                        console.log('ajax call completed');
                        $("#loader-modal").modal('hide');
                    }
                })
            }
        });

    }

    // (1) add deleteAtt flag (2) show attachmentContainer
    function deleteAttachment() {
        console.log('deleteAttachment()');
        $('#deleteAtt').val('1');
        $('#fileContainer').hide();
        $('#attachmentContainer').show();
    }
    
    function openSummaryModal() {
        var staff = `<?php echo $user['name']; ?>`;

        $("#summary-modal-subtitle").text(staff.toUpperCase());
        $('#summaryModal').modal('show');
    }












    $(".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/application/'); ?>" + user.id + '/' + year;
        });
    });

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

    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 openRequestModal() {
        $('#requestModal').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 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;
    }

    // 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' || mode == 'update') 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
    // 			await checkBackdated();   // Check if leave applied is backdated
    //             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) => {
    //             console.log(data);
    //             if ($.trim(data.status) == "success") {
    //                 console.log('displaying overlapped leaves error');
    //       			$.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();
    //                     //     }
    //                     // }
    //                     $("#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') + (v.period_from_id == 1 ? ' (Full day)' : (v.period_from_id == 2 ? ' (Half day - morning)' : ' (Half day - afternoon)')) + " to "
    //                         + moment(v.date_to, "YYYY-MM-DD").format('LL') + (v.period_to_id == 1 ? ' (Full day)' : (v.period_to_id == 2 ? ' (Half day - morning)' : ' (Half day - afternoon)')) + "." + "</li>");
    //                     $('#period').val(0);
    //                     $('#errorContainer').show();
    //       			});
    //                 console.log('error displayed');
    //             }
    //         }
    //     });
    // }

    // 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')
    //         },
    //         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.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 clearForm(e) {
    // 	$(e).parsley().reset();

    // 	$(e).find("select").val('').trigger('change');
    // 	$(e).find("input, textarea").val("");
    // }


    function prepareEdit(doingIt){
        if(doingIt){
            loadedApplication = null; // clear previous
            $('#pills-list-tab').addClass('disabled');
            $('#leave-type').prop('disabled', true);
        }else{
            $('#leave-type').val('').trigger('change');
            $('#pills-list-tab').removeClass('disabled');
            $('#leave-type').prop('disabled', false);
        }
    }
    
    function setupEdit(editing){
        console.log('loaded application with event: ' + JSON.stringify(loadedApplication));
        if(loadedApplication && editing){
            let editingDays = parseFloat(loadedApplication.days_applied);
            let editingType = loadedApplication.type_id;
            $('#badge-taken-type-' + editingType).html(parseFloat($('#badge-taken-type-' + editingType).html()) - editingDays);
            let tempDataSource = cal.getDataSource();
            cal.setDataSource(tempDataSource.filter(item => item.id != loadedApplication.event.id));
        }else if(loadedApplication && !editing){
            let editingDays = parseFloat(loadedApplication.days_applied);
            let editingType = loadedApplication.type_id;
            $('#badge-taken-type-' + editingType).html(parseFloat($('#badge-taken-type-' + editingType).html()) + editingDays);
            let tempDataSource = cal.getDataSource();
            tempDataSource.push(loadedApplication.event);
            cal.setDataSource(tempDataSource);
        }
    }

    // reroute new or load
    function reroute(event = null){
        if(event){
            if (event.type != 'applications')
                return console.log('Invalid action');
//                return alert('Got you! That is clearly not possible');
            if (event.status != 1)
                return loadImmutableModal(event.id);
            
            // if currently editing. clear first
            if(loadedApplication){
                setupEdit(false);
                loadedApplication = null;
                resetElements();
                prepareEdit(false); // if edit
            }

            // disable leave stype dd and nav tab
            prepareEdit(true);

            loadEditCard(event);
        }else{

        }
    }

    // card instead of modal
    function loadNewCard(date1, date2, isRange, periodArr1, periodArr2, isEL) {
        console.log('loadNewCard()');
        console.log(JSON.stringify(periodArr1));
        console.log(JSON.stringify(periodArr2));

        // clear
        $('#periodFrom').empty();
        $('#periodTo').empty();
        $('#periodOn').empty();

        // load date and period
        if (!isRange) {
            // display row with on
            $('#application-card input[name="dateOn"]').val(moment(date1).format('L'))
            for (var k in periodArr1) {
                $('#periodOn').append(`<option value="${k}">${periodArr1[k]}</option>`);
            }

            // show single container and hide range container
            $('#singleContainer').show();
            $('#rangeContainer').hide();
        } else {
            // display row with from and to. start 1/3 only. end 1/2 only
            $('#application-card input[name="dateFrom"]').val(moment(date1).format('L'))
            for (let k in periodArr1) {
                console.log(k);
                if (k != 2 && periodArr1[k])
                    $('#periodFrom').append(`<option value="${k}">${periodArr1[k]}</option>`);
            }
            $('#application-card input[name="dateTo"]').val(moment(date2).format('L'))
            for (let k in periodArr2) {
                console.log(k);
                if (k != 3 && periodArr2[k])
                    $('#periodTo').append(`<option value="${k}">${periodArr2[k]}</option>`);
            }

            // show range container and hide single container
            $('#singleContainer').hide();
            $('#rangeContainer').show();
        }

        // to make sure only one Full day allowed at one time
        if ($('#periodNdAdj').val() > 0) {
            console.log('period need adjustment. initial adjustment');
            if ($('#periodFrom > option').length > 1) {
                console.log('adjusting from');
                // $('#periodFrom').val() == 3 ? $('#periodFrom').prev().prop('selected', true) : $('#periodFrom').next().prop('selected', true);
                $('#periodFrom').val() == 3 ? $('#periodFrom').val(1) : $('#periodFrom').val(3);
            } else if ($('#periodTo > option').length > 1) {
                console.log('adjusting to');
                // $('#periodTo').val() == 3 ? $('#periodTo').prev().prop('selected', true).trigger('change') : $('#periodTo').next().prop('selected', true).trigger('change');
                $('#periodTo').val() == 2 ? $('#periodTo').val(1) : $('#periodTo').val(2);
            }
            // adjust duration
            adjdDuration = Number($('#duration').val()) - (0.5 * Number($('#periodNdAdj').val()));
            console.log('adjusted duration: ' + adjdDuration);
            $('#duration').val(adjdDuration);
        }

        // load leave type
        // isEL ? $('#leaveType').val(selectedLeaveObj.name + ' (Emergency)') : $('#leaveType').val(selectedLeaveObj.name);
        isEL ? $('#application-type').html(selectedLeaveObj.name + ' (Emergency)') : $('#application-type').html(selectedLeaveObj.name);

        // load exam 
        if (selectedLeaveObj.type_id == 7) {
            theExam = examList.find(elmt => elmt.id == selectedLeaveObj.paper_id);
            $('#exam-name').val(`${theExam.title} (${theExam.paper_code}) - ${moment(theExam.exam_date).format("MMM Do YYYY")}`);
            $('#exam-container').show();
        }

        // load user
        $('#userAddress').val(user.address);
        $('#userContact').val(user.phone);

        // attachment. trigger this only when cancel to allow editing
        // $('#leaveAttachment').val("");
        // $('#fileContainer').hide();
        // $('#attachmentContainer').show();

        // error
        $('#errorContainer').hide();
        $('#application-card-title').html('New Leave Application');
        $('#applicationCardSubmitBtn').attr('onclick', 'saveApplication()');
        $("#application-card").show();

    }

    // card instead of modal
    function loadEditCard(event = null, date1 = null, date2 = null, isRange = null, periodArr1 = null, periodArr2 = null, isEL = null) {
        console.log('loadEditCard() ' + (event ? event.id : loadedApplication.id));

        if (event && event.type != 'applications')
            return console.log('Invalid action');

        if (event && event.status != 1)
            return loadImmutableModal(event.id);

        if(!event){
            console.log('selected dates: ' + JSON.stringify(selectedDates));
        }

        // clear. apparently this will trigger onchange for dd
        $('#periodFrom').empty();
        $('#periodTo').empty();
        $('#periodOn').empty();

        // grab the application
            if(!loadedApplication){
                loadedApplication = (userApplications).find(ao => ao.id == event.id);
                $('#appId').val(event.id);
            }else{
                $('#appId').val(loadedApplication.id);
            }
            if (loadedApplication) {
                console.log('loaded application: ' + JSON.stringify(loadedApplication));
                if(!selectedDates){
                    // load selected dates
                    selectedDates = {
                        start: moment(loadedApplication.date_from, 'YYYY-MM-DD').format(),
                        end: moment(loadedApplication.date_to, 'YYYY-MM-DD').format()
                    };
                }
                
                console.log('pre selected dates: ' + JSON.stringify(selectedDates));

                // change the leave-type dd
                $('#leave-type').val(loadedApplication.allocation_id).trigger('change');
                // console.log('selected object: ' + JSON.stringify(selectedLeaveObj));

                console.log('post selected dates: ' + JSON.stringify(selectedDates));

                // load exam 
                if (loadedApplication.type_id == 7) {
                    theExam = examList.find(elmt => elmt.id == loadedApplication.exam_id);
                    $('#exam-name').val(`${theExam.title} (${theExam.paper_code}) - ${moment(theExam.exam_date).format("MMM Do YYYY")}`);
                    $('#exam-container').show();
                }

                // load attachement if any
                $('#leaveAttachment').val("");
                if (loadedApplication.file_name) {
                    baseUrl = window.location.origin;
                    console.log('base url: ' + baseUrl);
                    $('#fileBox a').attr('href', `${ baseUrl + '/spserp.dev/' + loadedApplication.file_location + loadedApplication.file_name }`);
                    // $('#fileBox a').append(`
                    //     <img src="${ baseUrl + '/' + loadedApplication.file_location + loadedApplication.file_name }" class="img-thumbnail" style="height:100px;"">`);
                    $('#fileContainer').show();
                    $('#attachmentContainer').hide();
                } else {
                    $('#fileContainer').hide();
                    $('#attachmentContainer').show();
                }

                // $('#duration').val(loadedApplication.days_applied);
                // loadedApplication.is_el == 1 ? $('#leaveType').val(allocations[i].name + ' (Emergency)') : $('#leaveType').val(allocations[i].name);
                // loadedApplication.is_el == 1 ? $('#application-type').html(allocations[i].name + ' (Emergency)') : $('#application-type').html(allocations[i].name);
                
                $('#leaveReason').val(loadedApplication.reason);
                $('#userAddress').val(loadedApplication.absent_address);
                $('#userContact').val(loadedApplication.absent_contact);
                $('#reliefPerson').selectpicker('val', [loadedApplication.absent_relief_id]);
                console.log('relief person id: ' + loadedApplication.absent_relief_id);

                // check if time editing
                if(date1 && date2){
                    // editing and new time selection. overwrite values

                    // load date and period
                    if (!isRange) {
                        // display row with on
                        $('#application-card input[name="dateOn"]').val(moment(date1).format('L'))
                        for (var k in periodArr1) {
                            $('#periodOn').append(`<option value="${k}">${periodArr1[k]}</option>`);
                        }

                        // show single container and hide range container
                        $('#singleContainer').show();
                        $('#rangeContainer').hide();
                    } else {
                        // display row with from and to. start 1/3 only. end 1/2 only
                        $('#application-card input[name="dateFrom"]').val(moment(date1).format('L'))
                        for (let k in periodArr1) {
                            console.log(k);
                            if (k != 2 && periodArr1[k])
                                $('#periodFrom').append(`<option value="${k}">${periodArr1[k]}</option>`);
                        }
                        $('#application-card input[name="dateTo"]').val(moment(date2).format('L'))
                        for (let k in periodArr2) {
                            console.log(k);
                            if (k != 3 && periodArr2[k])
                                $('#periodTo').append(`<option value="${k}">${periodArr2[k]}</option>`);
                        }

                        // show range container and hide single container
                        $('#singleContainer').hide();
                        $('#rangeContainer').show();
                    }

                    // to make sure only one Full day allowed at one time
                    if ($('#periodNdAdj').val() > 0) {
                        console.log('period need adjustment. initial adjustment');
                        if ($('#periodFrom > option').length > 1) {
                            console.log('adjusting from');
                            // $('#periodFrom').val() == 3 ? $('#periodFrom').prev().prop('selected', true) : $('#periodFrom').next().prop('selected', true);
                            $('#periodFrom').val() == 3 ? $('#periodFrom').val(1) : $('#periodFrom').val(3);
                        } else if ($('#periodTo > option').length > 1) {
                            console.log('adjusting to');
                            // $('#periodTo').val() == 3 ? $('#periodTo').prev().prop('selected', true).trigger('change') : $('#periodTo').next().prop('selected', true).trigger('change');
                            $('#periodTo').val() == 2 ? $('#periodTo').val(1) : $('#periodTo').val(2);
                        }
                        // adjust duration
                        adjdDuration = Number($('#duration').val()) - (0.5 * Number($('#periodNdAdj').val()));
                        console.log('adjusted duration: ' + adjdDuration);

                        $('#duration').val(adjdDuration);

                    }

                    console.log('date1=date2 selected dates: ' + JSON.stringify(selectedDates));
                    console.log('type name: ' + selectedLeaveObj.name);
                    isEL ? $('#application-type').html(selectedLeaveObj.name + ' (Emergency)') : $('#application-type').html(selectedLeaveObj.name);
                        
                } else{
                    // just editing. add event to loadedApplication
                    loadedApplication.event = event;
                    setupEdit(true, event);

                    slots = [];
                    slots[1] = 'Full day';
                    slots[2] = 'Half day (AM)';
                    slots[3] = 'Half day (PM)';

                    if (loadedApplication.date_from == loadedApplication.date_to) {
                        // same day
                        $('#application-card input[name="dateOn"]').val(moment(loadedApplication.date_from).format('L'))
                        $('#periodOn').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                        $('#periodOn').attr('disabled', true);
                        $('#singleContainer').show();
                        $('#rangeContainer').hide();
                    } else {
                        // multiple days
                        $('#application-card input[name="dateFrom"]').val(moment(loadedApplication.date_from).format('L'))
                        $('#periodFrom').append(`<option value="${loadedApplication.period_from_id}">${slots[loadedApplication.period_from_id]}</option>`);
                        $('#periodFrom').attr('disabled', true);
                        $('#application-card input[name="dateTo"]').val(moment(loadedApplication.date_to).format('L'))
                        $('#periodTo').append(`<option value="${loadedApplication.period_to_id}">${slots[loadedApplication.period_to_id]}</option>`);
                        $('#periodTo').attr('disabled', true);
                        $('#singleContainer').hide();
                        $('#rangeContainer').show();
                    }

                    $('#duration').val(loadedApplication.days_applied);
                    console.log('just editing selected dates: ' + JSON.stringify(selectedDates));
                    console.log('type name: ' + selectedLeaveObj.name);
                    loadedApplication.is_el == 1 ? $('#application-type').html(loadedApplication.leave_type + ' (Emergency)') : $('#application-type').html(loadedApplication.leave_type);
                }

                // error
                $('#errorContainer').hide();
                $('#application-card-title').html('Update Leave Application');
                $('#applicationCardSubmitBtn').attr('onclick', 'updateApplication()');
                $("#application-card").show();

            }

    }

</script>
