var contra_voucher={
    list(){
        let debit=$('#s_debit').val();
        let credit=$('#s_credit').val();
        ajax_report_request({contra_list:1,debit:debit,credit:credit},'trDetailsArea');
    },
    validation(){
        const date              = $('#date').val();
        const base_id           =parse_int( $('#base_id').val());
        const debit             =parse_int( $('#debit').val());
        const credit            =parse_int($('#credit').val());
        const amount            =parse_float($('#amount').val());
        const reference         = $('#reference').val();
        const transaction_charge= parse_float($('#transaction_charge').val());
        const note              = $('#note').val();
        if(debit<1){
            swMessage('Please select debit account');
            return false;
        }
        if(credit<1){
            swMessage('Please select credit account');
            return false;
        }
        if(amount<=0){
            swMessage('Please enter amount');
            return false;
        }
        const post_data = {
            date                : date,
            base_id             : base_id,
            debit               : debit,
            credit              : credit,
            amount              : amount,
            reference           : reference,
            transaction_charge  : transaction_charge,
            note                : note
        };
        return post_data;
    },
    add(){
        buttonLoading('add_button');
        const post_data = this.validation();
        post_data['contra_voucher_add'] = 1;
        let self = this;
        if(post_data){
            $.ajax({
                type:'post',
                url:ajUrl,
                data:post_data,
                success:function(data){
                    
                    if(typeof(data.status)  !== "undefined"){ 
                        if(data.status==1){
                            self.clear_form();
                        }
                        swMessageFromJs(data.m);
                    }   
                    else{
                        swMessage(AJAX_ERROR_MESSAGE);    
                    }
                    button_loading_destroy('add_button','Add');
                },
                error:function(data){
                    button_loading_destroy('add_button','Add');
                    swMessage(AJAX_ERROR_MESSAGE);  
                }
            });
        }
    },
    edit(){
        buttonLoading('edit_button');
        let post_data = false;
        const id = parse_int($('#id').val());
        if(id<1){
            swMessage('Invalid request');
        }
        else{
            post_data = this.validation();
            post_data['contra_voucher_edit'] = 1;
            post_data['id'] = id;
        }
        if(post_data){
            $.ajax({
                type:'post',
                url:ajUrl,
                data:post_data,
                success:function(data){
                    if(typeof(data.status)  !== "undefined"){ 
                        swMessageFromJs(data.m);
                    }   
                    else{
                        swMessage(AJAX_ERROR_MESSAGE);    
                    }
                    button_loading_destroy('edit_button','Update');
                },
                error:function(data){
                    button_loading_destroy('edit_button','Update');
                    swMessage(AJAX_ERROR_MESSAGE);  
                }
            });
        }
        else{
            button_loading_destroy('edit_button','Update');
        }
    },
    clear_form(){
        $('#base_id').val(0);
        $('#debit').val('');
        $('#credit').val('');
        $('#amount').val('');
        $('#reference').val('');
        $('#transaction_charge').val('');
        $('#note').val('');
        select2Call();
    },
    delete(id){
        are_you_sure(1,'Are you sure to delete this?',id,function(id){
            buttonLoading(`delete_${id}`);
            $.ajax({
                type:'post',
                url:ajUrl,
                data:{contra_voucher_delete:1,id:id},
                success:function(data){
                    if(typeof(data.status)  !== "undefined"){ 
                        if(data.status==1){
                            $('#contra_voucher_'+id).remove();
                        }
                        setTimeout(function(){
                            swMessageFromJs(data.m);
                        },100);
                    }   
                    else{
                        setTimeout(function(){
                            swMessage(AJAX_ERROR_MESSAGE);  
                        },100);
                    }
                    button_loading_destroy(`delete_${id}`,'Delete');
                },
                error:function(data){
                    setTimeout(function(){
                        swMessage(AJAX_ERROR_MESSAGE);  
                    },100);
                    button_loading_destroy(`delete_${id}`,'Delete');
                }
            });
        });
    }
}

//details 
function details_view(data){
    $('#details-body').html(loadingImage);
    $('#details-modal-title').html('Customer visit details');
    $.ajax({
        type:'post',
        url:ajUrl,
        data:data,
        success:function(data){
            $('#details-body').html('');
            if(typeof(data.status)!=='undefined'){
                if(data.status==1){
                    $('#details-body').html(data.html);
                }

                swMessageFromJs(data.m);
            }
            else{
                swMessage(AJAX_ERROR_MESSAGE); 
            }
        },
        error:function(){
            $('#details-body').html('');
            swMessage(AJAX_ERROR_MESSAGE); 
        }
    });
    $('#details-modal-btn').click();
}

function customer_visit_details_view(id){
    details_view({customer_visit_details_view:1,id:id});
}
function doctor_visit_details_view(id){
    details_view({doctor_visit_details_view:1,id:id});
}

function bazar_visit_details_view(id){
    doctor_visit_details_view({bazar_visit_details_view:1,id:id})
}


// sale
function productsSale(){
    buttonLoading('productsSale');
    $('#sale-print-btn').html('');
    let draftID = parse_int($('#draftID').val());
    let pay_type = parse_int($('#pay-type').val());
    let cID = parse_int($('#cID').val());
    let truk_rent_pay_by= parse_int($('#truk_rent_pay_by').val());
    let due_day = parse_int($('#due_day').val());
    let base_id = parse_int($('#base_id').val());
    let saleDate = $('#saleDate').val();
    let subTotal=parse_float($('#subTotal').html());
    let discount=parse_float($('#saleDiscount').val());
    let netPayable=parse_float($('#netPayable').html());
    let note = $('#note').val();
    let not_check_credit_limit = $('#not_check_credit_limit').is(':checked')?1:0;
   
    
    let products= {};
    let truk_list= {};
    let ade_list= {};
    let count=0;
    let truk_count=0;
    errorSet=0;

    if(cID<=0){swMessage('Please select a customers.');errorSet=1;}
    else if(base_id<1){swMessage('Please select a base.');errorSet=1;}
        else if(due_day<0){swMessage('Invalid due day.');errorSet=1;}
            else if(pay_type<1){swMessage('Please select a pay type.');errorSet=1;}
                else if(subTotal<0){swMessage('Please select product.');errorSet=1;}
                    else if(netPayable<0){
                        console.log('netPayable',netPayable)
                        swMessage('Invalid discount.');errorSet=1;

                    }


    if(errorSet==0){
        $('#saleProducts .pID').each(function(a,b){
            if(errorSet==0){
                let tID=$(this).closest('tr').attr('id');
                let pID                 = parse_int($('#'+tID+' .pID').val());
                let qty                 = parse_float($('#'+tID+' .qty').html());
                let sale_price           = parse_float($('#'+tID+' .salePrice').html());
                if(!products.hasOwnProperty(pID)){
                    products[pID]={
                        id          : pID,
                        qty         : qty,
                        sale_price   : sale_price
                    }
                    count++;
                }
                else{
                    swMessage('Some product you select multiple time. Please remove one.');errorSet=1;
                }
            }
        });
        $('#truk_list .truk_id').each(function(a,b){
            if(errorSet==0){
                let tID         = $(this).closest('tr').attr('id');
                let truk_id     = parse_int($('#'+tID+' .truk_id').val());
                let truk_rent   = parse_float($('#'+tID+' .truk_rent').html());
                if(!truk_list.hasOwnProperty(truk_id)){
                    truk_list[truk_id]={
                        truk_id:truk_id,
                        truk_rent:truk_rent
                    }
                    truk_count++;
                }
                else{
                    swMessage('Some truk you select multiple time. Please remove one.');errorSet=1;return;
                }
            }
        });
        $('#ade_list .truk_id').each(function(a,b){
            if(errorSet==0){
                let tID     = $(this).closest('tr').attr('id');
                let truk_id = parse_int($('#'+tID+' .truk_id').val());
                let ade_id  = parse_int($('#'+tID+' .ade_id').val());
                let pay_by  = parse_int($('#'+tID+' .pay_by').val());
                let amount  = parse_float($('#'+tID+' .amount').html());
                if(!ade_list.hasOwnProperty(truk_id)){
                    ade_list[truk_id]={
                        truk_id:truk_id,
                        pay_by:pay_by,
                        ade_id:ade_id,
                        amount:amount
                    }
                }
                else{
                    swMessage('Some additional expense you select multiple time. Please remove one.');errorSet=1;return;
                }
            }
        });
        if(count==0){errorSet=1;swMessage('Select a product');}
        else if(truk_count==0){errorSet=1;swMessage('select a truk');}
        if(errorSet==0){
            let postData={
                new_sale                : 1,
                not_check_credit_limit  : not_check_credit_limit,
                pay_type                : pay_type,
                draftID                 : draftID,
                cID                     : cID,
                base_id                 : base_id,
                due_day                 : due_day,
                saleDate                : saleDate,
                products                : products,
                discount                : discount,
                note                    : note,
                truk_rent_pay_by        : truk_rent_pay_by,
                truk_list               : truk_list,
                ade_list                : ade_list

            };
            $.ajax({
                type:'post',
                url:ajUrl,
                data:postData,
                success:function(data){
                    button_loading_destroy('productsSale','Sale');   
                    if(typeof(data.status)  !== "undefined"){ 
                        if(data.status==1){
                            $('#sale-print-btn').html('<a href="'+MAIN_URL+'/?print=sale&id='+data.sale_id+'" target="_blank" class="mt-1 btn-lg btn-success pull-right">Print</a>');
                            $('#cID').val('');
                            $('#saleDiscount').val('');
                            $('#saleProducts').html('');
                            $('#pay-type').html('');
                            $('#due_day').html('');
                            $('#base_id').html('');
                            select2Call();
                            productSaleSubTotal();

                        }
                        swMessageFromJs(data.m);
                    }
                    else{
                        swMessage(AJAX_ERROR_MESSAGE); 
                    }
                },
                error: function(data) { 
                    button_loading_destroy('productsSale','Sale');   
                    swMessage(AJAX_ERROR_MESSAGE); 
                }
            });

        }
    }
    if(errorSet==1){
        button_loading_destroy('productsSale','Sale');   
    }
}
function delete_sale_customer_change(customer_id){

    $('#customer_input_area .select2-container').attr('style','background-color:#FFFFFF');

    $.ajax({
        type:'post',
        url:ajUrl,
        data:{customerCurrentBalance:1,cID:customer_id},
        success:function(data){
            console.log('data',data)
            if(data.status==1){
                if(data.can_invoice==0){
                    $('#customer_input_area .select2-container').attr('style','background-color:red');
                }
            }
            //swMessageFromJs(data.m);
        },
        error:function(error) {
          console.log('Ajax Error:'+error);
        }   
    }); 

}
function income_and_expense_add(type){
    buttonLoading('income_and_expense_add');
    let date = $('#trDate').val();
    let base_id = parse_int($('#base_id').val());
    let debit = parse_int($('#debit').val());
    let credit = parse_int($('#credit').val());
    let amount = parse_float($('#amount').val());
    let note = $('#note').val();
    let error = 0;
    if(debit<1){swMessage('Please select debit account.');error=1;}
    else if(credit<1){swMessage('Please select credit account.');error=1;}
    else if(amount<=0){swMessage('Please enter amount.');error=1;}
    if(!error){
        $.ajax({
            type:'post',
            url:ajUrl,
            data:{
                income_and_expense_add:1,
                date:date,
                base_id:base_id,
                debit:debit,
                credit:credit,
                amount:amount,
                note:note,
                type:type
            },
            success:function(data){
                button_loading_destroy('income_and_expense_add','Add');
                if(typeof data.status !== 'undefined'){
                    if(data.status==1){
                        $('#base_id').val(0);
                        //$('#debit').val('');
                        //$('#credit').val('');
                        $('#amount').val('');
                        $('#note').val('');
                        select2Call();
                        income_expense_list(type);
                    }
                    swMessageFromJs(data.m);
                }
                else{
                    swMessage(AJAX_ERROR_MESSAGE);
                }
            },
            error:function(data){
                button_loading_destroy('income_and_expense_add','Add');
                swMessage(AJAX_ERROR_MESSAGE);
            }
        });
    }
    else{
        button_loading_destroy('income_and_expense_add','Add');
    }
}
