<section class="container mb-5">
    <div class="card no-shadow">
        <div class="card-body">
            
            <div class="row">
                <div class="col">
                    <h2>Add Petrol Claims (Submission <?php echo date('F-Y',strtotime('01-'.$month.'-'.$year)); ?>)</h2>
                </div>
            </div>

            <br>

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

            <div class="row">
                <div class="col-12 col-md-2">
                    <label><b>Amount</b></label>
                </div>
                <div class="col-12 col-md-10">
                    <input type="text" class="form-control currency_input" id="petrol_amount">
                </div>
            </div>

            <br>
            <div class="row">
                <div class="col-2">
                    <label><b>From</b> <span class="text-danger">*</span></label>
                </div>
                <div class="col">
                   <input type="text" class="form-control claimdate" id="dateFrom">
                </div>

                <div class="col-2">
                    <label><b>To</b> <span class="text-danger">*</span></label>
                </div>
                <div class="col">
                   <input type="text" class="form-control claimdate" id="dateTo">
                </div>

            </div>

            <br>
            <div class="row">
                <div class="col-12">
                    <label><b>Staff movement</b></label>
                </div>
            </div>
            <div class="row">
                <div class="col table-responsive">

                    <table class="table table-bordered" id="table-petrol-movement">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Movement Type</th>
                                <th>Client</th>
                                <th>Destination</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>

            <br>
            <div class="row">
                <div class="col">
                    <label><b>Attachments</b></label>
                </div>
                <div class="col">
                    <button class="btn btn-primary btn-sm float-right" data-toggle="modal" data-target="#upload_attachments"><i class="fas fa-plus"></i></button>
                </div>
            </div>
            
            <div class="row">
                <div class="col table-responsive">
                    <table class="table table-bordered" id="table-petrol-attachment">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>

            <br>
            <div class="row">
                <div class="col-12">
                    <button class="btn btn-success float-right" id="save_petrol_claim"> <i class="fas fa-save"></i> Save</button>
                </div>
            </div>

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

<div class="modal fade" id="upload_attachments" tabindex="-1" role="dialog" >
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Upload 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-12 form-group">
                <label>Attachments</label> 
                <br>
                <input type="file" id="upload_receipts">
            </div>
        </div>

        <div class="row">
            <div class="col-12 form-group">
                <label>Description</label>
                <textarea class="form-control" id="petrol_desciption"></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" onclick="upload_attachments();">Uploads</button>
      </div>
    </div>
  </div>
</div>

<script>
    var attachment      = [];    
    var staff_movement  = [];
    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
        }); 

        $('#dateFrom').change(function(){
            
            let date_from   = $('#dateFrom').val();
            let date_to     = $('#dateTo').val();

            let from_moment   = moment(date_from,'DD-MM-YYYY'); 
            let to_moment     = moment(date_to,'DD-MM-YYYY'); 

            if(from_moment.isValid() && to_moment.isValid())
            {
                fetchMovement();
            }else{
                staff_movement = [];
            }

        });

        $('#dateTo').change(function(){
            let date_from   = $('#dateFrom').val();
            let date_to     = $('#dateTo').val();

            let from_moment   = moment(date_from,'DD-MM-YYYY'); 
            let to_moment     = moment(date_to,'DD-MM-YYYY'); 

            if(from_moment.isValid() && to_moment.isValid())
            {
                fetchMovement();
            }else{
                console.log('either one is not valid date');
                staff_movement = [];
            }
        });

        $('#save_petrol_claim').click(function(){
            let amount = $('#petrol_amount').val();
            let error_message = '';
            let bool = true;
            let job_id = $('#job_id').val();

            if(amount <= 0 || amount == null )
            {
                error_message += 'Amount is empty.Please insert some amount to claim.';
                bool = false;
            }

            if(attachment.length == 0)
            {
                error_message += 'Please upload some attachments to support your claims.';
                bool = false; 
            }
            
            if(staff_movement.length == 0)
            {
                error_message += 'Unable to find staff movement for your claims.';
                bool = false;
            }

            if(job_id == 0 || job_id == null )
            {
                error_message += 'Job ID is empty.Please select Job ID before proceed.';
                bool = false;
            }

            if(bool == true)
            {
                $.ajax({
                    url: '<?php echo base_url('hr/claim_v2/add_petrol'); ?>',
                    type: 'POST',
                    data:{
                        claim_id        : <?php echo $claim_id; ?>,
                        attachment      : JSON.stringify(attachment),
                        staff_movement  : JSON.stringify(staff_movement),
                        amount          : amount,
                        date_from       : $('#dateFrom').val(),
                        date_to         : $('#dateTo').val(),
                        job_id          : job_id,
                    },
                    dataType: 'JSON',
                    success: function(data){
                        window.location.href = '<?php echo base_url('hr/claim_v2/myClaimDetail/'.$year.'/'.$month.'/'.$user_id.'/'.$claim_id); ?>';
                    },error:function(err){
                        iziToast.error({
                            title: 'Error',
                            message: 'Failed to create petrol claims.'
                        });
                    }
                });

                

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

    });

    function removeStaffMovement(elem) 
    {
        staff_movement.splice(elem,1);
        fill_table_movement();
    }

    function removeAttachment(elem) 
    {
        attachment.splice(elem,1);
        fill_table_attachment();    
    }

    function fill_table_movement() 
    {
        var table   = $('#table-petrol-movement').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 fill_table_attachment() 
    {
        console.log(attachment);

        var table_attachment = $('#table-petrol-attachment').DataTable();
        table_attachment.clear().draw();

        $.each(attachment,function(index,value){
            table_attachment.row.add({
                0:value.orig_name,
                1:value.description,
                2:'<button class="btn btn-danger btn-sm" onclick="removeAttachment('+index+')"><i class="fas fa-trash-alt"></i></button>',
            }).draw();
        });
    }

    function fetchMovement()
    {
        let date_from = $('#dateFrom').val();
        let date_to   = $('#dateTo').val();

        $.ajax({
            url: '<?php echo base_url('hr/api_movement/getUserMovementBetweenDate/'); ?>',
            type: 'POST',
            data:{
                token:'<?php echo $token; ?>',
                date_from:date_from,
                date_to:date_to,
                user_id:<?php echo $user_id; ?>,
            },
            dataType: 'JSON',
            success: function(data){
                if(data.results != null)
                {   
                    staff_movement = data.results;
                    fill_table_movement();
                }
            }
        });    
    }

    function upload_attachments() 
    {
        formData = new FormData();
        formData.append('files',$('#upload_receipts').prop('files')[0]);
        formData.append('description',$('#petrol_desciption').val()); 

        $.ajax({
            url: '<?php echo base_url('hr/claim/addAttachment/711'); ?>',
            type: 'POST',
            data:formData,
            contentType:false,       
            cache: false,             
            processData:false,
            dataType: 'JSON',
            success: function(data){
                attachment.push(data);
                fill_table_attachment();
                $('#upload_attachments').modal('hide');
            },
            error:function(err){
                console.log('error code ');
            }
        });
    }


</script>