<style type="text/css">
    .off{
        cursor:no-drop;
    }
</style>

<section class="container collapse" id="tncInfo">
    <div class="jumbotron bg-white">
        <h6 class="text-danger">Meal Allowance</h6>
        <ul>
            <li>
                4.4.2 Staff who are required to do field works during office hour or out of office assignment within Klang Valley for continuously 4 hours excluding lunch time are entitle to meal allowance as follows:
                <table class="table-bordered" style="width:100%;">
                    <thead>
                        <tr>
                            <th class="p-3">Day</th>
                            <th class="p-3">Minimum Hours</th>
                            <th class="p-3">Rate</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="p-3" rowspan="2">Normal working days (Monday - Saturday)</td>
                            <td class="p-3">4 hours and above</td>
                            <td class="p-3">RM5.00</td>
                        </tr>
                        <tr>
                            <td class="p-3">8 hours and above</td>
                            <td class="p-3">RM10.00</td>
                        </tr>
                    </tbody>
                </table>
                (Refer to General HR Forms-Index No 4.0)
            </li>
        </ul>
        <small>Reference : <a href="http://salihin.noip.me/spserp/assets/uploads/hr/tnc/Claims__Allowances_-(Revision_2).pdf" target="_blank">Claims and Allowance (Revision no:2) Effective date:1st Janury 2018</a></small>
        <br>
        <small class="text-danger"><i>[Notes]: Not applicable for 4.4.1 (overtime claim) refer to <a href="<?php echo base_url('hr/overtime/yearlist'); ?>" target="_blank">Overtime list</a></i></small>
    </div>
</section>

<section class="container" style="padding-bottom: 2rem;">
	<div class="card no-shadow">

        <form method="post" action="" id="meal_claim_form">
            <div class="card-body">
                <div class="row">
                    <div class="col">
                        <h2><?php echo $Operation ?> Meal Allowance Claim <small>(Submission <?php echo date('F Y',strtotime('01-'.$month.'-'.$year)) ?>)</small></h2>
                    </div>
                    <div class="col-2 text-right">
                        <button class="btn btn-sm btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="" type="button" data-toggle="collapse" data-target="#tncInfo" data-original-title="Terms and Condition Reference">
                            <i class="fas fa-info"></i>
                        </button>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12 col-md-2">
                        <label for="job_id"><b>Job ID</b> <span class="text-danger">*</span></label>
                    </div>
                    <div class="col-12 col-md-10">
                        <select class="form-control select" name="job_id" id="job_id">
                            <option value="0" selected disabled>-- Select Job --</option>
                            <option value="-1">No Job ID</option>
                            <?php foreach ($mgs_job as $key => $row): ?>
                                <option value="<?php echo $row->job_id;?>">[<?php echo $row->job_id;?>] <?php echo $row->customerName;?> - <?php echo $row->description;?></option>
                            <?php endforeach ?> 
                        </select>
                    </div>
                </div><br>

                <div class="row">
                    <div class="col">
                        <div class="row form-group">
                            <div class="col-lg-4">
                                <label for="date"> Traveling Date <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <input type="text" class="form-control claimdate" name="date" id="date" autocomplete="off">
                                <small><span class="text-danger" id="notice_date"></span></small>
                            </div> 
                        </div>
                    </div>
                    <div class="col">
                        <div class="row">
                            <div class="col-lg-4">
                                <label for="amount_claim">Amount Claim <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <div class="input-group ">
                                    <div class="input-group-append">
                                        <span class="input-group-text">RM</span>
                                    </div>
                                    <input type="number" class="form-control bg-white" placeholder="Enter Amount Claim" name="amount_claim" id="amount_claim" onchange="formCheck()" onkeyup="formCheck()" disabled>
                                </div>
                                <small><span class="text-danger" id="notice_charge"></span></small>
                            </div>
                        </div>
                    </div>
                </div>

                <span class="text-danger font-italic"><small>[NOTES : ] * require</small></span>
                <br>
                <small><span class="text-danger font-italic" id="notice_attachment"></span></small>


                <div class="row">
                    <div class="col table-responsive">
                        <table class="table table-bordered" id="table-staffMovement">
                            <thead>
                                <tr>
                                    <th>Client</th>
                                    <th>Location</th>
                                    <th>Hours</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                
                            </tbody>
                        </table>   
                    </div>
                </div>

            </div>
            <div class="card-footer bg-white">
                <div class="btn-group float-right mb-3">
                    <button type="submit" class="btn btn-success" id="saveBtn" disabled><i class="fas fa-save"></i> Save</button>
                </div>
            </div>
        </form>

    </div>
</section>

<!-- modal add item -->
<div class="modal fade" id="modal_add_item" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Add Attachment (Meal Claim)</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="attachment_form" enctype="multipart/form-data">
                <div class="modal-body">

                    <div class="row form-group">
                        <div class="col">
                            <label for="item"><b>Description</b></label>
                        </div>
                    </div> 

                    <div class="row">
                        <div class="col">
                           <textarea class="form-control" rows="5" name="description" id="attachment_description"></textarea>
                        </div>
                    </div>

                    <br>
                    <div class="row form-group">
                        <div class="col">
                            <input type="file" class="form-control" id="upload-attachment">
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-success btn-block"><i class="fas fa-save"></i> Save</button>
                        </div>
                    </div>  

                </div>
            </form>
        </div>
    </div>
</div>
<!-- modal add item -->

<script>
    var staff_movement = [];
    var claim_year = <?php echo $this->uri->segment(4); ?>; //2018
    var claim_month = <?php echo $this->uri->segment(5); ?>; //8
    var date = new Date();
    var full_start_date = date.setFullYear(claim_year,claim_month-1 , 1);
    var start_claim     = moment(full_start_date).subtract(2,'months').startOf('month').format('DD-MM-YYYY');

    var full_end_date = date.setFullYear(claim_year,claim_month,1);
    var end_claim     = moment(full_end_date).subtract(2,'months').endOf('month').format('DD-MM-YYYY');

    $(document).ready(function(){


        if(claim_year == 2020 && claim_month == 2)
        {
            console.log('submission bulan dua claim');
            start_claim = '01-01-2020';
            end_claim = '31-01-2020';
        }


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

        $('#meal_claim_form').submit(function(event){
            event.preventDefault();
            is_pass     = formCheck();
            $('#saveBtn').attr('disabled','disabled');
            console.log('value for the '+is_pass);
         
            if (is_pass) {
                url     = '<?php echo base_url('hr/api/claim_v2/createMeal/'); ?>';
                type    = 'POST',
                data    = {
                    token       : '<?php echo $_SESSION['token']; ?>',
                    // form        : JSON.stringify(formIdToInputObject('#meal_claim_form')),
                    date        : $('#date').val(),
                    amount_claim: $('#amount_claim').val(),
                    year        : <?php echo ($this->uri->segment(4))?$this->uri->segment(4):''; ?>,
                    month       : <?php echo ($this->uri->segment(5))?$this->uri->segment(5):''; ?>,
                    user        : <?php echo ($this->uri->segment(6))?$this->uri->segment(6):''; ?>,
                    claim_id    : <?php echo ($this->uri->segment(7))?$this->uri->segment(7):''; ?>,
                    staff_movement : JSON.stringify(staff_movement),
                    job_id      : $('#job_id').val(),
                };
                redirect = '<?php echo base_url('hr/claim_v2/myClaimDetail').'/'.$this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6).'/'.$this->uri->segment(7).'/'; ?>';
                ajxRequest(url, type, data,redirect);
            }else{
                iziToast.warning({
                    position:'bottomRight',
                    message: 'Please enter valid travelling date'
                });
            }
        });
        
        $('#date').change(function(){
            let user_id = <?php echo $this->uri->segment(6); ?>;
            let token = '<?php echo $this->session->userdata('token'); ?>';
           
            $.ajax({
                url: '<?php echo base_url('hr/api_movement/getUserMovementByDate'); ?>',
                type: 'POST',
                data:{
                    token:token,
                    user:user_id,
                    date:$(this).val()
                },
                dataType: 'JSON',
                success: function(data){
                    console.log(data);

                    if(data.results.length == 0){
                        iziToast.error({
                            title: 'Error',
                            message: 'No movement'
                        });
                    }
                    staff_movement = data.results;
                    create_table_staff_movement();
                }
            });

        });

    });


    function formCheck()
    {
        let travelling_date = $('#date').val();
        let amount_claim    = $('#amount_claim').val();
        let job_id          = $("#job_id").val();

        if(job_id == 0 || job_id == '' || job_id == null){
            $('#saveBtn').attr('disabled','disabled');
            return false;
        }

        if(amount_claim > 0 && travelling_date != '')
        {
            //enable button submit
            $('#saveBtn').removeAttr('disabled');
            return true;
        }else{
            //disable button submit
            $('#saveBtn').attr('disabled','disabled');
            return false;
        }

        return false;
    }

    function create_table_staff_movement() 
    {
        var table   = $('#table-staffMovement').DataTable();
        let hour = 0;
        table.clear().draw();

        $.each(staff_movement,function(index,value){
            
            minus = 0;
            if((Date.parse('1/1/2020 '+value.timeOut) <= Date.parse('1/1/2020 13:00:00')) && ((Date.parse('1/1/2020 '+value.timeIn) >= Date.parse('1/1/2020 14:00:00')) || (Date.parse('1/1/2020 '+value.timeIn) >= Date.parse('1/1/2020 00:00:00')))){
                console.log('kene tolak satu');
                minus = 1; //tolak satu jam
            }else if(
                (Date.parse('1/1/2020 '+value.timeOut) >= Date.parse('1/1/2020 13:00:00')) && 
                (Date.parse('1/1//2020 '+value.timeOut) <= Date.parse('1/1/2020 14:00:00')) &&  //waktu keluar jatuh antara pukul 1 dan 2 
                (Date.parse('1/1/2020 '+value.timeIn) >= Date.parse('1/1/2020 14:00:00'))){ //waktu masuk lebih dari pukul 2
                console.log('kene tolak hasil tolak pukul dua dengan time out');
                let masa_end = moment(value.date+'T14:00:00');
                let masa_start = moment(value.date+'T'+value.timeOut);
                let difference = masa_end.diff(masa_start,'minutes');
                minus = difference/60;

            }else if(
                (Date.parse('1/1/2020 '+value.timeOut) >= Date.parse('1/1/2020 13:00:00')) && 
                (Date.parse('1/1//2020 '+value.timeOut) <= Date.parse('1/1/2020 14:00:00')) &&  //waktu keluar jatuh antara pukul 1 dan 2 
                (Date.parse('1/1/2020 '+value.timeIn) <= Date.parse('1/1/2020 14:00:00'))
            ){
                console.log('basically 0 hours sebab masa keluar dan masuk berada dalam waktu lunch hour');
            }else{
                console.log('tak yah tolak sebab masa keluar dan masuk bukan waktu lunch hour');
            }

            let start_time = moment(value.date+'T'+value.timeOut);
            let end_time = moment(value.date+'T'+value.timeIn);

            let minutes_differences = end_time.diff(start_time,'minutes');
            let hour_difference = end_time.diff(start_time,'hours');
            // hour += (minutes_differences/60) - minus;

            /* test new calculation */
            var startTime   = value.timeOut.split(":"); //16:30
            var endTime     = value.timeIn.split(":");  //01:00
            var hh;
            var mm;
            if(parseInt(startTime[0]) == 0) startTime[0] = 24;
            if(parseInt(endTime[0]) == 0) endTime[0] = 24;
            

            if(parseInt(startTime[0]) < parseInt(endTime[0]))
            {
                var h =  0;

                console.log("HS0 < HE0");
                if(parseInt(startTime[1]) < parseInt(endTime[1])){
                    console.log("MS0 < ME0");

                    hh = parseInt(endTime[0]) - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);
                }
                else if(parseInt(startTime[1]) > parseInt(endTime[1])){
                    console.log("MS0 > ME0");

                    hh = parseInt(endTime[0]) - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);

                    if(mm < 0){
                        hh = hh - 1;
                        mm = -1 * mm;
                    }
                }
                else if(parseInt(startTime[1]) == parseInt(endTime[1])) {
                    console.log("MS0 == ME0");

                    hh = parseInt(endTime[0]) - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);
                }
            }
            if(parseInt(startTime[0]) > parseInt(endTime[0]))
            {
                console.log("HS1 > HE1");
                
                var h =  parseInt(endTime[0]) + 24;
                if(parseInt(startTime[1]) < parseInt(endTime[1])){
                    console.log("MS1 < ME1");

                    hh = h - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);
                }
                else if(parseInt(startTime[1]) > parseInt(endTime[1])){
                    console.log("MS1 > ME1");

                    hh = h - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);

                    if(mm < 0){
                        hh = hh - 1;
                        mm = -1 * mm;
                    }
                }
                else if(parseInt(startTime[1]) == parseInt(endTime[1])) {
                    console.log("MS1 == ME1");

                    hh = h - parseInt(startTime[0]);
                    mm = parseInt(endTime[1]) - parseInt(startTime[1]);
                }
            }

            if(mm >= 30) mm = 5;


            var hour_minute = hh + '.' + mm;
            var total_hour = (hour_minute - minus);
            hour += total_hour;

            /* test new calculation */

            let client = '';
            let remove_button = `<div class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="remove_staff_movement(${index})"><i class="fas fa-trash-alt"></i></button></div>`;

            if(value.client_name != '' && value.client_name != null && value.client_name != undefined)
            {
                client += value.client_name;
            }

            if(value.address1 != '' && value.address1 != null && value.address1 != undefined)
            {
                client += '<br/>'+value.address1;
            }

            if(value.address2 != '' && value.address2 != null && value.address2 != undefined)
            {
                client += '<br/>'+value.address2;
            }

            if(value.city != '' && value.city != null && value.city != undefined)
            {
                client += '<br/>'+value.city;
            }

            table.row.add({
                0:client,
                1:value.destination,
                2:total_hour+' Hours',
                3:remove_button
            }).draw();
        });

        if(hour >= 8)
        {
            $('#amount_claim').val(10);
        }else if(hour >= 4){
            $('#amount_claim').val(5);            
        }else{
            $('#amount_claim').val(0);            
        }

        formCheck();

        console.log('create table from staff movement');
    }
    
    function remove_staff_movement(index)
    {

        toastConfirm('Are you sure you want to remove this item from your movement',function()
        {
            staff_movement.splice(index-1,1);
            create_table_staff_movement();
        });

    }
</script>