<section class="container collapse" id="tncInfo">
    <div class="jumbotron bg-white">
        <h6 class="text-danger">Toll Charges</h6>
        <ul>
            <li>5.7.2 Staff will be reimbursed on the actual amount of toll charges incurred based on receipts/tickets while on official business trip</li>
        </ul>
        <small>Reference : <a href="http://salihin.noip.me/spserp/assets/uploads/hr/tnc/Travel_-_(Revision_2).pdf" target="_blank">Local and Business Travel (Revision no: 2) Effective date : 1st January 2018</a></small>
    </div>
</section>

<section class="container">
    <div class="card no-shadow">
        <div class="card-body">
            <div class="row">
                <div class="col">
                    <h2>Toll Charges <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>
    </div>
</section>

<section class="container mb-5">
    <div class="card no-shadow">
        <div class="card-body">

            <div class="row">
                <div class="col-lg-2">
                    <label for="job_id"><b>Job ID</b> <span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-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-lg-2">
                    <label><b>Date</b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <input type="text"  class="form-control claimdate" id="date_from" placeholder="Enter valid date (<?php echo date('d-m-Y'); ?>)"/>
                </div>

                <div class="col-lg-2">
                    <label><b>Amount</b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1">RM</span>
                        </div>
                        <input type="text" class="form-control currency_input" id="amount" placeholder="0.00"/>
                    </div>
                    
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <label><b>Staff movements</b></label>
                    <div class="row">
                        <div class="col text-right pr-4">
                            <!-- <button class="btn btn-primary btn-sm"><i class="fas fa-sync-alt"></i></button> -->
                        </div>
                    </div>
                    <table class="table table-bordered" id="table-staffMovement">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Movement Type</th>
                                <th>Client</th>
                                <th>Location</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>


            <div class="row">
                <div class="col">
                    <label><b>Attachments</b></label>
                    <div class="row">
                        <div class="col text-right pr-4">
                            <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#mdl-attachment"><i class="fas fa-plus"></i></button>
                        </div>
                    </div>
                    <table class="table table-bordered" id="table-attachments">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>


            <div class="row">
                <div class="col text-right">
                    <button class="btn btn-success" onclick="createTollCharges()" id="btnSave"><i class="fas fa-save"></i> Save</button>
                </div>
            </div>


        </div>
    </div>
</section>


<!-- attachements modal -->
<div class="modal fade" id="mdl-attachment" tabindex="-1" role="dialog" >
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Uploading Attachments</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="row">
            <div class="col">
                <label><b>File</b></label>
                <input type="file" class="form-control" id="attachments_doc">
            </div>
        </div>
        <div class="row">
            <div class="col">
                <label><b>Description</b></label>
                <textarea cols="30" rows="10" class="form-control" id="attachment-description"></textarea>
            </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="uploadAttachment()">Save changes</button>
      </div>
    </div>
  </div>
</div>
<!-- attachments modal -->

<script>
    var staff_movement  = [];
    var attachment      = [];

    var claim_year      = <?php echo $year; ?>; //2018
    var claim_month     = <?php echo $month; ?>; //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: true,
                startDate :start_claim,
                endDate:end_claim
            }
        );

        $('#date_from').change(function()
            {
                let date_from   = $('#date_from').val();
                let from_is_valid = moment(date_from,'DD-MM-YYYY');

                if(from_is_valid.isValid())
                {
                    if(date_from)
                    {
                        fetchMovement(date_from);
                    }
                }else{
                    iziToast.destroy();
                    iziToast.error({
                        title: 'Error',
                        message: 'Please enter a valid date.'
                    });
                }
            }
        );

    });

    function fetchMovement(date_from)
    {
        if(date_from)
        {
            let url = '<?php echo base_url('hr/api_movement/getUserMovementBetweenDate/'); ?>';
            let data = 
            {
                token:'<?php echo $token; ?>',
                date_from:date_from,
                date_to:date_from,
                user_id:<?php echo $user_id; ?>,
            }

            $.ajax({
                url: url,
                type: 'POST',
                data:data,
                dataType: 'JSON',
                success: function(data)
                {
                    if(data.results)
                    {
                        staff_movement = data.results;
                    }else{
                        staff_movement = [];
                    }
                    createTable();
                },error:function(err)
                {
    
                }
            });

        }
    }

    function createTable()
    {
        var table   = $('#table-staffMovement').DataTable();
        table.clear().draw();

        $.each(staff_movement,function(index,value){
            table.row.add({
                0:moment(value.movement_date).format('DD/MM/YYYY'),
                1:value.movement_type,
                2:value.client,
                3:value.destination,
                4:'<button class="btn btn-danger btn-sm" onclick="removeStaffMovement('+index+')" ><i class="fas fa-trash-alt"></i></button>',
            }).draw();
        });
    }

    function removeStaffMovement(index)
    {
        staff_movement.splice(index,1);
        createTable();
    }


    function uploadAttachment()
    {
    
        formData = new FormData();
        formData.append('files',$('#attachments_doc').prop('files')[0]);
        formData.append('description',$('#attachment-description').val());

        $.ajax({
            url: '<?php echo base_url('hr/claim/addAttachment/76/'); ?>',
            type: "POST",             
            data: formData, 
            contentType:false,       
            cache: false,             
            processData:false,
            dataType: 'JSON',
            success: function(data)
            {
                console.log('uploading attachments');
                if(data.status == false)
                {
                    iziToast.error({
                        position: 'bottomRight',
                        title: 'Uploading Attachments Failed',
                        message: data[0].error,
                    });
                }else
                {
                    attachment.push(data);
                    createTableAttachment();
                }
            }
        });

    }

    function createTableAttachment()
    {
        var table = $('#table-attachments').DataTable();
        table.clear().draw();

        $.each(attachment,function(index,value){

            let action = `<button class="btn btn-danger btn-sm" onclick="removeAttachment(${index})">
                                <i class="fas fa-trash-alt"></i>
                            </button>`;
            table.row.add({
                0:value.orig_name,
                1:value.description,
                2:action
            }).draw();
        });

    }

    function removeAttachment(index)
    {   
        attachment.splice(index,1);

        createTableAttachment();
        console.log('attachment i d: '+index);
    }

    function createTollCharges()
    {
        let required        = is_required();
        let have_movement   = is_staffMovement();
        let have_attachment = is_attachment();

        if(required && have_movement && have_attachment)
        {
            $('#btnSave').attr('disabled',true);
            let url = '<?php echo base_url('/hr/api/claim_v2/createToll/'); ?>';
            let data = 
            {
                token:'<?php echo $token; ?>',
                date:$('#date_from').val(),
                amount:$('#amount').val(),
                staff_movement:staff_movement,
                attachment:attachment,
                claim_id:<?php echo $claim_id; ?>,
                user_id:<?php echo $user_id?>,
                job_id:$('#job_id').val(),
            }
            let redirect = '<?php echo base_url('/hr/claim_v2/myClaimDetail/'.$year.'/'.$month.'/'.$user_id.'/'.$claim_id); ?>';
            // redirect = null;
            ajxRequest(url, 'POST', data, redirect);


        }
    }

    function is_required()
    {
        let date    = $('#date_from').val();
        let amount  = $('#amount').val();
        let job_id  = $('#job_id').val();

        if(job_id == 0 || job_id == '' || job_id == null){
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Job ID are required',
            });
            return false;
        }

        if(date && amount)
        {
            return true;
        }else{
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Date and amount are required',
            }); 
            return false;
        }
    }

    function is_staffMovement()
    {
        if(staff_movement.length > 0)
        {
            return true;
        }else{
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Unable to find any movements',
            });
            return false;
        }
    }

    function is_attachment()
    {
        if(attachment.length > 0)
        {
            return true;
        }else{
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Unable to find any attachments',
            });
            return false;
        }
    }
</script>