<style>
    .card-height
    {
        min-height:100px;
    }
</style>

<section class="container p-0 mb-5" style="padding-bottom: 2rem;overflow:hidden;">
    <?php if($check_eligable_for_claim): ?>
        <?php if($last_month_allocation_balance > 0 || $last_2_month_allocation_balance > 0): ?>
    	<div class="card no-shadow">
            <form method="post" action="" id="dressing_form">
                <div class="card-body">
                    <h2><?php echo $Operation ?> Special Allowance - Dressing <small>(Submission <?php echo date('F Y',strtotime('01-'.$month.'-'.$year)) ?>)</small></h2>
                    <i><span class="text-danger">*</span>Dressing Allocation Balance (for <?php echo $year; ?>) : RM <?php echo $current_allocation_balance; ?></i>
                    <hr>
                        <div class="row">
                            <div class="col">
                                <div class="row form-group">
                                    <div class="col-lg-4">
                                        <label for="dressing_date"> <b>Date</b> <span class="text-danger">*</span></label>
                                    </div>
                                    <div class="col">
                                        <input type="text" class="form-control claimdate" name="dressing_date" id="dressing_date" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()" placeholder="Enter date (<?php echo date('d-m-Y'); ?>)" required>
                                        <small><span class="text-danger" id="dressing_notice_date"></span></small>
                                    </div> 
                                </div>
                            </div>
                            <div class="col">
                                <div class="row form-group">
                                    <div class="col-lg-4">
                                        <label for="dressing_invoice_chit"><b>Invoice No</b><span class="text-danger">*</span></label>
                                    </div>
                                    <div class="col">
                                       <input type="text" class="form-control " name="dressing_invoice_chit" id="dressing_invoice_chit" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()" placeholder="Enter invoice number" required>
                                    </div> 
                                </div>
                            </div>
                        </div>

                        <div class="row form-group">
                            <div class="col-lg-2">
                                <label for="dressing_desc"><b>Description</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <textarea type="text" class="form-control" name="dressing_desc" id="dressing_desc" rows="4" autocomplete="off" placeholder="Description" required></textarea>
                            </div> 
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <div class="row">
                                    <div class="col-lg-4">
                                        <label for="dressing_amount_charge"><b>Amount Charge </b><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="dressing_amount_charge" id="dressing_amount_charge" onchange="formCheck()" onkeyup="formCheck()" required>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col">
                                <div class="row">
                                    <div class="col-lg-4">
                                        <label for="dressing_amount_claim"><b>Amount Claim </b><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="dressing_amount_claim" id="dressing_amount_claim" onchange="formCheck()" onkeyup="formCheck()" required>
                                        </div>
                                        <small><span class="text-danger" id="dressing_notice_charge"></span></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                <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 bg-light-transparent no-shadow">  
                      
                    <div class="card-body">
                        <div class="row mt-3 mr-1">
                            <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 mb-3">
                    <div class="btn-group float-right">
                        <button type="submit" class="btn btn-success text-white" id="saveBtn"><i class="fas fa-save"></i> Save</button>
                    </div>
                </div>
                <br>
            </form>
        </div>
        <?php else:?>
        <div class="card no-shadow">
            <div class="card-body">
                <div class="row">
                    <div class="col-6 col-md-2 mx-auto">
                        <img src="<?php echo base_url('/assets/themes/web/img/coins.png'); ?>" alt="" class="img img-fluid">
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 text-center">
                        <h4>Not allowed to claim Special Allowance - Dressing. Allocation already empty.</h4>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    <?php else:?>
        <div class="card no-shadow">
            <div class="card-body">
                <div class="row">
                    <div class="col-6 col-md-2 mx-auto">
                        <img src="<?php echo base_url('/assets/themes/web/img/coins.png'); ?>" alt="" class="img img-fluid">
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 text-center">
                        <h4>Not allowed to claim Special Allowance - Dressing. No allocation for this user.</h4>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</section>

<!-- modal add item -->
<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 (Dressing)</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">
                        <div class="col">
                            <label for="item"><b>Description</b></label>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col">
                           <textarea class="form-control" rows="5" id="attachment_description" placeholder="Attachment's Descriptive Information "></textarea>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-8">
                            <input type="file" class="form-control form-control-sm" id="upload-attachment" placeholder="Uploads file">
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-primary text-white btn-block btn-sm"><i class="fas fa-save text-white" ></i> Save</button>
                        </div>
                    </div>  
                </div>
            </form>
        </div>
    </div>
</div>
<!-- modal add item -->

<script>
    var attachments = [];
    var claim_year = <?php echo $this->uri->segment(4); ?>; 
    var claim_month = <?php echo $this->uri->segment(5); ?>; 
    var date = new Date();

    <?php if($last_month_allocation_balance == true && $last_2_month_allocation_balance == true): ?>
        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');
    <?php else:?>
        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');
    <?php endif; ?>

    $(document).ready(function(){
        $( ".claimdate" ).datepicker({
            uiLibrary: 'bootstrap4',
            format: 'dd-mm-yyyy',
            orientation: "bottom auto",
            autoclose: true,
            changeMonth: true, 
            changeYear: true,
            startDate :start_claim,
            endDate:end_claim
        });

        $('#dressing_form').submit(function(event){
            event.preventDefault();
            is_pass     = formCheck();
            is_attach   = attachmentCheck();

            if (is_pass && is_attach) {
                $('#saveBtn').attr('disabled','disabled');
                //ajx req
                url     = '<?php echo base_url('hr/api/claim/createDressing/'); ?>';
                type    = 'POST',
                data    = {
                    token       : '<?php echo $_SESSION['token']; ?>',
                    form        : JSON.stringify(formIdToInputObject('#dressing_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).'/'; ?>';
                ajxRequest(url, type, data,redirect);

            }else{
                iziToast.warning({
                    position:'bottomRight',
                    message: 'Make sure all forms have been filled and upload your attachments.'
                });
            }
        });

        $('#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/90/'); ?>',
                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: 'Uploading 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();
        var is_filled = true;
        var input = formIdToInputObject('#dressing_form');
        
        console.log(input);

        //checking if all input filled
        $.each(input, function(index,value)
        {
            if(value.length <= 0){
                is_filled = false;
            }
        });

        //validating date
        if(input.dressing_date.length > 0)
        {
            if(moment(input.dressing_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'); ?>) ';
                iziToast.error({
                    position:'bottomRight',
                    message:error,
                });

                $('#dressing_notice_date').html(error);
            }else{
                $('#dressing_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+' )';
            iziToast.error({
                position:'bottomRight',
                message:error,
            });
            $('#dressing_notice_date').html(error);
         }else{
            $('#dressing_notice_date').empty();
         }
        
        //checking if amount charge and amount claim are numbers
        if($.isNumeric(input.dressing_amount_charge) && $.isNumeric(input.dressing_amount_claim)){

            number_condition = true;

            if(parseFloat(input.dressing_amount_claim) < 0 || parseFloat(input.dressing_amount_charge) < 0){
                is_filled = false;
                number_condition = false;
                var error = 'Amount claim and amount charge cannot be negative';
                iziToast.error({
                    position:'bottomRight',
                    message:error,
                });
                $('#dressing_notice_charge').html(error);
            }

            //claim more than charge
            if(parseFloat(input.dressing_amount_claim) > parseFloat(input.dressing_amount_charge)){
                is_filled = false;
                number_condition = false;
                var error = 'You trying to claim more than what have been charged';
                iziToast.error({
                    position:'bottomRight',
                    message:error,
                });
                $('#dressing_notice_charge').html(error);
            }

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


        if(!isClaimableAmount(input.dressing_date,input.dressing_amount_claim))
        {
            is_filled = false;
        }

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

        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   : '<a href="">'+value.orig_name+'<a>',
                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 = $('#dressing_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;
    }

    function isClaimableAmount(claim_date,amount_claim) 
    {

        let choose_date = moment(claim_date,'YYYY/MM/DD');
        let choose_month = choose_date.format('M');
        let is_balanced_previous_month = true;
        //compare claimable amount dengan date sbb balanced untuk submission bulan 2 ada 2..
        let submission_month    = <?php echo $this->uri->segment(5); ?>;
        let last_month_allocation_balance   = <?php echo (!empty($last_month_allocation_balance))?($last_month_allocation_balance > 0)?$last_month_allocation_balance:0:0; ?>;
        let last_2_month_allocation_balance = <?php echo (!empty($last_2_month_allocation_balance))?($last_2_month_allocation_balance > 0)?$last_2_month_allocation_balance:0:0; ?>; 
        let allocation_balanced = 0;

        if(submission_month == 2 && choose_month == 12)
        {
            is_balanced_previous_month = false
        }

        if(is_balanced_previous_month)
        {
            allocation_balanced = last_month_allocation_balance;
        }else{
            allocation_balanced = last_2_month_allocation_balance;
        }

        if(amount_claim > allocation_balanced)
        {
            var error = 'Amount claim cannot need to be less than allocation balanced.Amount allocation balanced : RM'+allocation_balanced;
            iziToast.error({
                position:'bottomRight',
                message: error,
            });
            return false;
        }else{
            return true;
        }
        
    }
</script>