<section class="container collapse" id="tncInfo">
    <div class="jumbotron bg-white">
        <h6 class="text-danger">Transportation</h6>
        <ul>
            <li>
                5.3.1 A staff may travel using his own vehicle or other suitable means of
                transport as authorized by his Head of Department.
            </li>
            <li>
                5.3.2 If a staff travels using his own vehicle, he is entitled to mileage
                claims (Refer 4.3). A staff is only allowed to claim the shorter
                distance from either his office or home to the destination, and vice
                versa.
            </li>
            <li>
                5.3.3 If a staff travels by air, he is entitled for economy class tickets. In the
                event a ticket is not available for an economy class seat, and the staff
                is still required to travel, he may upgrade his ticket from an economy
                class seat to a business class seat, after obtaining approval from the
                management.
            </li>
            <li>
                5.3.4 If a staff travels by train, he is entitled to the first class tickets
            </li>
            <li>
                5.3.5 If a staff travels by bus, taxi, rented car or other public
                transportation, the fares shall be reimbursed based on receipts. 
            </li>
            <li>
                5.3.6 If a travel itinerary changes, the staff shall make the necessary
                arrangement to process the changes. Any unused or partially used
                tickets should be returned to Human Resource Department.
            </li>
            <li>
                5.3.7 A staff is not allowed to downgrade his entitlement to travel and
                make use of the difference in fares to support the traveling
                expenses for his spouse or family.
            </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>Transportation Fare<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 <span class="text-danger">*</span></b></label>
                </div>
                <div class="col-lg-4">
                    <input type="text" class="form-control claimdate" id="date_from" placeholder="Enter a valid date (<?php echo date('d-M-Y'); ?>)" required/>
                </div>
                <div class="col-lg-2">
                    <label><b>Transportation <span class="text-danger">*</span></b></label>
                </div>
                <div class="col-lg-4">
                    <select class="form-control" id="transportation" required>

                        <option value="3">Car Rental</option>
                        <option value="4">Flight</option>
                        <option value="5">Public Transport</option>
                        <option value="7">E Hailing</option>
                        <option value="8">Trains / Rails </option>

                        <?php //foreach($vehicles as $key => $value): ?>
                            <!-- <option value="<?php// echo $value['id']; ?>"><?php //echo $value['type']; ?></option> -->
                        <?php //endforeach; ?>
                    </select>
                </div>
            </div> 
            <br/>
            <div class="row">
                <div class="col-lg-2">
                    <label><b>Amount <span class="text-danger">*</span></b></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="number" class="form-control currency_input" id="amount" placeholder="0.00" required>
                    </div>
                    
                </div>
                <div class="col-lg-2">
                    <label><b>Description <span class="text-danger">*</span></b></label>
                </div>
                <div class="col-lg-4">
                    <textarea class="form-control" rows="5" id="description" placeholder="Enter description" required></textarea>
                </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-attachment">
                        <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="saveTravelingTransportation()" id="saveBtn"><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 date_is_valid = moment(date_from,'DD-MM-YYYY');

                if(date_is_valid.isValid())
                {
                    if(date_from)
                    {
                        fetchMovement(date_from);
                    }
                }else{
                    staff_movement = [];
                    iziToast.destroy();
                    iziToast.error({
                        position: 'bottomRight',
                        title: 'Failed',
                        message: 'Invalid 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)
                {
                    staff_movement = data.results;
                    createTable();
                },error:function(err)
                {
    
                }
            });

        }
    }

    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/72/'); ?>',
            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 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 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 removeStaffMovement(index)
    {
        staff_movement.splice(index,1);
        createTable();
    }

    function saveTravelingTransportation()
    {
        let is_required         = is_requiredInputFilled();
        let have_movement       = is_staffMovement();
        let have_attachment     = is_attachment();

        if(is_required && have_movement && have_attachment)
        {
            $('#saveBtn').attr('disabled',true);
            let url         = '<?php echo base_url('hr/api/claim/createTransportation/'); ?>';
            let type        = 'POST';
            let data        = {
                token:'<?php echo $token; ?>',
                date:$('#date_from').val(),
                transportation:$('#transportation').val(),
                amount:$('#amount').val(),
                description:$('#description').val(),
                staff_movements: staff_movement,
                attachments: attachment,
                claim_id: <?php echo $claim_id; ?>,
            }
            let redirect   = '<?php echo base_url('hr/claim/myClaimDetail/'.$year.'/'.$month.'/'.$user_id.'/'.$claim_id); ?>';
            // redirect = null;
            ajxRequest(url, type, data, redirect);
        }else{

            if(!is_required)
            {
                iziToast.destroy();
                iziToast.error({
                    title: 'Error',
                    message: 'Date, Transportation, Amount and Description are required'
                });
            }

            if(!have_movement)
            {
                iziToast.destroy();
                iziToast.error({
                    title: 'Error',
                    message: 'Unable to find any movements'
                });
            }

            if(!have_attachment)
            {
                iziToast.destroy();
                iziToast.error({
                    title: 'Error',
                    message: 'Unable to find any attachments'
                });
            }

        }
    }

    function is_requiredInputFilled()
    {
        let date            = $('#date_from').val();
        let transportation  = $('#transportation option:selected').val();
        let amount          = $('#amount').val();
        let description     = $('#description').val();

        if(date && transportation && amount && description)
        {
            return true;
        }else{
            console.log('Date : '+date);
            console.log('Transportation : '+transportation);
            console.log('Amount : '+amount);
            console.log('Description : '+description);

            iziToast.error({
                position: 'bottomRight',
                title: 'Failed',
                message: 'Date, Trasnportation , Amount and Description are required',
            });
            return false;
        }
    }

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

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

</script>