<section class="container collapse" id="tncInfo">
    <div class="jumbotron bg-white">
        <h6 class="text-danger">Trainer / Facilitator</h6>
        <ul>
            <li>
                4.13.1 Staff who conducts training for In House training or external
                public training will be eligible to claim for allowance RM200.00
                per session (min. 4 hours per day). The allowance will reimburse
                to staff in monthly claim.
            </li>
        </ul>
        <small>Reference : <a href="http://salihin.noip.me/spserp/assets/uploads/hr/tnc/Claims__Allowances_-(Revision_2).pdf" target="_blank">Claims and Allowances (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>Trainer / Facilitator <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><b>Date</b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <input type="text"  class="form-control claimdate" id="training_date" placeholder="Enter valid date (<?php echo date('d-m-Y'); ?>)"/>
                </div>
            </div>
            <br/>

            <div class="row">
                <div class="col-lg-2">
                    <label><b>Start : </b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <input type="text"  class="form-control timepicker" id="training_start" placeholder="Enter valid time (<?php echo date('h:i A'); ?>)" />
                </div>

                <div class="col-lg-2">
                    <label><b>End : </b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <input type="text" class="form-control timepicker" id="training_end"  placeholder="Enter valid time (<?php echo date('h:i A',strtotime(date('d-m-Y H:i:s') . "+ 4 hours")); ?>)"  />
                </div>
            </div>
            <br/>

            <div class="row">
                <div class="col-lg-2">
                    <label><b>Training Title</b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <input type="text" class="form-control" id="training_title" placeholder="Enter training title"/>
                </div>
                <div class="col-lg-2">
                    <label><b>Type</b><span class="text-danger">*</span></label>
                </div>
                <div class="col-lg-4">
                    <select class="form-control" id="training_type" >
                        <option value="0" >In House Training</option>
                        <option value="1" >External Training</option>
                    </select>
                </div>
            </div>
            <br>

            <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-attachment" >
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>

            <div class="row d-none" id="staff-movement-section">
                <div class="col table-responsive">
                    <label><b>Staff Movement</b></label>
                    <table class="table table-bordered" id="table-movement">
                        <thead>
                            <tr>
                                <th>Movement Type</th>
                                <th>Client</th>
                                <th>Time Out</th>
                                <th>Time In</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="row">
                <div class="col text-right">
                    <button class="btn btn-success" onclick="createTrainer()" 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 attachment      = [];    
    var movement_table  = [];
    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
        });

        $('#training_date').change(function(){
            let date_from   = $('#training_date').val();
            let from_is_valid = moment(date_from,'DD-MM-YYYY');
            if(!from_is_valid.isValid())
            {
                iziToast.destroy();
                iziToast.error({
                    title: 'Error',
                    message: 'Please enter a valid date.'
                });
            }else{
                fetchMovement();
            }
        });

        $('#training_type').change(function() {
            let choice = $(this).val();
            if(choice == 0)
            {
                $('#staff-movement-section').addClass('d-none');
            }else{
                $('#staff-movement-section').removeClass('d-none');
            }
        });
    });

    function create_table_movement() 
    {
        var table_movement = $('#table-movement').DataTable();
        table_movement.clear().draw();

        if(movement_table.length > 0)
        {
            $.each(movement_table,function(index,movement){
                table_movement.row.add({
                    0:movement.movement_type,
                    1:movement.client+' '+movement.destination,
                    2:movement.timeOut,
                    3:movement.timeIn,
                }).draw();
            });
        }
    }

    function fetchMovement() 
    {
        movement_table = [];create_table_movement();
        let movement_date = $('#training_date').val();
        if(movement_date)
        {
            let url = '<?php echo base_url('hr/api_movement/getUserMovementBetweenDate/'); ?>';
            let data = 
            {
                token:'<?php echo $token; ?>',
                date_from:movement_date,
                date_to:movement_date,
                user_id:<?php echo $user_id; ?>,
            }

            $.ajax({
                url: url,
                type: 'POST',
                data:data,
                dataType: 'JSON',
                success: function(data)
                {
                    console.log(data);
                    if(data.results != null)
                    {
                        movement_table = data.results;
                        create_table_movement();
                    }else{
                        console.log('results empty');
                    }
                },error:function(err)
                {
                    console.log('error wey');
                    return false;
                }
            });


        }

    }


    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/83/'); ?>',
            type: "POST",             
            data: formData, 
            contentType:false,       
            cache: false,             
            processData:false,
            dataType: 'JSON',
            success: function(data)
            {
                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-attachment').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 createTrainer()
    {
        let requiredFills   = is_requiredFills();
        let is_upload       = is_attachment();

        if(requiredFills && is_upload)
        {
            $('#btnSave').attr('disabled',true);
            let url = '<?php echo base_url('/hr/api/claim/createTrainer/'); ?>';
            let data = 
            {
                token:'<?php echo $token; ?>',
                date:$('#training_date').val(),
                start:$('#training_start').val(),
                end:$('#training_end').val(),
                title:$('#training_title').val(),
                type:$('#training_type').val(),
                attachment:attachment,
                movements:movement_table,
                claim_id:<?php echo $claim_id; ?>,
                user_id:<?php echo $user_id?>
            }

            let redirect = '<?php echo base_url('/hr/claim/myClaimDetail/'.$year.'/'.$month.'/'.$user_id.'/'.$claim_id); ?>';
            // redirect = null;
            ajxRequest(url, 'POST', data, redirect);
        }
    }

    function is_requiredFills()
    {
        let date            = $('#training_date').val();
        let start           = $('#training_start').val();
        let end             = $('#training_end').val();
        let training_title  = $('#training_title').val();
        let type            = $('#training_type').val();

        if(date && start && end && training_title && type)
        {
            return true;
        }else{
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Date, Start, End, Title and Type are required',
            });
            return false;
        }
    }

    function is_attachment()
    {
        if(attachment.length > 0)
        {
            return true;
        }else{
            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Attachment is required',
            });
            return false;
        }
    }
</script>