<style>
    #map {height: 300px;}
    .search-wrapper{
        border-radius: 5px;
        border: .5px solid #dedede;
      }

      .cursor-pointer{
        padding-left: 0px;
        cursor: pointer;
      }

      ul{
        list-style:none;
        padding-left: 10px;
        padding-right: 10px;
        /*box-shadow: 0px 3px rgba(0,0,0,0.3);*/
      }

      li{
        display: block;
        padding: 10px;
        /*border-bottom: 1px solid #dedede;*/
      }

      li:hover{
        transition: all 0.5s ease;
        background-color: #ccc;
        opacity: .65;
      }

      .scrollbar
        {
            margin-left: 30px;
            float: left;
            height: 300px;
            width: 65px;
            background: #F5F5F5;
            overflow-y: scroll;
            margin-bottom: 25px;
        }
</style>
<section class="collapse container" id="tncInfo">
    <div class="jumbotron bg-white">
        <h6 class="text-danger">Traveling</h6>

        <label><b>Mileage Claims</b></label>
        <ul>
            <li>
                4.2.1 Staff who are authorized to travel in their own vehicles on official Company business may claim mileage at the following rates: 
                <table class="table-bordered" width="100%">
                    <thead>
                        <tr>
                            <th>Type of Transport</th>
                            <th>Rate of Claim</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Motorcar</td>
                            <td>
                                RM 0.60 per km for the first 500 km <br>
                                RM 0.55 per km for the next 150 km <br/>
                                RM 0.50 per km for the next 150 km <br>
                                Remainder RM0.25 per km
                            </td>
                        </tr>
                        <tr>
                            <td>Motorcycle</td>
                            <td>
                                RM 0.30 per km
                            </td>
                        </tr>
                    </tbody>
                </table>
            </li>
            <li>
                4.2.2 Staffs who are authorized to travel in company car on official company business may claim as per petrol sheets provided that the claim is equivalent with the location.
            </li>
            <li>
                4.2.3 Staffs who travel by public transport can claim for taxi fare or any other type of public transport for the distance traveled provided the amount claimed is reasonable.
            </li>
            <li>
                4.2.4 SALIHIN reserves the right to revise the mileage claim rate from time to time as determine by the management.(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">Claim and Allowances (Revision no : 2 ) Effective date : 1st January 2018</a></small>
    </div>
</section>

<section class="container" style="padding-bottom: 2rem;">
	<div class="card no-shadow">
        <form method="post" id="travelling_form">
            <div class="card-body">
            
                <div class="row">
                    <div class="col">
                        <h2><?php echo $Operation ?> Mileage 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>
                
                <hr>
                <div class="row d-none">   
                    <div class="col">
                        <label>Start Date</label>
                        <input type="text" class="form-control claimdate">
                    </div>
                    <div class="col">
                        <label>End Date</label>
                        <input type="text" class="form-control claimdate">
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <div class="row form-group">
                            <div class="col-lg-4">
                                <label for="job_id"><b>Job ID</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <select class="form-control select" name="job_id" id="job_id" onchange="formCheck()" onkeyup="formCheck()">
                                    <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>
                    </div>
                </div><br>

                <div class="row">
                    <div class="col">
                        <!-- travelling date -->
                        <div class="row form-group">
                            <div class="col-lg-4">
                                <label for="date"><b>Travelling Date</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <input type="text" class="form-control claimdate" name="date" id="date" autocomplete="off" onchange="reqStaffMovementData()" onkeyup="reqStaffMovementData()" value="<?php echo date('d-m-Y'); ?>">
                                <small><span class="text-danger" id="notice_date"></span></small>
                            </div> 
                        </div>
                        <!-- travelling date  -->
                    </div>
                    <div class="col d-none">
                        <!-- client / travelling -->
                        <div class="row">
                            <div class="col-lg-4">
                                <label for="client"><b>Client</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <select class="form-control select" name="client" id="client" onchange="formCheck()">
                                    <option value="-1" selected disabled>Select Client/ Location</option>
                                    <?php foreach ($clients as $key => $row ): ?>
                                        <option value="<?php echo $row->customer_id;?>"><?php echo $row->name;?></option>
                                    <?php endforeach ?>
                                        <option value="-2">Others</option>                                 
                                </select>
                                <small><span class="text-danger" id="notice_client"></span></small>

                            </div> 
                        </div>
                        <!-- client / travelling-->
                    </div>
                </div>

                <div class="row d-none">
                    <div class="col">
                        <!-- task -->
                        <div class="row form-group">
                            <div class="col-lg-4">
                                <label for="task"><b>Task</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <textarea class="form-control" name="task" id="task" cols="30" rows="3" placeholder="Enter Task Description" onchange="formCheck()" onkeyup="formCheck()">Enter task description</textarea>
                            </div> 
                        </div>
                        <!-- task -->
                    </div>
                    <div class="col">
                        <!-- zone -->
                        <span class="text-danger font-italic"><small>[NOTES : ] * require</small></span>
                        <br>
                        <small><span class="text-danger font-italic" id="notice_items"></span></small>
                        <!-- zone -->
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <!-- staff movement -->
                        <div class="card no-shadow">
                            <div class="card-body">
                                <div class="row mb-2">
                                    <div class="col">
                                        <h5><b>Staff Movement</b></h5>
                                    </div>
                                    <div class="col text-right">
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-primary btn-sm" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Refresh Movement" onclick="reqStaffMovementData();"><i class="fas fa-sync-alt"></i></button>
                                            <!-- 
                                            <a type="button" class="btn btn-primary btn-sm text-white" 
                                                data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Add Movement" 
                                                href="<?php echo base_url('hr/StaffMovement/create'); ?>" target="_blank">
                                                    <i class="fas fa-plus"></i>
                                            </a> 
                                            -->
                                        </div>
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered" width="100%" id="table-staffmovement">
                                        <thead>
                                            <th class="text-center">Date</th>
                                            <th class="text-center">Movement Type</th>
                                            <th class="text-center">Client</th>
                                            <th class="text-center">Location</th>
                                            <th class="text-center">Action</th>
                                        </thead>
                                        <tbody id="table-staff-movement-body">
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <!-- staff movement -->
                    </div>
                </div>
                <br>

                <div class="row d-none">
                    <div class="col">
                        <!-- items -->
                        <div class="card no-shadow">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col">
                                        <h5><b>Items</b></h5>
                                    </div>
                                    <div class="col text-right">
                                         <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#modal_add_item" type="button" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Add Items"><i class="fas fa-plus"></i></button>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-hover" id="tbl-item" width="100%">
                                                <thead>
                                                    <tr>
                                                        <th rowspan="2" class="text-center">Item</th>
                                                        <th rowspan="2" class="text-center">Description</th>
                                                        <th colspan="2" class="text-center">Units of Measurement </th>
                                                        <th rowspan="2" class="text-center">Total Amount</th>
                                                        <th rowspan="2" class="text-center">Action</th>
                                                    </tr>
                                                    <tr>
                                                        <th class="text-center">Measurement</th>
                                                        <th class="border-right text-center">Unit</th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- items -->
                    </div>
                </div>
                <br>

                <div class="row">
                    <div class="col">
                        <div class="card no-shadow">
                            <div class="card-body">
                                <!-- travel route -->
                                <div class="row">
                                    <div class="col">
                                        <h5><b>Travel Route</b></h5>
                                    </div>
                                    <div class="col text-right">
                                        <button class="btn btn-primary btn-sm" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Add stop points" type="button" data-toggle="modal" data-target="#mdl-route" onclick="openTravellingModal()">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col table-responsive">
                                        <table class="table table-bordered" id="tbl-route">
                                            <thead>
                                                <tr>
                                                    <th>From</th>
                                                    <th>To</th>
                                                    <th>Distance</th>
                                                    <th>Vehicle</th>
                                                    <th>Action</th>
                                                </tr>   
                                            </thead>
                                            <tbody>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <!-- travel route -->
                            </div>
                        </div>
                    </div>
                </div>
                <br>

                <div class="row">
                    <div class="col">  
                        <!-- attachments -->
                        <div class="card no-shadow">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col">
                                        <h5><b>Attachments</b></h5>
                                    </div>
                                    <div class="col text-right">
                                        <button class="btn btn-primary btn-sm" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Add attachments" type="button" data-toggle="modal" data-target="#mdl-attachments">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <table class="table table-bordered" id="tbl-attachment">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Description</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>

                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- attachments -->
                    </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">
                        <i class="fas fa-save"></i> Save
                    </button>
                </div>
            </div>
        </form>
    </div>
</section>

<!-- modal route -->
<div class="modal" id="mdl-route" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document" style="max-width:90%;">
    <div class="modal-content" >
      <div class="modal-header">
        <h5 class="modal-title">Add route stop point </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="routeForm">

            <div class="row">
                <div class="col">
                    <input type="hidden" class="form-control" id="travelId">
                </div>
            </div>

            <div class="row">
                <div class="col-lg-6">
                    <div class="row">        
                        <div class="col-lg-4">
                            <b>From</b> <span class="text-danger">*</span>
                        </div>
                        <div class="col-lg-8">
                            
                            <div class="search-wrapper">
                                
                              <input type="text" id="search_departure_from" name="search_departure_from" onkeyup="findSuggestion()" onchange="formCheck()" class="form-control form-control-sm" width="100%;" autocomplete="off">
                              <!-- <ul id="result_departure_from" style="margin-bottom:0px;height:20vh;border:1px solid #dedede;overflow-y:scroll;"></ul> -->
                                <ul 
                                    id="result_departure_from"  
                                    style="margin-bottom:0px;border:1px solid #dedede;overflow-y:scroll;">
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="row">
                        <div class="col-lg-4">
                            <b>To</b> <span class="text-danger">*</span>
                        </div>
                        <div class="col">
                            <div class="search-wrapper" style="">
                              <input type="text" id="search_departure_to" name="search_departure_to" onkeyup="findSuggestion2()" onchange="formCheck()" class="form-control form-control-sm" width="100%;" autocomplete="off">
                              <ul id="result_departure_to" style="margin-bottom:0px;border:1px solid #dedede;overflow-y:scroll;"></ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col mt-3">
                    <div class="row">
                        <div class="col-lg-4">
                            <b>Distance</b> 
                        </div>
                        <div class="col">
                            <div class="input-group mb-3">
                              <input type="hidden" class="form-control form-control-sm" id="departure_distance">
                              <input type="text" class="form-control form-control-sm" id="hidden_departure_distance" name="departure_distance">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col">
                    <div class="row">
                        <div class="col-lg-4 mt-3">
                            <b>Travelling Type</b> <span class="text-danger">*</span>
                        </div>
                        <div class="col mt-3">
                            <select class="form-control" name="vehicle_departure" id="vehicle_departure">
                                <?php foreach ($vehicles as $key => $vehicle): ?>
                                    <?php if($key <= 1):?>
                                        <option value="<?php echo $vehicle['id']; ?>" data-vehicle="<?php echo $vehicle['type'];?>"><?php echo $vehicle['type']; ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <br>
        
            <div class="row">
                <div class="col-lg-4 ml-auto">
                    <button class="btn btn-success btn-sm btn-block" onclick="addStopPoint()" type="button">
                        <i class="fas fa-plus"></i>Add Stop Points 
                    </button>
                </div>
            </div>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- modal route -->

<!-- modal mdl-attachment-->
<div class="modal" id="mdl-attachments" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
        <form id="addAttachmentsForm">
          <div class="modal-header">
            <h5 class="modal-title">Add 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-md-3">
                    <label><b>Attachments</b></label>
                </div>
                <div class="col">
                    <input type="file" class="form-control" id="attachment">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-3">
                    <label><b>Description</b></label>
                </div>
                <div class="col">
                    <textarea class="form-control" id="descriptionAttachments"></textarea>
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Save changes</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          </div>
        </form>

    </div>
  </div>
</div>
<!-- modal mdl-attachment-->

<script>
    var claim_date;
    var staff_movement  = []; 
    var items           = [];
    var route           = [];
    var attachment_list = [];

    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: true,
            startDate :start_claim,
            endDate:end_claim
        });

        jQuery.support.cors = true; 
        $('#travelling_form').submit(function(event)
        {
            event.preventDefault();
            is_pass     = formCheck();
            job_id      = $('#job_id').val();

            if (is_pass) {
                url     = '<?php echo base_url('hr/api/claim_v2/createTravelClaim/'); ?>';
                type    = 'POST',
                data    = {
                    token               : '<?php echo $_SESSION['token']; ?>',
                    form                : JSON.stringify(formIdToInputObject('#travelling_form')),
                    items               : items,
                    staff_movements     : staff_movement,
                    routes              : route,
                    attachments         : attachment_list,
                    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):''; ?>,
                    job_id              : job_id,
                };

                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: 'make sure all forms have been filled and upload your attachments'
                });
            }
        });

        $('#additionalItemForm').submit(function(event)
        {
            event.preventDefault();
            var input = formIdToInputObject('#additionalItemForm');
            $("#additionalItemForm")[0].reset();
            items.push(input);
            populateItems();
            $('#modal_add_item').modal('toggle');
        });

        $('#editItemModal').submit(function(event)
        {
            event.preventDefault();
            let index = $('#indexEdit').val();
            let item = $('#itemEdit').val();
            let description = $('#descriptionEdit').val();
            let measurement = $('#measurementEdit').val();
            let amount = $('#amountEdit').val();
            let unit = $('#unitEdit').val();


            items[index].amount = amount;
            items[index].description = description;
            items[index].item = item;
            items[index].measurement = measurement;
            items[index].unit = unit;

            populateItems();
            $('#modal_edit_item').modal('toggle');
        });

        $('#addAttachmentsForm').submit(function(event)
        {
            event.preventDefault();
            $('#mdl-attachments').modal('toggle');
            uploadAttachment('#attachment','#descriptionAttachments',function(res)
            {
                let json    = JSON.parse(res);
                if(json.status == false){
                    iziToast.error({
                        position: 'bottomRight',
                        title: 'Failed',
                        message: 'Failed to upload attachment'
                    });
                }else{
                    attachment_list.push(res);
                    fillTableAttachments();
                    formCheck();
                }
            });
            $('#addAttachmentsForm').trigger('reset');
        });

    });

    function itemCheck()
    {
        if (items.length > 0) {
            $('#notice_items').empty();
            return true;
        }else{
            $('#notice_items').html('Please add items to claims');
            return false;
        }
    }

    function createTableMovement() 
    {
        var table = $('#table-staffmovement').DataTable();
        table.clear().draw();
        $.each(staff_movement,function(index,value){
            let template =  `<div class="btn-group">
                                <button class="btn btn-danger btn-sm" 
                                    data-trigger="hover" data-tooltip="tooltip" title="" 
                                    data-original-title="Remove Movement From Claim" type="button" data-index="${index}" onclick="removeStaffMovement(this)">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                            `;
            
            table.row.add({
                    0 : value.date,
                    1 : value.type,
                    2 : value.title,
                    3 : value.destination, 
                    4 : template, 
                }).draw();
        });
    }

    function reqStaffMovementData() 
    {
        var input = formIdToInputObject('#travelling_form');
        claim_date = input.date;

        staff_movement = [];
        $.ajax({
            url : '<?php echo base_url('hr/api_movement/getUserMovementBetweenDate'); ?>',
            type: 'POST',
            data:{
                token: '<?php echo $_SESSION['token']; ?>', 
                date_from: claim_date,
                date_to:claim_date,
                user_id:<?php echo $_SESSION['user']['id']; ?>,
            },
            dataType: 'JSON',
            success: function(data){
                
                console.log(data);
                if(data.results != null)
                {
                    $.each(data.results,function(index,value){
                        let movement = 
                        {
                            date:value.movement_date,
                            type:value.movement_type,
                            title:value.client,
                            destination:value.destination
                        }
                        staff_movement.push(movement);
                    });

                    createTableMovement();
                }else{
                    var table = $('#table-staffmovement').DataTable();
                    table.clear().draw();
                }
            },
            error: function(){

            }
        });
        formCheck();
    }

    function removeStaffMovement(elem) 
    {
        toastConfirm('Are you sure you want to remove this movement ?',function() {
            staff_movement.splice($(elem).data('index'),1);
            createTableMovement();
        });
    }

    function formCheck()
    {
        iziToast.destroy();
        var is_filled       = true;
        var input           = formIdToInputObject('#travelling_form');
        let errors          = [];
        let client          = $('#client').val();
        let job_id          = $('#job_id').val();

        //validation job_id
        if(!job_id)
        {
            let error_message = 'Job ID cannot be empty';
            errors.push(error_message);
            is_filled = false;
        }

        //checking if all input filled
        $.each(input, function(index,value)
        {
            if(value.length <= 0){
                let error_message = index+' cannot be empty';
                errors.push(error_message);
                is_filled = false;
            }
        });

        //validating date
        if(input.date.length > 0)
        {
            if(moment(input.date,'DD-MM-YYYY',true).isValid() == false){
                is_filled = false;
                var error = 'Please enter a valid date format : day-month-year (<?php echo date('d-m-Y'); ?>) ';
                errors.push(error);

                $('#notice_date').html();
            }else{
                $('#notice_date').empty();
                claim_date = input.date;
            }
        }

        //validation client
        // if(!client)
        // {
        //     let error_message = 'Client cannot be empty';
        //     errors.push(error_message);
        //     is_filled = false;
        // }
        
        if(staff_movement.length <= 0)
        {
            errors.push('Staff Movement cannot be empty');
            is_filled = false;
        }

        // if(attachment_list.length <= 0)
        // {
        //     errors.push('Please upload some attachments ');
        //     is_filled = false;
        // }

        if(is_filled)
        {
            $('#saveBtn').removeAttr('disabled');
        }else{
            let error_message = '';
            $.each(errors,function(index,value){
                error_message += value;
                if(index !== errors.length){
                    error_message += ',<br/> ';
                }
            });

            iziToast.error({
                position: 'bottomRight',
                title: 'Error',
                message: error_message
            });

            $('#saveBtn').attr('disabled','disabled');
        }

        return is_filled;
    }

    function populateItems() 
    {
        var table   = $('#tbl-item').DataTable();
        table.clear().draw();
        $.each(items,function(index,value){
            var rowCount    = table.data().count();
            var item_name   = '';

            <?php if(!empty($item)) foreach ($item as $key => $val) 
            {
            ?>
                if (value.item == <?php echo $val['id']; ?>) {
                    item_name = '<?php echo $val['description']; ?>'; 
                };
            <?php
            } 
            ?>

            table.row.add({
                0   : item_name,
                1   : value.description,
                2   : value.measurement,
                3   : value.unit,
                4   : value.amount,
                5   : '<div class="btn-group">\
                            <button class="btn btn-warning btn-sm text-white" onclick="editItem(this)" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Edit Item" type="button" data-index="'+index+'"><i class="fas fa-edit"></i></button>\
                            <button class="btn btn-danger btn-sm" onclick="removeItem(this)" data-index="'+index+'" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Remove Item From Claim" type="button"><i class="fas fa-trash-alt"></i></button>\
                        </div>'
            }).draw();
        });
    }

    function fillTableAttachments() 
    {
        let table   = $('#tbl-attachment').DataTable();
        table.clear().draw(attachment_list);
        $.each(attachment_list,function(index,value)
        {
            let json = JSON.parse(value);    
            let name_template   = `<a href="<?php echo base_url('hr/claim_2/openAttachment/unique_id'); ?>" target="_blank">${json.client_name}</a>`;
            let action_template = `<button 
                                        class="btn btn-danger btn-sm" 
                                        data-index="${index}" 
                                        data-trigger="hover" 
                                        data-tooltip="tooltip" 
                                        title="" 
                                        data-original-title="Remove attachments" 
                                        type="button" 
                                        onclick="removeAttachments(this)">
                                            <i class="fas fa-trash-alt"></i>
                                    </button>`;
            table.row.add({
                0   : name_template,
                1   : json.description,
                2   : action_template
            }).draw();
        });
    }

    function removeAttachments(elem) 
    {
        toastConfirm('Are you sure you want to delete this items ?',function() {
            attachment_list.splice($(elem).data('index'),1);
            fillTableAttachments();
        });
    }

    function removeItem(elem) 
    {
        toastConfirm('Are you sure you want to delete this items ?',function() {
            items.splice($(elem).data('index'),1);
            populateItems();
        });
    }

    function editItem(elem) 
    {

        let index = $(elem).data('index');
        let amount = items[index].amount;
        let description = items[index].description;
        let item = items[index].item;
        let measurement = items[index].measurement;
        let unit = items[index].unit;


        $('#indexEdit').val(index);
        $('#amountEdit').val(amount);
        $('#descriptionEdit').val(description);
        $('#itemEdit').val(item).trigger('change');
        $('#measurementEdit').val(measurement);
        $('#unitEdit').val(unit);

        $('#modal_edit_item').modal('toggle');
    }

    function editRoute(elem) 
    {
        let index = $(elem).data('index');
        $('#travelId').val(index);
        $('#search_departure_from').val(route[index].from).trigger('change');
        $('#search_departure_to').val(route[index].to).trigger('change');
        $('#vehicle_departure').val(route[index].vehicle_id);
        $('#departure_distance').val(route[index].distance);
        $('#hidden_departure_distance').val(route[index].distance);
    }

    function createTableRoute() 
    {
        let d = new Date();
        let index = $('#travelId').val();
        if(index)
        {
            route.splice(index,1);
            $('#routeForm').trigger('reset');
            $('#travelId').val('');
            createTableRoute();
        }else
        {
            var table   = $('#tbl-route').DataTable();
            table.clear().draw();
            $.each(route,function(index,value){
                table.row.add({
                    0   : value.from,
                    1   : value.to,
                    2   : value.distance,
                    3   : value.vehicle,
                    4   : `<div class="btn-group">
                                <button class="btn btn-warning btn-sm text-white" 
                                    data-trigger="hover" 
                                    data-tooltip="tooltip" 
                                    data-original-title="Edit Route" title="" 
                                    data-toggle="modal" 
                                    data-target="#mdl-route" 
                                    type="button" 
                                    onclick="editRoute(this)" data-index="${index}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-danger btn-sm" 
                                    data-trigger="hover" 
                                    data-tooltip="tooltip" 
                                    data-original-title="Remove Route From Claim" title="" 
                                    data-index="${index}" 
                                    onclick="removeStopPoint(this);"
                                    type="button">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                            `, 
                }).draw();
            });
        }
    }

    function addStopPoint()
    {
        var from        = $('#search_departure_from').val();
        var to          = $('#search_departure_to').val();
        var distance    = $('#hidden_departure_distance').val();
        var vehicle_id  = $('#vehicle_departure').val();
        var vehicle     = $('#vehicle_departure option:selected').data('vehicle');

        var stop_point = {
            from : from,
            to : to,
            distance : distance,
            vehicle_id : vehicle_id,
            vehicle : vehicle,
        }

        if(from.length > 0 && to.length > 0 && distance.length > 0 && to != '0' && to != '0 km' && to != '0 m')
        {
            route.push(stop_point);
        }else{
            iziToast.error({
                title: 'Error',
                message: 'From, To and distance are required'
            });
        }
        createTableRoute();

        $("#routeForm")[0].reset();
        $('#mdl-route').modal('toggle');
    }

    function removeStopPoint(elem) 
    {
        toastConfirm('Are you sure you want to delete this items ?',function() {
            route.splice($(elem).data('index'),1);
            createTableRoute();
        });
    }

    // function btnSave() 
    // {
    //     var url         = '<?php echo base_url('hr/api/claim/createTravelClaim'); ?>';
    //     var redirect    = '<?php echo base_url('hr/claim/myClaimList/'.$year.'/'.$month.'/'.$user.'/'.$claim_id); ?>';
    //     var data = 
    //     {
    //         token           : '<?php echo $_SESSION['token']; ?>',
    //         claim_id        : '<?php echo $this->uri->segment(7); ?>',
    //         date            : $('#date').val(),
    //         client          : $('#client').val(),
    //         task            : $('#task').val(),
    //         staff_movement  : staff_movement, 
    //         items           : items,
    //         travel_route    : route, 
    //     }
    //     ajxRequest(url, 'POST', data,null);
    // }

    function openTravellingModal() 
    {
        $("#routeForm")[0].reset();
    }

    function uploadAttachment(attachment_id,description_id,func) 
    {
        formData = new FormData();
        formData.append('files',$(attachment_id).prop('files')[0]);
        formData.append('description',$(description_id).val());

        $.ajax({
            url: '<?php echo base_url('hr/claim_2/addAttachment/7/'); ?>',
            type: "POST",             
            data: formData, 
            contentType:false,       
            cache: false,             
            processData:false,  
            success: function(data){
                func(data);
            },
            error: function(){
                iziToast.error({
                    position: 'bottomRight',
                    title: 'Failed',
                    message: 'Uploading attachments failed'
                });
            }
        });



    }
</script>
<script>
    //google autocomple place suggestion
    var text = '';
    var search_input = 0;

    function findSuggestion()
    {
        let from = $('#search_departure_from').val();
        if(from){
            $('#result_departure_from').css("height","20vh");
        }else{
            $('#result_departure_from').css("height","0vh");
        }

        $('#departure_distance').val('0 km');

        $('#result_departure_from').empty();
        search_input = 0;
        text = $('#search_departure_from').val();
        initService();
    }

    function findSuggestion2()
    {
        let arrive = $('#search_departure_to').val();
        if(arrive){
            $('#result_departure_to').css("height","20vh");
        }else{
            $('#result_departure_to').css("height","0vh");
        }

        $('#departure_distance').val('0');
        $('#hidden_departure_distance').val('0');
        $('#result_departure_to').empty();
        search_input = 1;
        text = $('#search_departure_to').val();
        initService();
    }

    function fillSearch(elem) 
    {
          var place = $(elem).data('value');
          var box = $(elem).data('input');
          if(box == 0)
          {
            $('#search_departure_from').val(place);
            $('#result_departure_from').empty();
            getDepartureDistance();
          }

          if(box == 1)
          {
            $('#search_departure_to').val(place);
            $('#result_departure_to').empty();
            getDepartureDistance();
          }


    }

    function getDepartureDistance() 
    {
        var from = $('#search_departure_from').val();
        var to   = $('#search_departure_to').val();

        if((from != '') && (to != '')){

            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins:[from],
                destinations:[to],
                travelMode: 'DRIVING'
            },function callback(response,status){
                console.log('Response : ');
                console.log(status);




                if(response.rows[0].elements[0].distance.text){
                    var distance = response.rows[0].elements[0].distance.text;
                }else{
                    var distance = '';
                }
                $('#departure_distance').val(distance);
                $('#hidden_departure_distance').val(distance);
            });
        }    
    }

    function getReturnDistance() 
    {
        var from = $('#search_return_from').val();
        var to   = $('#search_return_to').val();   

        if((from != '') && (to != ''))
        {
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins:[from],
                destinations:[to],
                travelMode: 'DRIVING'
            },function callback(response,status){
               if(response.rows[0].elements[0].distance.text)
               {
                    var distance = response.rows[0].elements[0].distance.text;
                }else
                {
                    var distance = '';
                }
                $('#return_distance').val(distance);
                $('#hidden_return_distance').val(distance);
            });
        }
    }

    function initService()
    {

        var displaySuggestions = function(predictions, status) {

          if (status != google.maps.places.PlacesServiceStatus.OK) 
          {
            return;
          }

          //departure from 
          if (search_input == 0) 
          {
                predictions.forEach(function(prediction) {
                    $('#result_departure_from').append('<li class="cursor-pointer" \
                                                            data-value="'+prediction.description+'" \
                                                            data-input="'+search_input+'" \
                                                            onclick="fillSearch(this)" >\
                                                                <i class="fas fa-map-marker"></i> '+prediction.description+'\
                                                        </li>');
                  
                });
          };
          
          //departure to 
          if (search_input == 1) {
                predictions.forEach(function(prediction) {
                    $('#result_departure_to').append('  <li class="cursor-pointer" \
                                                            data-value="'+prediction.description+'" \
                                                            data-input="'+search_input+'" \
                                                            onclick="fillSearch(this)" > \
                                                                <i class="fas fa-map-marker"></i> '+prediction.description+'\
                                                        </li>');
                }); 
          };
        };

        var service = new google.maps.places.AutocompleteService();
        var options = {
            input:text
        };

        // service.setOptions(options);
        service.getQueryPredictions(options, displaySuggestions);
    }
</script>

<?php
    $this->load->view('hr/claim/scripts/google_map.php');
?>