<style>
    .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">
                    <?php if($first_col_year != $second_col_year): ?>
                    <div class="col">
                        <?php echo $first_col_year; ?> <br>
                        RM<?php echo $first_col_prorate; ?>
                    </div>
                    <?php endif; ?>
                    <div class="col">
                        <?php echo $second_col_year; ?> <br>
                        RM<?php echo $second_col_prorate; ?>
                    </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($first_col_year != $second_col_year): ?>
                    <div class="col">
                        <?php echo $first_col_year; ?> <br>
                        RM<?php echo $first_col_approved; ?>
                    </div>
                    <?php endif; ?>
                    <div class="col">
                        <?php echo $second_col_year; ?> <br>
                        RM<?php echo $second_col_approved; ?>
                    </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($first_col_year != $second_col_year): ?>
                    <div class="col">
                        <?php echo $first_col_year; ?> <br>
                        RM<?php echo $first_col_pending; ?>
                    </div>
                    <?php endif; ?>
                    <div class="col">
                        <?php echo $second_col_year; ?> <br>
                        RM<?php echo $second_col_pending; ?>
                    </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">
                    <?php if($first_col_year != $second_col_year): ?>
                    <div class="col">
                        <?php echo $first_col_year; ?> <br>
                        RM<?php echo (!empty($first_col_balanced))?($first_col_balanced > 0)?$first_col_balanced:'0.00':'0.00'; ?>
                    </div>
                    <?php endif; ?>
                    <div class="col">
                        <?php echo $second_col_year; ?> <br>
                        RM<?php echo (!empty($second_col_balanced))?($second_col_balanced > 0)?$second_col_balanced:'0.00':'0.00'; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if($first_col_balanced > 0 || $second_col_balanced > 0): ?>
        <form method="post" action="" id="hospitalization_form">
            <div class="card no-shadow">
                <div class="card-body">
                    <h2><?php echo $Operation ?> Hospitalization Claim <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"><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'); ?>)">
                                        <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"><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">
                                    </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">
                                    </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="Applicable for employee, spouse and child below than 17 years old" >
                                            <i class="fas fa-info-circle"></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-lg-2">
                                <label for="day_warded"><b>No of Days Warded</b> <span class="text-danger">*</span></label>
                            </div>
                            <div class="col">
                                <input type="number" class="form-control positive_number" name="day_warded" id="day_warded" min="0" autocomplete="off" onchange="formCheck()" onkeyup="formCheck()" placeholder="No of days warded" >
                                <small><span class="text-danger" id="notice_day_warded"></span></small>
                            </div>
                            <div class="col-lg-2">
                                <b>Payment method </b>
                            </div>
                            <div class="col">
                                <select name="payment_method" id="payment_method" class="form-control">
                                        <option value="0">Cash</option>
                                        <option value="1">Premium Insurance</option>                                    
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group row">
                            <div class="col">
                                <div class="row">
                                    <div class="col-lg-4">
                                        <label for="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="amount_charge" id="amount_charge" onchange="formCheck()" onkeyup="formCheck()" min="0.01" step="0.01" >
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col">
                                <div class="row">
                                    <div class="col-lg-4">
                                        <label for="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="amount_claim" id="amount_claim" onchange="formCheck()" onkeyup="formCheck()"  min="0.01" step="0.01">
                                        </div>
                                        <small><span class="text-danger" id="notice_charge"></span></small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <span class="text-danger font-italic"><small>[NOTES : ] <br>* require <br>Please attach supporting documents for premium insurance if any</small></span>
                        <br>
                        <small><span class="text-danger font-italic" id="notice_attachment"></span></small>
                    
                        <div class="card no-shadow">
                            <div class="card-body bordered">
                                <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="row">
                                    <div class="col">
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-hover" width="100%" style="width:100%;">
                                                <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>
                                                <tbody></tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                </div>
                <div class="card-footer bg-white">
                    <div class="btn-group float-right">
                        <!-- <button type="button" class="btn btn-info">Cancel</button> -->
                        <button type="submit" class="btn btn-success" id="saveBtn"><i class="fas fa-save"></i> Save</button>
                    </div>
                </div>
        </form>
    <?php else: ?>
        <div class="card">
            <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 hospitalization.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 (Hospitalization)</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-lg-12">
                            <label for="item"><b>Description</b></label>
                        </div>
                        <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">
                        </div>
                        <div class="col">
                            <button type="submit" class="btn btn-primary btn-sm btn-block text-white"><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); ?>; //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');

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

    $('#hospitalization_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/createHospitalization/'); ?>';
            type    = 'POST',
            data    = 
            {
                token       : '<?php echo $_SESSION['token']; ?>',
                form        : JSON.stringify(formIdToInputObject('#hospitalization_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) ;
            //ajx req
        }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/1/'); ?>',
            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
                    });
                }
                
            }
        });

    });



    $(document).ready({
         
        /*
        $('#room_package').change(function(){
            let amount = $('#room_package option:selected').data('amount');
            $('#room_amount').val(amount);
        });
        */
    });

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

    function formCheck()
    {
        // return true; //TODO : remove before goind live
        iziToast.destroy();
        var is_filled = true;
        var input = formIdToInputObject('#hospitalization_form');
        patientInfo();

        //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({
                    position:'bottomRight',
                    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({
                position:'bottomRight',
                message: error,
            });
            $('#notice_date').html();
         }else{
            $('#notice_date').empty();
         }

        //validating day warded *off for covid swab test claim
        // if(input.day_warded.length > 0){
        //     if($.isNumeric(input.day_warded)){
        //         $('#notice_day_warded').empty();
        //         if(input.day_warded <= 0){
        //             is_filled = false;
        //             var error = 'Number of day warded need to be greater or equal to one';
        //             iziToast.error({
        //                 position:'bottomRight',
        //                 message: error,
        //             });
        //             $('#notice_day_warded').html(error); 
        //         }
        //     }else{
        //         is_filled = false;
        //         $('#notice_day_warded').html('Input is not a numeric value');
        //     }
        // }

        //checking if amount charge and amount claim are numbers
        //$.isNumeric(input.amount_charge) && $.isNumeric(input.amount_claim)
        
        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({
                    position:'bottomRight',
                    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({
                    position:'bottomRight',
                    message: error,
                });
                $('#notice_charge').html(error);
            }

            if(!is_claimable_amount())
            {
                is_filled = false;
            }

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


        if(input.date.length > 0)
        {
            if(!is_claimable_amount(input.date,input.amount_claim)  )
            {
            is_filled = false;
            }
        }

        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">\
                        <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;
    }

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

    /**
        if claim amount is less allocation balanced 
     */
    function is_claimable_amount(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 first_col_balanced  = <?php echo (!empty($first_col_balanced))?($first_col_balanced > 0)?$first_col_balanced:0:0; ?>;
        let second_col_balanced = <?php echo (!empty($second_col_balanced))?($second_col_balanced > 0)?$second_col_balanced: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 = second_col_balanced;
        }else{
            allocation_balanced = first_col_balanced;
        }

        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>