<section class="container" style="padding-bottom: 2rem;">
    <form method="post" action="" id="medical_screening_form">

    	<div class="card no-shadow">
            <div class="card-body">
                <h2><?php echo $Operation ?> Medical Screening <small>(Submission <?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-4">
                                    <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" onchange="formCheck()" onkeyup="formCheck()">
                                    <small><span class="text-danger" id="notice_date"></span></small>
                                </div> 
                            </div>
                        </div>
                        <div class="col">
                            <div class="row form-group">
                                <div class="col-lg-4">
                                    <label for="invoice-chit">Invoice Chit <span class="text-danger">*</span></label>
                                </div>
                                <div class="col">
                                   <input type="text" class="form-control " name="invoice_chit" id="invoice-chit" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()">
                                </div> 
                            </div>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col-lg-2">
                            <label for="hospital">Hospital/ Clinic <span class="text-danger">*</span></label>
                        </div>
                        <div class="col">

                            <select class="form-control" name="hospital" id="hospital" onchange="formCheck()" required>
                                <option disabled selected>Please Select Clinic</option>
                                <?php foreach ($panels as $key => $panel): ?>
                                    <option value="<?php echo $panel->id;?>"><?php echo $panel->name; ?></option>
                                <?php endforeach ?>
                            </select>

                           <!-- <input type="text" class="form-control " name="hospital" id="hospital" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()"> -->
                        </div> 
                    </div>

                    <div class="row">
                        <div class="col">
                            <div class="row">
                                <div class="col-lg-4">
                                    <label for="amount_charge">Amount Charge <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" placeholder="Enter Amount Charge" name="amount_charge" id="amount_charge" onchange="formCheck()" onkeyup="formCheck()">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col">
                            <div class="row">
                                <div class="col-lg-4">
                                    <label for="amount_claim">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" placeholder="Enter Amount Claim" name="amount_claim" id="amount_claim" onchange="formCheck()" onkeyup="formCheck()">
                                    </div>
                                    <small><span class="text-danger" id="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>

            <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">Date uploaded</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                        </table>
                    </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>
        </form>
    </div>
</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 (Medical Screening) </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">
                           <input type="file" class="form-control form-control-sm" id="upload-attachment">
                        </div>
                        <div class="col-lg-4">
                            <button type="submit" class="btn btn-primary btn-sm btn-block"><i class="fas fa-save"></i> Save</button>
                        </div>
                    </div>  
                </div>
                <div class="modal-footer">
                   <div class="btn-group float-right">
                        <button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- modal add attachment -->
<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(){
        $( ".claimdate" ).datepicker({
            uiLibrary: 'bootstrap4',
            format: 'dd-mm-yyyy',
            autoclose: true,
            changeMonth: true, 
            changeYear: true,
            startDate :start_claim,
            endDate:end_claim
        });

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

            console.log('value for the '+is_pass);
            console.log('value for the attachment : '+is_attach);
            if (is_pass && is_attach) {
                
                //ajx req
                url     = '<?php echo base_url('hr/api/claim/createMedicalScreening/'); ?>';
                type    = 'POST',
                data    = {
                    token       : '<?php echo $_SESSION['token']; ?>',
                    form        : JSON.stringify(formIdToInputObject('#medical_screening_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/3/'); ?>',
                type: "POST",             
                data: formData, 
                contentType:false,       
                cache: false,             
                processData:false,
                dataType: 'JSON',
                success: function(data){
                    $('#modal_add_item').modal('hide');
                    attachments.push(data);
                    populatetable();
                }
            });

        });
        
        
    });

    //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('#medical_screening_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.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'); ?>) ';
                iziToast.error({
                    status:'Error',
                    message: 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+' )';
            iziToast.error({
                status:'Error',
                message:error,
            });
            $('#notice_date').html(error);
         }else{
            $('#notice_date').empty();
         }
         

        //checking if amount charge and amount claim are numbers
        if($.isNumeric(input.amount_charge) && $.isNumeric(input.amount_claim)){

            number_condition = true;

            if(parseFloat(input.amount_claim) < 0 || parseFloat(input.amount_charge) < 0){
                is_filled = false;
                number_condition = false;
                var error = 'Amount claim and amount charge cannot be negative';
                iziToast.error({
                    status:'Error',
                    message:error,
                });
                $('#notice_charge').html(error);
            }

            //claim more than charge
            if(parseFloat(input.amount_claim) > parseFloat(input.amount_charge)){
                is_filled = false;
                number_condition = false;
                var error = 'You trying to claim more than what have been charged';
                iziToast.error({
                    status:'Error',
                    message: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');
        }

        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.file_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>
