<section class="container" style="padding-bottom: 2rem;">
    <form method="post" id="other_claim_form">
    	<div class="card no-shadow">
            <div class="card-body">
<!-- changes made by Ariff 29/03/2021 -->
                <h2><?php echo $Operation ?> <small>(Submision <?php echo date('F Y',strtotime('01-'.$month.'-'.$year)) ?>)</small></h2>
                <hr>
                    <div class="row">
                        <div class="col">
                            <div class="row form-group">
                                
                                <div class="col-lg-2">
                                    <label for="date"> Date <span class="text-danger">*</span></label>
                                </div>
                                <div class="col">
                                   <input type="text" class="form-control claimdate" name="date" id="date" autocomplete="off" placeholder="Enter valid date (<?php echo date('d-m-Y'); ?>)">
                                   <small><span class="text-danger" id="notice_date"></span></small>
                                </div> 

                                <div class="col-lg-2">
                                    <label for="">Type<span class="text-danger">*</span></label>
                                </div>
                                <div class="col">
                                    <?php if(!empty($type)){ ?>
                                        <?php if($type == 'membership'){ ?>
                                            <select class="form-control" name="type_other">
                                                <option value="MEMBERSHIP">Membership</option>
                                            </select>
                                        <?php } ?>
                                    <?php } else { ?>
                                        <select class="form-control" name="type_other">

                                            <!-- 
                                                remove 29/6/2020
                                                    1. will not be shown in reporting
                                                    2. user abuse it for claiming other items such as fuel
                                                <option value="PURCHASE">Purchase</option>
                                                <option value="CALL">Call</option> 
                                            -->

                                            <option value="TNG">Touch n Go</option>
                                            <option value="AIRPORT_TAXES">Airport Taxes</option>
                                            <option value="SERVICE_TAXES">Service Taxes</option>
                                            <!-- 
                                                remove 29/6/2020
                                                <option value="TIPS_AND_PORTAGE">Tips and Portage</option> 
                                            -->

                                            <!-- 
                                                remove 29/6/2020    
                                                <option value="LAUNDRY">Laundry</option> 
                                            -->

                                            <option value="EXCESS_BAGGAGE">Excess Baggage</option>
                                            
                                            <!-- 
                                                remove 29/6/2020
                                                <option value="LOSS_IN_FOREIGN_EXCHANGE">Loss in Foreign Exchange</option> 
                                                <option value="FIRM_EVENT">Firm Event</option>
                                              -->
                                            <!-- 
                                                taxi fare ni sepatutnya dah ada kat transportation    
                                                <option value="TAXI_FARE">Taxi Fare</option> 
                                            -->
                                            <!-- <option value="MOTOR_EXPENSES">Motor Expenses</option> -->
                                            <!-- <option value="SSM_SEARCH">SSM Search</option> -->

                                            <!-- 
                                                remove 29/6/2020
                                                    1. will not be shown in reporting    
                                                <option value="BOOK">Book</option> 
                                            -->

                                            <!-- <option value="STATIONARY">Stationary</option> -->
                                            <!-- <option value="PRINTING">Printing</option> -->
                                            <!-- <option value="STAMPING">Stamping / Oath</option> -->
                                            <!-- <option value="MEMBERSHIP">Membership</option> -->
                                            <option value="LICENSE">License</option>
                                            <!-- <option value="COURIER">Courier / Postage </option> -->
                                        </select>
                                    <?php } ?>
                                </div>

                                <!-- <div class="col-lg-1">
                                    <label for="">Membership Type<span class="text-danger">*</span></label>
                                </div>
                                <div class="col">
                                    <?php if(!empty($type)){ ?>
                                        <?php if($type == 'membership'){ ?>
                                            <select class="form-control" name="type_other">
                                                <option value="ACCA">ACCA</option>
                                                <option value="MIA">MIA</option>
                                                <option value="CPA">CPA</option>
                                                <option value="MICPA">MICPA</option>
                                                <option value="CTIM">CTIM</option>
                                                <option value="MATA">MATA</option>
                                                <option value="MICG">MICG</option>
                                                <option value="IIAM">IIAM</option>
                                            </select>
                                        <?php } ?>
                                    <?php } ?>
                                </div> -->
<!-- changes made by Ariff 29/03/2021 -->


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

                    <!-- others claim -->
                    <div class="row form-group">
                        <div class="col-lg-2">
                            <label for="hospital">Description <span class="text-danger">*</span></label>
                        </div>
                        <div class="col">
                            <textarea class="form-control" name="description" autocomplete="off" rows="5" placeholder="Description"></textarea>
                        </div> 
                    </div>

                    
                    <div class="form-group row">
                        <div class="col">
                            <div class="row">
                                <div class="col-lg-2">
                                    <label for="amount_charge">Amount Claim <span class="text-danger">*</span></label>
                                </div>
                                <div class="col">
                                     <div class="input-group ">
                                        <div class="input-group-append">
                                            <span class="input-group-text">RM</span>
                                        </div>
                                        <input type="number" class="form-control currency_input" placeholder="0.00" name="amount_charge" id="amount_charge" min="0.01" step=".01">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>                    

                    <!-- others claim -->
                    <span class="text-danger font-italic"><small>[NOTES : ] * require</small></span>
                    <br>
                    <small><span class="text-danger font-italic" id="notice_attachment"></span></small>

                    <div class="card no-shadow">
                        <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <h4>Attachment</h4>
                                </div>
                                <div class="col text-right">
                                    <button class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal_add_item" type="button"><i class="fas fa-plus"></i> Add attachment</button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover">
                                    <thead>
                                        <tr>
                                            <th class="text-center">#</th>
                                            <th class="text-center">Description</th>
                                            <th class="text-center">File Name</th>
                                            <th class="text-center">Action</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                    </div>

            </div>
            <div class="card-footer bg-white">
                <div class="btn-group float-right">
                    <button type="submit" class="btn btn-success" id="saveBtn"><i class="fas fa-save"></i> Save</button>
                </div>
            </div>
        </div>
    </form>
</section>
<!-- modal add attachment -->

<div class="modal fade" id="modal_add_item" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Add Attachment</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="attachment_form" enctype="multipart/form-data">
                <div class="modal-body"> 
                    <div class="row form-group">
                        <div class="col">
                            <label for="item"><b>Description</b></label>
                        </div>
                    </div>  

                    <div class="row mb-3">
                        <div class="col">
                           <textarea class="form-control" rows="5" id="attachment_description" placeholder="Attachment description"></textarea>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col">
                            <input type="file" class="form-control form-control-sm" id="upload-attachment">
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-success btn-block btn-sm"><i class="fas fa-save"></i> Save</button> 
                        </div>
                    </div>  
                </div>
            </form>
        </div>
    </div>
</div>

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

        $('#other_claim_form').submit(function(event){
           if(formCheck())
           {
            $('#saveBtn').attr('disabled',true);
            event.preventDefault();
            
            url     = '<?php echo base_url('hr/api/claim/createOtherClaim/'); ?>';
            type    = 'POST',
            data    = 
            {
                token       : '<?php echo $_SESSION['token']; ?>',
                form        : JSON.stringify(formIdToInputObject('#other_claim_form')),
                attachment  : attachments,
                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):''; ?>,
            };
            redirect = '<?php echo base_url('hr/claim/myClaimDetail').'/'.$this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6).'/'.$this->uri->segment(7).'/'; ?>';
            // redirect = null;
            ajxRequest(url, type, data, redirect);
           }

        });

        $('#attachment_form').submit(function(event){
            event.preventDefault();

            var $form = $(this);
            url = $form.attr('action');

            formData = new FormData();
            formData.append('files',$('#upload-attachment').prop('files')[0]);
            formData.append('description',$('#attachment_description').val());

            $.ajax({
                url: '<?php echo base_url('hr/claim/addAttachment/5/'); ?>',
                type: "POST",             
                data: formData, 
                contentType:false,       
                cache: false,             
                processData:false,
                dataType: 'JSON',
                success: function(data){
                    $('#modal_add_item').modal('hide');

                    if(data.status == true)
                    {
                        attachments.push(data);
                        populatetable();
                    }else
                    {
                        iziToast.error({
                            position: 'bottomRight',
                            title: 'File upload failed',
                            message:data[0].error
                        });
                    } 
                }
            });

        });

    });

    //form checking 
    function attachmentCheck()
    {
        if(attachments.length > 0){
            $('#notice_attachment').empty();
            return true;
        }else{
            $('#notice_attachment').html('Please upload attachment');
            return false;
        }
    }

    function formCheck()
    {
        iziToast.destroy();
        let err_arry = [];
        var is_filled;

        if(!attachmentCheck()){
            let error = 'Please upload supporting documents';
            err_arry.push(error);
            is_filled = false;
            console.log('error in attachment');
        }else{
            is_filled = true;
        }
        
        var input = formIdToInputObject('#other_claim_form');
        
        //checking if all input filled
        $.each(input, function(index,value){
            if(value.length <= 0){
                
                if(index == 'amount_charge')
                {
                    index = 'Amount Claim';
                }
                
                if(index == 'amount_claim')
                {
                    index = 'Amount Claim';
                }

                index = index.charAt(0).toUpperCase() + index.slice(1);

                console.log('error in input form');
                is_filled = false;
                let error = index+' cannot be empty';
                err_arry.push(error);
            }
        });

        //validating date
        if(input.date.length > 0){
            if(moment(input.date,'DD-MM-YYYY',true).isValid() == false){
                is_filled = false;
                let error = 'Please enter a valid date format : day-month-year (<?php echo date('d-m-Y'); ?>) ';
                err_arry.push(error);
                $('#notice_date').html(error);
            }else{
                $('#notice_date').empty();
            }
        }

        var claim_able_date = isWithinClaimableDate();

         if(!claim_able_date){
            is_filled = false;
            var error = '<br/> Date is not whithin claimable date period : ( '+start_claim+' - '+end_claim+' )';
            err_arry.push(error);
            $('#notice_date').html(error);
         }else{
            $('#notice_date').empty();
         }
        
        //checking if amount charge and amount claim are numbers
        if($.isNumeric(input.amount_charge))
        {
            number_condition = true;
            if(parseFloat(input.amount_claim) < 0)
            {
                is_filled = false;
                number_condition = false;
                var error = 'Amount cannot be negative';
                err_arry.push(error);
                $('#notice_charge').html(error);
            }

            if(number_condition)
            {
                $('#notice_charge').empty();
            }
            
        }else{
            is_filled = false;
            $('#notice_charge').empty();
        }

        if(is_filled){
            $('#saveBtn').removeAttr('disabled');
        }else{
            $('#saveBtn').attr('disabled','disabled');
        }

        if(!is_filled)
        {
            var error_string = '';
            $.each(err_arry,function(index,value){
                error_string += value+', <br/>';
            });
            iziToast.error({
                position:'bottomRight',
                message: error_string
            });
        }

        return is_filled;
    }

    function populatetable() 
    {
        // console.log(attachments);  
        var table   = $('.table').DataTable();
            table.clear().draw();

        $.each(attachments,function(index,value){
            console.log(value);
            
            var rowCount = table.data().count();
            table.row.add({
                0   : ++rowCount,
                1   : value.description,
                2   : value.orig_name,
                3   : '<td class="text-center">\
                        <a href="javascript:removeAttachment('+rowCount+')" data-toggle="tooltip" data-placement="top" title="Delete" class="btn btn-danger btn-sm"><i class="fas fa-trash-alt" ></i>\
                        </a>\
                    </td>',
            }).draw();
        });  
    }

    function removeAttachment(index)
    {
        //pop / slice attachment items
        toastConfirm('Are you sure you want to remove this item from your attachments',function(){
            attachments.splice(index-1,1);
            populatetable();
        });
    }

    function isWithinClaimableDate() 
    {
        var bool = true;

        var claim_date = $('#date').val();
        if(claim_date){
            if (moment(claim_date,'DD-MM-YYYY').isBetween(moment(start_claim,'DD-MM-YYYY').subtract(1,'days'),moment(end_claim,'DD-MM-YYYY').add(1,'days')) == false) {
                bool = false;
            }
        }

        return bool;
    }
</script>