<style type="text/css">
    .off{cursor:no-drop;}
    .card-height{min-height:100px;}
</style>

<section class="container p-0 mb-5" style="padding-bottom: 2rem;overflow:hidden;">

    <div class="row bg-dark" style="border-radius:5px;">
        <div class="col-12 col-lg-3 p-3">
            <div class="p-3 m-0 bg-dark text-white card-height" style="border:0.5px solid black;border-radius:5px;">
                <h4>PRORATE</h4>
                <div class="row">
                    <div class="col">
                        <?php echo date('F',strtotime('01-'.$previous_2_month.'-2019')); ?> <br>
                        RM<?php echo (!empty($previous_2_month_prorate))?number_format($previous_2_month_prorate,2):'0.00'; ?>
                    </div>
                    <div class="col">
                        <?php echo date('F',strtotime('01-'.$previous_month.'-2019')); ?> <br>
                        RM<?php echo (!empty($previous_month_prorate))?number_format($previous_month_prorate,2):'0.00'; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-3 p-3">
            <div class="p-3 bg-dark m-0 text-white card-height" style="border:0.5px solid black;border-radius:5px;">
                <h4>APPROVED</h4>
                <div class="row">
                    <?php if($month <= 2): ?>
                    <div class="col">
                        <?php echo $year_2; ?> <br>
                        RM<?php echo (!empty($previous_approved_2))?number_format($previous_approved_2,2):'0.00'; ?>
                    </div>
                    <?php endif; ?>

                    <div class="col">
                        <?php echo $year_1; ?> <br>
                        RM<?php echo (!empty($previous_approved))?number_format($previous_approved,2):'0.00'; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-3 p-3">
            <div class="p-3 bg-dark m-0 text-white card-height" style="border:0.5px solid black;border-radius:5px;">
                <h4>PENDING</h4>
                <div class="row">
                    <?php if($month <= 2): ?>
                    <div class="col">
                        <?php echo $year_2; ?> <br>
                        RM<?php echo (!empty($previous_pending_2))?number_format($previous_pending_2,2):'0.00'; ?>
                    </div>
                    <?php endif; ?>
                    <div class="col">
                        <?php echo $year_1; ?>  <br>
                        RM<?php echo (!empty($previous_pending))?number_format($previous_pending,2):'0.00'; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-3 p-3">
            <div class="p-3 bg-dark m-0 text-white card-height" style="border:0.5px solid black;border-radius:5px;">
                <h4>BALANCED</h4>
                <div class="row">
                    <div class="col">
                        <?php echo date('F Y',strtotime('01-'.$month_2.'-'.$year_2)); ?><br>
                        RM<?php echo (!empty($previous_balanced_2))?(number_format($previous_balanced_2,2) > 0)?number_format($previous_balanced_2,2):'0.00':'0.00'; ?>
                    </div>
                    <div class="col">
                        <?php echo date('F Y',strtotime('01-'.$month_1.'-'.$year_1)); ?> <br>
                        RM<?php echo (!empty($previous_balanced))?(number_format($previous_balanced,2) > 0 )?number_format($previous_balanced,2):'0.00':'0.00'; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php if($is_previous_claimable == true || $is_previous_2_claimable == true): ?>
        <div class="card no-shadow">
            <form method="post" action="<?php echo base_url(); ?>" id="outpatient_form">

                <div class="card-body">
                    <h2><?php echo $Operation ?> Outpatient Claim  <small>(Submission <?php echo $submission['month_full'].' '.$submission['year']; ?>)</small></h2>
                    <hr>
                        <div class="row">
                            <div class="col">
                                
                                <div class="row form-group">
                                    <div class="col">
                                        <div class="row">
                                            <div class="col-lg-4">
                                                <label for="date"> <b>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="formCheck()" onkeyup="formCheck()" placeholder="Enter valid date (<?php echo date('d-m-Y'); ?>)" required>
                                                <small><span class="text-danger" id="notice_date"></span></small>
                                            </div> 
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="row">
                                            <div class="col-lg-4">
                                                <label for="invoice_chit"><b>Invoice No </b><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()" placeholder="Enter invoice number" required>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col">
                                        <div class="row form-group">
                                            <div class="col-lg-4">
                                                <label for="hospital"><b>Hospital/Clinic</b> <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col">
                                                <input type="text" class="form-control" name="hospital" placeholder="Enter hospital name">
                                            </div> 
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group row">
                                            <div class="col-lg-4">
                                                <label for="treatment"><b>Treatment</b> <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col">
                                                <input type="text" class="form-control " name="treatment" id="treatment" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()" placeholder="Enter type of treatment receive" required>
                                                <?php if($user['position_id'] <= 9 && $user['position_id'] != 0): ?>
                                                    <input type="checkbox" onclick="checkMedical(this)" name="medical_screening" value="1"> Medical Screening 
                                                    <span data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Applicable for directors and above only" >
                                                        <i class="fas fa-info-circle fx-1" style="font-size:10px;"></i> 
                                                    </span>
                                                <?php endif ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col">
                                        <div class="row form-group">
                                            <div class="col-lg-4">
                                                <span data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Assistant manager and above applicable to claim for spouse and child below than 17 years old" >
                                                    <i class="fas fa-info-circle fx-1" style="font-size:10px;"></i> 
                                                </span>
                                                <label for="patient"><b>Patient Name</b> <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col">
                                                <select class="form-control" name="patient" id="patient" onchange="formCheck()" required>
                                                        <option value="<?php echo $this->uri->segment(6); ?>" data-relation="self"><?php echo $user['name']; ?></option>
                                                    <?php if($families) foreach ($families as $key => $family): ?>
                                                            
                                                            <!-- child  -->
                                                            <?php 
                                                                if ($family->relation == 2){
                                                                    $age = date('Y') - date('Y',strtotime($family->birthdate));
                                                                    if ($age > 17) {
                                                            ?>
                                                                        <option value="<?php echo $family->id; ?>" data-relation="<?php echo $family->relations; ?>" disabled class="text-danger"><?php echo $family->name.'('.$age.' Years Old)'; ?></option>            
                                                            <?php
                                                                    }else{
                                                            ?>
                                                                        <option value="<?php echo $family->id; ?>" data-relation="<?php echo $family->relations; ?>"><?php echo $family->name.'('.$age.' Years Old)'; ?></option>            
                                                            <?php
                                                                    }
                                                                }
                                                            ?>
                                                            
                                                            <!-- spouse -->
                                                            <?php   
                                                                if ($family->relation == 3){ 
                                                            ?>
                                                                <option value="<?php echo $family->id; ?>" data-relation="<?php echo $family->relations; ?>"><?php echo $family->name; ?></option>            
                                                            <?php
                                                                }
                                                            ?>

                                                    <?php endforeach ?>
                                                </select>
                                            </div> 
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="row form-group">
                                            <div class="col-lg-4">
                                                <label for="relation"><b>Relation</b> <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col">
                                            <input type="text" class="form-control " name="relation" id="relation" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()" required readonly>
                                            </div> 
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <div class="col">
                                        <label for="amount_charge"><b>Amount Charge</b> <span class="text-danger">*</span></label>
                                        <div class="input-group ">
                                            <div class="input-group-append">
                                                <span class="input-group-text bg-light">RM</span>
                                            </div>
                                            <input type="number" class="form-control currency_input" placeholder="0.00" name="amount_charge" id="amount_charge" onchange="formCheck()" onkeyup="formCheck()" min="0.00" max="9999999999.99" step="0.01" required>
                                        </div>
                                    </div>

                                    <div class="col">
                                        <label for="amount_claim"><b>Amount Claim</b> <span class="text-danger">*</span></label>
                                        <div class="input-group ">
                                            <div class="input-group-append">
                                                <span class="input-group-text bg-light">RM</span>
                                            </div>
                                            <input type="number" class="form-control currency_input" placeholder="0.00" name="amount_claim" id="amount_claim" onchange="formCheck()" onkeyup="formCheck()" min="0.00" max="9999999999.99" step="0.01" required>
                                        </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-body">
                    <div class="card no-shadow">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-12 col-lg-10">
                                    <h4>Attachment</h4>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal_add_item" id="btnaddAttachment">
                                            <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 mb-3">
                        <button type="submit" class="btn btn-success text-white" id="saveBtn"><i class="fas fa-save"></i> Save</button>
                    </div>
                </div>

            </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 mx-auto text-center">
                        <h4>Not allowed to claim outpatient.Allocation already empty.</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 (Outpatient)</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="attachment_description"><b>Description</b></label>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col">
                            <textarea class="form-control" id="attachment_description" rows="5" placeholder="Attachment's descriptive information " required></textarea>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-8">
                           <input type="file" class="form-control form-control-sm" name="files" id="upload-attachment" required>
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-primary btn-sm btn-block" id="attachment_save_btn"><i class="fas fa-save"></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); ?>; //2018
    var claim_month = <?php echo $this->uri->segment(5); ?>; //8
    

    <?php if($is_previous_claimable == true && $is_previous_2_claimable == true): ?>
        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');
    <?php else: ?>
        var date = new Date();
        var full_start_date     = date.setFullYear(claim_year,claim_month , 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(){
        

        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
        });

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

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

        });

        //reset form data everytime button attachment click
        $('#btnaddAttachment').click(function(){
            $('#attachment_form').trigger('reset'); 
        });

    });

    //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('#outpatient_form');
        patientInfo();
        // 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;
                iziToast.error({
                    title: 'Error',
                    message: 'Please enter a valid date format.(<?php echo date('d-m-Y'); ?>) '
                });

                $('#notice_date').html('Please enter a valid date format : day-month-year (<?php echo date('d-m-Y'); ?>) ');
            }else{
                $('#notice_date').empty();
            }
        }

        var claim_able_date = isWithinClaimableDate();
        if(!claim_able_date){
            is_filled = false;
            iziToast.error({
                title: 'Error',
                message: 'Date is not within date period('+start_claim+' - '+end_claim+')'
            });
            $('#notice_date').html('<br/> Date is not whithin date period : ( '+start_claim+' - '+end_claim+' )');
            // console.log(start_claim+' '+end_claim);
        }else{
            $('#notice_date').empty();
        }

        if(!isAllowedProrate(input.amount_claim,input.date))
        {
            is_filled = false;
        }

        //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;
                iziToast.error({
                    title: 'Error',
                    message: 'Amount claim and amount charge cannot be negative'
                });
                $('#notice_charge').html('Amount claim and amount charge cannot be negative');
            }

            if(parseFloat(input.amount_claim) > parseFloat(input.amount_charge)){
                is_filled = false;
                number_condition = false;
                iziToast.error({
                    title: 'Error',
                    message: 'You cannot claim more than what have been charged'
                });
                $('#notice_charge').html('You trying to claim more than what have been charged');
            }
            
            if(number_condition){
                $('#notice_charge').empty();
            }
        }else{
            $('#notice_charge').empty();
        }



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

    function populatetable() 
    {
        var table   = $('.table').DataTable();
            table.clear().draw();

        $.each(attachments,function(index,value){            
            var rowCount = table.data().count();
            table.row.add({
                0   : ++rowCount,
                1   : value.description,
                2   : '<a href="" target="_blank">'+value.orig_name+'</a>',
                3   : '<td class="text-center">\
                        <div 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>\
                        </div>\
                    </td>',
            }).draw();
        });  
    }

    function removeAttachment(index)
    {
        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;
    }


    /**
     * version 2.0 :
     */
    function isAllowedProrate(amount_claim,date)
    {
        if(amount_claim == '' || date == '')
        {
            return false;
        }else{
            let month = moment(date,'DD-MM-YYYY').month()+1;
            let segment = '<?php echo $this->uri->segment(5); ?>'
            // console.log(segment-month);
            if(segment - month == -10 || segment - month == 2)
            {
                var allocation_balanced = <?php echo $last_2_month_allocation_balance; ?>;
            }else{
                var allocation_balanced = <?php echo $last_month_allocation_balance; ?>;
            }

            if(amount_claim > allocation_balanced)
            {
                iziToast.error({
                    title: 'Error',
                    message: 'You are trying to claim more than allocation balanced. Your allocation balanced are : RM'+allocation_balanced
                });
                return false;
            }else{
                return true;
            }
        }

        // let allocation_balanced = 0;
        // iziToast.error({
        //     title: 'Error',
        //     message: 'You trying to claim more than allocation balance.You allocation balanced are :'+allocation_balanced
        // });
    }


    /*
    function isNotAllowedProrate(amount_claim)
    {
        //get prorate 
        let prorate = <?php echo ($allocation)?$allocation:0; ?>;
        //get approved claim
        let approved = <?php echo ($approved_claims)?$approved_claims:0; ?>
        //draft (status incomplete)
        let draft = <?php echo ($draft_claims)?$draft_claims:0; ?>;
    
        allowed_claim = prorate - (approved + draft);
        if(amount_claim >= allowed_claim)
        {
            return true;
        }else{
            return false;
        }
    }
    */

    function patientInfo() 
    {
        var relation = $('#patient').find(':selected').data('relation');
        $('#relation').val(relation);
    }

    function checkMedical(elem) 
    {
        let val = $(elem).prop('checked');
        if (val == true){
            $('#patient').attr('disabled','disabled');
            $("#patient option[data-relation='self']").prop("selected", true).trigger('change');

            $('#treatment').val('Medical Screening');
            $('#treatment').attr('disabled','disabled');

        }else{
            $('#patient').removeAttr('disabled');
            $('#treatment').val('');
            $('#treatment').removeAttr('disabled');

        }
    }
</script>
