$(document).ready(function(){
    //$(".select2").select2();
    //console.log(base_url);
    //console.log($('input[name="locationthemes"]:checked').serialize());

    //or
    
    $('input[name="locationthemes"]:checked').each(function() {
       //console.log(this.value);
    }); 
    $('.calc_row').on('change',function(){
        var sum = 0.00;
        $('.calc_row:checked').each(function() {
            sum += parseFloat($(this).data('total'));
        });
        $('tfoot tr td:last').text(' ₹ '+parseFloat(sum).toFixed(2));
        
        if(!$(this).is(':checked')){
            var sell_id = $(this).val();
            $.ajax({
				url: base_url+'callback/sell-manage.php',
				type: 'POST',
				data: {action:'delete_sell',sell_id:sell_id},
				success: function (response) {
				        
				}
			});
        }
    });
    $('.check_all').on('change',function(){
        if($(this).is(':checked')){
            $('.calc_row').attr('checked','checked');
        }else{
            $('.calc_row').removeAttr('checked');
        }
        var sum = 0.00;
        $('.calc_row:checked').each(function() {
            sum += parseInt($(this).data('total'));
        });
        $('tfoot tr td:last').text(' ₹ '+parseFloat(sum).toFixed(2));
         $('.calc_row:not(:checked)').each(function() {
            var sell_id = $(this).val();
            $.ajax({
				url: base_url+'callback/sell-manage.php',
				type: 'POST',
				data: {action:'delete_sell',sell_id:sell_id},
				success: function (response) {
				        
				}
			});
         });
    });
    
    if( $('.calc_row').length>0){
        var sum = 0.00;
        $('.calc_row:checked').each(function() {
            sum += parseFloat($(this).data('total'));
        });
        $('tfoot tr td:last').text(' ₹ '+parseFloat(sum).toFixed(2));   
    } 
    if( $('.custom-range-select').length>0 ){
        $('.custom-range-select').on('change', function(){
            if($(this).val()=='custom_range'){
                $('.custom-range-wrap').show();
            }else{
                $('.custom-range-wrap').hide();
                $('.custom-range-wrap').val(' ');
            }
        });
    }
    
    if( $('.filter-by').length>0 ){
        $('.filter-by').on('click', function(){
            var start_date, end_date;
           var business_name = $('.business_name').val(); 
           var by_date = $('.custom-range-select').val();
           if(by_date=='custom_range'){
               start_date = $('input[name=start_date]').val();
               end_date = $('input[name=end_date]').val();
           }
           
        });
        
          $( function() {
              var todaydt = new Date();
                $("input[name=start_date]").datepicker({
                            autoclose: true,
                                dateFormat: "dd/mm/yy",
                                endDate: todaydt,
                            onSelect: function (date) {
                               //Get selected date 
                                var date2 = $('input[name=start_date]').datepicker('getDate');
                                //sets minDate to input[name=end_date]
                                $('input[name=end_date]').datepicker('option', 'minDate', date2);
                            }
                        });
                        $('input[name=end_date]').datepicker({
                            dateFormat: "dd/mm/yy",
                            
                        });
              });
    }
    
    // PO REquests
    if($('#product_val').length>0 ){
        $('#product_val').on('keyup', function(){
            var pro_name = $(this).val(); 
            var product = [];
    		/*Initializing array with already fetched product*/
            $("tr.product").each(function(){
                product.push($(this).attr('data-id'));
            });
            
            $.ajax({
				url: base_url+'callback/po-request.php',
				type: 'POST',
				data: {action:'get_product_name',pro_name:pro_name, product:product},
				success: function (response) {
				    if(response){
				        $('.product-container').show();
				      $('.product-container').html(response);
				    }  else{
				        $('.product-container').hide();
				    }
				}
			});
        });
         $(document).on('click', '.select-product', function(){
           var pro_name = $(this).attr('data-id'); 
            $.ajax({
				url: base_url+'callback/po-request.php',
				type: 'POST',
				data: {action:'get_product',pro_name:pro_name},
				success: function (response) {
				        $('.product-container').hide();
				        $('#app_products tbody').append(response);
				       
                        var quantity = 0.00;
                        $('input.quantity').each(function() {
                            quantity += parseFloat($(this).val());
                        });
                        
                        var subtotal = 0.00;
                        $('.subtotal').each(function() {
                            subtotal += parseFloat($(this).text());
                        });
                        
                        $('.total_quantity').text(parseFloat(quantity));
                        
                        $('.price_total').text(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=amount]').val(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=quantity]').val(parseFloat(quantity));
                        
				}
			});
        });
        
        $(document).on('change', 'input.quantity', function(){
          var subtotal_app =  $(this).closest('tr').find('td.subtotal').attr('data-default');
          console.log(subtotal_app);
          var res = subtotal_app*$(this).val();
          var pro_id = $(this).attr('data-id');
          $(this).closest('tr').find('td.subtotal').text(parseFloat(res).toFixed(2));
          $(this).closest('tr').find('input[name="po['+pro_id+'][price]"]').val(parseFloat(res).toFixed(2));
          
          var qun = $(document).find('input.quantity');
                        var quantity = 0.00;
                        $(qun).each(function() {
                            quantity += parseFloat($(this).val());
                        });
                        
                        var subtotal = 0.00;
                        $('.subtotal').each(function() {
                            subtotal += parseFloat($(this).text());
                        });
                        
                        $('.total_quantity').text(parseFloat(quantity));
                        
                        $('.price_total').text(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=amount]').val(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=quantity]').val(parseFloat(quantity));
                        
        });
        
         $(document).on('click', '.remove_product', function(){
            var product_id = $(this).attr('data-id');
            var po_req_id = $(this).attr('data-rid');
            var _this = $(this);
            if(po_req_id){
                        
                if($('#app_products > tbody > tr.product').length>1){
                    
                     if(confirm('Are you sure you really want to delete this product?')){
                          $(_this).closest('tr').remove();
                          var quantity = 0.00;
                            $('input.quantity').each(function() {
                                quantity += parseFloat($(this).val());
                            });
                            
                            var amount = 0.00;
                            $('.subtotal').each(function() {
                                amount += parseFloat($(this).text());
                            });
                        $.ajax({
            				url: base_url+'callback/po-request.php',
            				type: 'POST',
            				data: {action:'delete_po_product', product_id:product_id, po_req_id:po_req_id, quantity:quantity, amount:amount},
            				success: function (response) {
            				     if(response){
            				         alert('Product has been removed successfully.');
            				         window.location.reload();
            				     }else{
            				         alert('Something went wrong please try again.');
            				     }   
            				}
            			});
                     }
                }else{
                    alert('Please select another product before empty complete rows.');
                }
            }else{
                 $(_this).closest('tr').remove();
                        var qun = $(document).find('input.quantity');
                        var quantity = 0.00;
                        $(qun).each(function() {
                            quantity += parseFloat($(this).val());
                        });
                        
                        var subtotal = 0.00;
                        $('.subtotal').each(function() {
                            subtotal += parseFloat($(this).text());
                        });
                        
                        $('.total_quantity').text(parseFloat(quantity));
                        
                        $('.price_total').text(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=amount]').val(parseFloat(subtotal).toFixed(2));
                        
                        $('input[name=quantity]').val(parseFloat(quantity));
            }
        });
        
        $(document).click(function (e)
        {
            var container = $(".search-container");
        
            if (!container.is(e.target))
            {
                $('.product-container').hide();
            }
        });
    }
    $('.execute-po').on('click', function(){
        if(confirm('Are you sure you want to execute PO?')){
            if(confirm('All checked requests will be transferred in respective list of suppliers')){
                $.ajax({
    				url: base_url+'callback/po-request.php',
    				type: 'POST',
    				dataType: 'json',
    				data: {action:'execute_po'},
    				success: function (response) {
    				    //console.log(response);
    				    $('.noti__item .quantity').text(' ');
    				    $('.notifi__title').html('');
    				    $('.notify__links').html('');
                        if(response){
                            $('.noti__item .quantity').text(response.count);
                            $('.notifi__title').html('<p>You have '+response.count+' Notifications</p>');
                            $('.notify__links').append(response.data);
                            alert('PO Executed successfully.');
                        }
                        //window.location.reload();
                        window.location.href = "https://app.divyaproducts.in/suppliers.php";
    				}
    			});
            }
        }
    });
    
    $('.noti__item i').on('click', function(){
        $.ajax({
			url: base_url+'callback/po-request.php',
			type: 'POST',
			data: {action:'remove_alert_count'},
			success: function (response) {
			    //console.log(response);
                if(response){
                    $('.noti__item .quantity').text(' ');
                }
			}
		});
    });
     $('.vendor_executed').on('click', function(){
         var vendor_executed = $(this).attr('data-id');
        $.ajax({
			url: base_url+'callback/po-request.php',
			type: 'POST',
			data: {action:'add_vendor_executed', vendor_executed:vendor_executed},
			success: function (response) {
			    //console.log(response);
                if(response){
                    window.location.reload();
                }
			}
		});
    });
    
    $(document).on('click', '.blink-text', function(e){
        
        e.preventDefault();
        
         var supplier_id = $(this).attr('id');
         var supplier_href = $(this).attr('href');
         
        $.ajax({
			url: base_url+'callback/po-request.php',
			type: 'POST',
			data: {action:'supplier_view', supplier_id:supplier_id},
			success: function (response) {
			    console.log(response);
                if(response){
                    window.location.href = supplier_href;
                }
			}
		});
    });
    
	function load_bulk_notifications(base_url){
	     $.ajax({
    				url: base_url+'callback/po-request.php',
    				type: 'POST',
    				dataType: 'json',
    				show: 'true',
    				data: {action:'bulk_execute_po'},
    				success: function (response) {
    				    //console.log(response);
    				    $('.noti__item .quantity').text(' ');
    				    $('.notifi__title').html('');
    				    $('.notify__links').html('');
                        if(response){
                            $('.noti__item .quantity').text(response.count);
                            $('.notifi__title').html('<p>You have '+response.count+' Notifications</p>');
                            $('.notify__links').append(response.data);
                            
                            if(response.vender_id!=null){
                                $.each(response.vender_id , function(index, val) { 
                                  if(val && !$('#'+val).hasClass('blink-text')){
                                      $('#'+val).addClass('blink-text');
                                  }
                                });
                            }
                        }
                       // window.location.reload();
    				}
    			});
	}
	load_bulk_notifications(base_url);
	setInterval(function(){
		load_bulk_notifications(base_url)
	}, 30000);
});