var loadingImage = '<img style="width:100px!important" src="../plugins/images/main_loading.gif" alt="Wait Loading...." title="Wait Loading....">';
var autoInc=1;
function parse_float(rString){rString=parseFloat(rString);if(isNaN(rString))rString=0;return rString;}
function parse_int(rString){rString=parseInt(rString);if(isNaN(rString))rString=0;return rString;}
function t(a){console.log(a);}
function swMessage(msgData){ 
    swal({
        title: msgData,
        timer: 5000, 
    });
}
function remove_row_by_id(rowId){
    swal({
        title: 'Are you sure to delete tnis?',
        text: '',
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#27ae60",
        confirmButtonText: "Continue",
        cancelButtonText: "Cancel",
        }, function (isConfirm) {
            if (isConfirm) {
                $('#'+rowId).remove();
            } 
    });
    //var checkConfirm = confirm('Are you sure to delete tnis?');if(checkConfirm == true){$('#'+rowId).remove();}
    return true;//return currently not use
}

function mainCategoryChange(){
    let category=parse_int($('#category').val());
    if(typeof(NEED_ALL_FOR_FIRST_SELECT)=='undefined'){
        $('#subCategory').html('<option value="">Select sub category</option>');
    }
    else{
        $('#subCategory').html('<option value="">All</option>');
    }
    if(category>0){
        let count = 0;
        $.each(categoryData[category].childCategory,function(a,b){
            count++;
        });
        $.each(categoryData[category].childCategory,function(a,b){
            let sel = '';
            if(count==1){
                sel = 'selected';
            }
            $('#subCategory').append('<option '+sel+' value="'+b.id+'">'+b.title+'</option>');
        });

    }
    select2Call();
}
function purchaseSubCategoryChange(){  
    let subCategory=parse_int($('#subCategory').val());
    if(typeof(NEED_ALL_FOR_FIRST_SELECT)=='undefined'){
        $('#pID').html('<option value="">Select Product</option>');
    }
    else{
        $('#pID').html('<option value="">All</option>');
    }
    if(typeof(productData)!='undefined'){
        let count = 0;
        $.each(productData,function(a,b){
            if(b.pc==subCategory){
                count++;
            }
        });
        $.each(productData,function(a,b){
            if(b.pc==subCategory){
                let sel = '';
                if(count==1){  
                    sel = 'selected'; 
                    saleProductChange(a);
                }
                $('#pID').append('<option '+sel+' value="'+a+'">'+b.t+'</option>');
            }
        });
    }
    select2Call();

}

function saleProductChange(pID){
    if(typeof(productData[pID])!=="undefined"){
        let p=productData[pID];
        t(p);
        $('#productSalePrice').val(p.s);
        $('#product-tp').val(p.s);
        $('#qtyLabel').html(p.u);
    }
    else{
        $('#productSalePrice').val('');
        $('#qtyLabel').html('');  
    }
    saleRowTotal()
}
function productDiscount(id){
    let main_id = $(id).closest('tr').attr('id');
    let discount = parse_float($(id).val());
    let sub_total = parse_float($('#'+main_id+' .sub_total').html());
    let total =  sub_total - discount;
    $('#'+main_id+' .total').html(total);
    productSaleSubTotal();
}
function productSaleSubTotal(){
    let total=0;
    let total_product_discount=0;
    $('#saleProducts .pID').each(function(a,b){
        let tID=$(this).closest('tr').attr('id');
        let pID = $('#'+tID+' .pID').val();
        //let p=productData[pID]; 
        //let qty=parse_float($('#'+tID+' .qty').html());
        let tt =parse_float($('#'+tID+' .total').html());
        let discount =parse_float($('#'+tID+' .discunt').val());
        // let tt=salePrice*qty;
        //t('#'+tID+' .unitPrice');

        total_product_discount+=discount;
        total+=tt;
    });
    $('#subTotal').html(total.toFixed(2));
    $('#total_product_discount').html(total_product_discount.toFixed(2));
    let discount=parse_float($('#saleDiscount').val());
    let netPayable=total-discount;
    $('#netPayable').html(netPayable.toFixed(2));
}
function saleRowTotal(){
    let product_tp=parse_float($('#product-tp').val());
    let salePrice=parse_float($('#productSalePrice').val());
    let qty=parse_float($('#productSaleqty').val()); 
    let pID = parse_int($('#pID').val());
    let discount = 0;  
    if(typeof(productData[pID])!=="undefined"){
        let p=productData[pID];
        discount = product_tp-salePrice;
        let free_qty = 0;
        if(p.get_one_free>0){
            if(qty>p.get_one_free){
                free_qty = parse_int(qty/p.get_one_free);
            } 
        }
        if(free_qty>0){
            $('#freeQTY').val(free_qty);
        }
        else{
            $('#freeQTY').val('');
        }
    }
    else{
        $('#freeQTY').val('');
    }
    let total_discount = (qty*discount).toFixed(2);

    let total=(salePrice*qty).toFixed(2);
    $('#product-discount').val(total_discount);
    $('#total').val(total);
}  
function productSaleAddToCart(){
    let category    = parse_int($('#category').val());
    let subCategory    = parse_int($('#subCategory').val());
    let pID         = parse_float($('#pID').val());
    errorSet=0;
    let salePrice_tp   = parse_float($('#product-tp').val());
    let salePrice   = parse_float($('#productSalePrice').val());
    let qty         = parse_int($('#productSaleqty').val());
    let free_qty         = parse_int($('#freeQTY').val());

    if(USE_PRODUCT_CATEGORY==1 && category<=0 ){swMessage('Please select a category');errorSet=1;}
    else if(USE_PRODUCT_CATEGORY==1 && typeof(categoryData[category])== "undefined"){swMessage('invalid category');errorSet=1;}
        else if(USE_PRODUCT_CATEGORY==1 && subCategory<=0 ){swMessage('Please select a sub category');errorSet=1;}
            else if(USE_PRODUCT_CATEGORY==1 && typeof(categoryData[category].childCategory[subCategory])== "undefined"){swMessage('invalid category');errorSet=1;}
                else if(pID<=0){swMessage('Please select a product');errorSet=1;}
                    else if(qty<=0){swMessage('Please enter a valid Quantity');errorSet=1;}
                        else if(free_qty<0){swMessage('Please enter a valid free Quantity');errorSet=1;}
    if(errorSet==0){
        let p=productData[pID];

        let total_qty=qty+free_qty;
        if(p.st<total_qty){swMessage('Product stock out!');errorSet=1;}
        else if(p.s<salePrice){swMessage('Invalid sale price.');errorSet=1;}
            else if(p.s>0&&salePrice==0){swMessage('Invalid discount.');errorSet=1;}
                else{
                    let total_discount = (salePrice_tp-salePrice)*qty

                    let sub_total=(salePrice_tp*qty).toFixed(2);
                    let total=(salePrice*qty).toFixed(2);
                    let c,sc;
                    if(USE_PRODUCT_CATEGORY==1){
                        let c=categoryData[category];
                        let sc=categoryData[category].childCategory[subCategory];
                    }
                    let id='pd_'+pID+'_'+autoInc;autoInc++;
                    $('#saleProductsTr .pID').val(pID);
                    if(USE_PRODUCT_CATEGORY==1){
                        $('#saleProductsTr .category').html(c.title)
                        $('#saleProductsTr .subCategory').html(sc.title)
                    }
                    $('#saleProductsTr .pTitle').html(p.t);
                    $('#saleProductsTr .unTitle').html(p.u);
                    $('#saleProductsTr .salePrice-tp ').html(salePrice_tp.toFixed(2));
                    $('#saleProductsTr .salePrice ').html(salePrice.toFixed(2));
                    $('#saleProductsTr .qty').html(qty);
                    $('#saleProductsTr .free_qty').html(free_qty);
                    $('#saleProductsTr .total_qty').html(total_qty);
                    $('#saleProductsTr .total').html(total);
                    $('#saleProductsTr .discunt').html(total_discount.toFixed(2));
                    $('#saleProductsTr .sub_total').html(sub_total);
                    $('#saleProductsTr .remove').attr('onclick','remove_row_by_id(\''+id+'\');productSaleSubTotal()')
                    var purchaseProductsTr=$('#saleProductsTr').html();
                    //        t('purchaseProductsTr')
                    //        t(purchaseProductsTr)
                    $('#saleProducts').append('<tr id="'+id+'">'+purchaseProductsTr+'</tr>');
                    $('#pID').val('');
                    $('#productSalePrice').val('');
                    $('#product-tp').val('');
                    $('#product-discount').val('');
                    $('#total').val('');
                    $('#productSaleqty').val('');
                    $('#freeQTY').val('');
                    $('#subCategory').val('');
                    $('#category').val('');
                    select2Call();
                    let tr_sl_start=1;$('#saleProducts .autoSerial').each(function(){$(this).html(tr_sl_start);tr_sl_start++;});
                    productSaleSubTotal();
                }
    }
}
function doctor_visit(){
    let entry_date = $('#entry-date').val();
    let houre = $('#houre').val();
    let minuet = $('#minuet').val();
    let doctor_id = parse_int($('#doctor-id').val());
    let prescription = parse_int($('#prescription').val());
    let note = $('#note').val();
    if(doctor_id<=0 ){swMessage('Please select a doctor');}
    else{
        buttonLoading('doctor_visit');
        let finished_product = visit_product_data('#finished-product');
        if(finished_product==false){button_loading_destroy('doctor_visit','SUBMIT');return 0;}
        let gift_product = visit_product_data('#gift-product');
        if(gift_product==false){button_loading_destroy('doctor_visit','SUBMIT');return 0;}
        let post_dtaa={
            module:'doctor_visit',
            entry_date:entry_date,
            houre:houre,
            minuet:minuet,
            doctor_id:doctor_id,
            prescription:prescription,
            finished_product:finished_product,
            gift_product:gift_product,
            note:note,
        };
        $.ajax({
            type:'post',
            url:ajUrl,
            data:post_dtaa,
            success:function(data){
                button_loading_destroy('doctor_visit','SUBMIT');
                if(typeof(data.status)  !== "undefined"){ 
                    if(data.status==1){
                        $('#doctor-id').val('');
                        $('#houre').val('00');
                        $('#minuet').val('00');
                        $('#prescription').val('');
                        $('#note').val('');
                        $('#finished-product').html('');
                        $('#gift-product').html('');
                        select2Call();
                    }
                    swMessageFromJs(data.m);
                }
                else{
                    swMessage(AJAX_ERROR_MESSAGE); 
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                button_loading_destroy('doctor_visit','SUBMIT');
                swMessage(AJAX_ERROR_MESSAGE); 
            }
        });
    }
}
function customer_visit(){
    let entry_date = $('#entry-date').val();
    let houre = $('#houre').val();
    let minuet = $('#minuet').val();
    let customer_id = parse_int($('#customer-id').val());
    let note = $('#note').val();
    if(customer_id<=0 ){swMessage('Please select a customer');}
    else{
        buttonLoading('customer_visit');
        let finished_product = visit_product_data('#finished-product');
        if(finished_product==false){ button_loading_destroy('customer_visit','SUBMIT');return 0;}
        let gift_product = visit_product_data('#gift-product');
        if(gift_product==false){ button_loading_destroy('customer_visit','SUBMIT');return 0;}
        let post_dtaa={
            module:'customer_visit',
            entry_date:entry_date,
            houre:houre,
            minuet:minuet,
            customer_id:customer_id,
            finished_product:finished_product,
            gift_product:gift_product,
            note:note,
        };
        $.ajax({
            type:'post',
            url:ajUrl,
            data:post_dtaa,
            success:function(data){
                button_loading_destroy('customer_visit','SUBMIT');
                if(typeof(data.status)  !== "undefined"){ 
                    if(data.status==1){
                        $('#customer-id').val('');
                        $('#houre').val('00');
                        $('#minuet').val('00');
                        $('#note').val('');
                        $('#finished-product').html('');
                        $('#gift-product').html('');
                        select2Call();
                    }
                    swMessageFromJs(data.m);
                }
                else{
                    swMessage(AJAX_ERROR_MESSAGE); 
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                button_loading_destroy('customer_visit','SUBMIT');
                swMessage(AJAX_ERROR_MESSAGE); 
            }
        });
    }
}
function bazar_visit(){
    let entry_date = $('#entry-date').val();
    let houre = $('#houre').val();
    let minuet = $('#minuet').val();
    let bazar_id = parse_int($('#bazar-id').val());
    let note = $('#note').val();
    if(bazar_id<=0 ){swMessage('Please select a area');}
    else{
        buttonLoading('bazar_visit');
        let post_dtaa={
            module:'bazar_visit',
            entry_date:entry_date,
            houre:houre,
            minuet:minuet,
            bazar_id:bazar_id,
            note:note,
        };
        $.ajax({
            type:'post',
            url:ajUrl,
            data:post_dtaa,
            success:function(data){
                button_loading_destroy('bazar_visit','SUBMIT');
                if(typeof(data.status)  !== "undefined"){ 
                    if(data.status==1){
                        $('#bazar-id').val('');
                        $('#houre').val('00');
                        $('#minuet').val('00');
                        $('#note').val('');
                        select2Call();
                    }
                    swMessageFromJs(data.m);
                }
                else{
                    swMessage(AJAX_ERROR_MESSAGE); 
                }
            },
            error: function() {
                button_loading_destroy('bazar_visit','SUBMIT');
                swMessage(AJAX_ERROR_MESSAGE); 
            }
        });
    }
}
function visit_product_data(id){
    let products={};
    let error=0;
    $(id+' .product-id').each(function(a,b){
        let tID=$(this).closest('tr').attr('id');
        let product_id         = parse_int($('#'+tID+' .product-id').val());
        let qty         = parse_float($('#'+tID+' .qty').html());
        if(typeof(products[product_id])!=='undefined'){swMessage('Same product add.'); error=1; return 0;}

        products[product_id]={
            quaintity:qty,
            product_id:product_id,
        }
    });
    if(error==1){
        return false;
    }
    return products;

}
function product_details_load(id){
    let product_id = parse_int($('#'+id+'-product-id').val());
    let unit ='--';
    if(product_id>0){
        let product= product_details[id][product_id];
        unit =  product.u;
    }
    $('#'+id+'-unit').html(unit);

}
function visit_card_add(id){
    let error=0;
    let product_id  = parse_int($('#'+id+'-product-id').val());
    let qty         = parse_int($('#'+id+'-quantity').val());

    if(product_id<=0){swMessage('Please select a product');errorSet=1;}
    else if(qty<=0){swMessage('Please enter a valid Quantity');errorSet=1;}
        else{
            let tr_id='pd_'+product_id+'_'+id+'_'+autoInc;autoInc++;
            let card_id = '#card-product';
            let product_title = $('#'+id+'-product-id-'+product_id).text(); 
            let product_unit = $('#'+id+'-unit').html(); 
            $(card_id+' .product-id').val(product_id);
            $(card_id+' .product-title').html(product_title);
            $(card_id+' .unit').html(product_unit);
            $(card_id+' .qty').html(qty);

            $(card_id+' .remove').attr('onclick','remove_row_by_id(\''+tr_id+'\');')
            let card_tr=$(card_id).html();
            $('#'+id+'-product').append('<tr id="'+tr_id+'">'+card_tr+'</tr>');
            $('#'+id+'-product-id').val('');
            $('#'+id+'-unit').html('--');
            $('#'+id+'-quantity').val('');
            select2Call();
            let tr_sl_start=1;$('#'+id+'-product .autoSerial').each(function(){$(this).html(tr_sl_start);tr_sl_start++;});
        }
}
function productsSaleDraft(){
    buttonLoading('productsSaleDraft');
    let draftID = parse_int($('#draftID').val());
    let pay_type = parse_int($('#pay-type').val());
    let cID = parse_int($('#cID').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 products= {};
    let count=0;
    errorSet=0;
    if(cID<=0){swMessage('Please select a customers.');errorSet=1;}
    else if(USER_TYPE!=1&&base_id<1){swMessage('Please select a MPO.');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){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 free_qty         = parse_float($('#'+tID+' .free_qty').html());
                let total_qty         = parse_float($('#'+tID+' .total_qty').html());
                let salePrice_tp        = parse_float($('#'+tID+' .salePrice-tp').html());
                let salePrice   = parse_float($('#'+tID+' .salePrice').html());
                let product_discount    = parse_float($('#'+tID+' .discunt').html());
                let total   = parse_float($('#'+tID+' .total').html());
                if(product_discount>salePrice){swMessage('Invalid discount.');errorSet=1;}
                if(!products.hasOwnProperty(pID)){
                    products[pID]={
                        qty:qty,
                        free_qty:free_qty,
                        total_qty:total_qty,
                        salePrice_tp:salePrice_tp,
                        salePrice:salePrice,
                        discount:product_discount
                    }
                }
                else{
                    swMessage('Some product you select multiple time. Please remove one.');errorSet=1;
                }
                count++;
            }
        });
        if(count==0){errorSet=1;swMessage('select a product');}
        else{

            let postData={
                module:'productsSaleDraft',
                cID:cID,
                pay_type:pay_type,
                base_id:base_id,
                due_day:due_day,
                saleDate:saleDate,
                products:products,
                discount:discount,
                note:note,

            };
            $.ajax({
                type:'post',
                url:ajUrl,
                data:postData,
                success:function(data){
                    console.log('success') ;
                    button_loading_destroy('productsSaleDraft','Draft');
                    if(typeof(data.status)  !== "undefined"){ 
                        if(data.status==1){
                            $('#cID').val('');
                            $('#base_id').val('');
                            $('#due_day').val('');
                            $('#pay-type').val('');
                            $('#saleDiscount').val('');
                            $('#saleProducts').html('');
                            select2Call();
                            productSaleSubTotal();
                        }
                        swMessageFromJs(data.m);
                    }
                    else{
                        swMessage(AJAX_ERROR_MESSAGE); 
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log('error') ;
                    button_loading_destroy('productsSaleDraft','Draft');
                    swMessage(AJAX_ERROR_MESSAGE); 
                }
            });
        }
    }
    if(errorSet==1){
        button_loading_destroy('productsSaleDraft','Draft');   
    }
}
function customer_visit_details_view(id){
    $('#modal_title').html("Customer visit details");
    $('#details-body').html(loadingImage);
    $.ajax({
        type:'post',
        url:ajUrl,
        data:{module:'customer_visit_details_view',id:id},
        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 buttonLoading(classAdd){

    $('.'+classAdd).addClass("disable");
    $('.'+classAdd).attr("disabled",true);
    $('.'+classAdd).html("<i class='fa fa-spinner fa-spin '>");
}
function button_loading_destroy(classAdd,test){
    $('.'+classAdd).removeAttr('disabled');;
    $('.'+classAdd).html(test);
    $('.'+classAdd).removeClass("disable");
}

$(document).on('change','#category',function(){mainCategoryChange();purchaseSubCategoryChange()}); 
$(document).on('change','#subCategory',function(){purchaseSubCategoryChange()}); 

$(document).on('keyup','#discount',function(){purchaseSubTotal();});
$(document).on('keyup change','#productSaleqty,#productSalePrice',function(){saleRowTotal();});  

$(document).on('keyup','#saleDiscount',function(){productSaleSubTotal();});
  
