function getPrices()
{
    var vals = $('#mymultis').val();
    if(vals==null)
    {
      $('#org_price').val(0);
    }
    else
    {
        $.ajax({
            url:base_url+'offers/get_price',
            type:'POST',
            data:{vals:vals},
            success:function(response)
            {
                var res = $.parseJSON(response);
                // var org_price = parseFloat($('#org_price').val());
                // if(isNaN(org_price)){org_price=0;}
                // var new_price = parseFloat(res[0]);
                // if(isNaN(new_price)){new_price=0;}
                // var calculate = org_price+new_price;
                $('#org_price').val(res[0]);
            }
        });
    }
}
function getePrices()
{
    var vals = $('#emymultis').val();
    if(vals==null)
    {
      $('#eorg_price').val(0);
    }
    else
    {
        $.ajax({
            url:base_url+'offers/get_price',
            type:'POST',
            data:{vals:vals},
            success:function(response)
            {
                var res = $.parseJSON(response);
                // var org_price = parseFloat($('#org_price').val());
                // if(isNaN(org_price)){org_price=0;}
                // var new_price = parseFloat(res[0]);
                // if(isNaN(new_price)){new_price=0;}
                // var calculate = org_price+new_price;
                $('#eorg_price').val(res[0]);
            }
        });
    }
}
function discounted_price()
{
    var op = parseFloat($('#org_price').val());
    var dp = parseFloat($('#dis_pricea').val());
    if(isNaN(op)){op=0;}
    if(isNaN(dp)){dp=0;}
    $('#dis_price').val(op-dp);
}
function ediscounted_price()
{
    var op = parseFloat($('#eorg_price').val());
    var dp = parseFloat($('#edis_pricea').val());
    if(isNaN(op)){op=0;}
    if(isNaN(dp)){dp=0;}
    $('#edis_price').val(op-dp);
}
$(document).ready(function(){
	$('.ifnotify2').trigger('click');
	// Datepicker 
	$('.datepicker').datepicker({dateFormat:'yy-mm-dd'});
	$('#offersTable').DataTable({
    	 "sAjaxSource": base_url+'offers/show_offers',
    	 "pageLength": 10,
    	 "order": [],
    	 "responsive":true
    });

    $('#mymultis').multiSelect({
        afterSelect: function(values){
            getPrices();
        },
        afterDeselect: function(values){
            getPrices();
        }
    });
        
    $('#dis_pricea').on('keyup',function(e){
        var orgprc = parseFloat($('#org_price').val());
        var amount = parseFloat($('#dis_pricea').val());
        var prcent = parseFloat($('#dis_pricep').val());
        if(isNaN(orgprc)){orgprc=0;}
        if(isNaN(amount)){amount=0;}
        if(isNaN(prcent)){prcent=0;}
        $('#dis_pricep').val((amount/orgprc)*100);
        discounted_price();
    });
    
    $('#dis_pricep').on('keyup',function(e){
        var orgprc = parseFloat($('#org_price').val());
        var amount = parseFloat($('#dis_pricea').val());
        var prcent = parseFloat($('#dis_pricep').val());
        if(isNaN(orgprc)){orgprc=0;}
        if(isNaN(amount)){amount=0;}
        if(isNaN(prcent)){prcent=0;}
        $('#dis_pricea').val((orgprc*prcent)/100);
        discounted_price();
    });

    $('#btn_offer_image').on('click',function(e){
        $('#offer_image').trigger('click');
    });

    $('#offer_image').on('change',function(e){
        $('#offer_image_preview').attr('src', window.URL.createObjectURL(this.files[0]));
    });
    $('#btn-add-offer').on('click',function(e){
        var offer_title = $('#offer_title').val();
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var services    = $('#mymultis').val();
        var offer_image =$('#offer_image')[0].files.length;
        var org_price   = parseFloat($('#org_price').val());
        if(isNaN(org_price)){org_price=0;}
        var dis_price   = parseFloat($('#dis_price').val());
        if(isNaN(dis_price)){dis_price=0;}
        var dis_pricep   = parseFloat($('#dis_pricep').val());
        if(isNaN(dis_pricep)){dis_pricep=0;}
        if(services==null)
        {
            $('#ifnotify-warning').text(' Add some services');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(offer_title=="")
        {
            $('#ifnotify-warning').text(' Add Title');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(start_date=="")
        {
            $('#ifnotify-warning').text(' Add Start Date');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(end_date=="")
        {
            $('#ifnotify-warning').text(' Add End Date');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(org_price==0)
        {
            $('#ifnotify-warning').text(' Add some services');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(dis_price==0)
        {
            $('#ifnotify-warning').text(' Add Discounted Price');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(dis_price>=org_price)
        {
            $('#ifnotify-warning').text(' Discounted Price should be less than original price');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        var form_data = new FormData();
        form_data.append('offer_title',offer_title);
        form_data.append('start_date',start_date);
        form_data.append('end_date',end_date);
        form_data.append('services',JSON.stringify(services));
        form_data.append('org_price',org_price);
        form_data.append('dis_price',dis_price);
        form_data.append('dis_pricep',dis_pricep);
        if(offer_image!=0)
        {
            form_data.append('offer_image',$('#offer_image')[0].files[0]);
        }
        $.ajax({
            url:base_url+'offers/add_offers',
            type:'POST',
            processData:false,
            contentType: false,
            data:form_data,
            success:function(response)
            {
                if(response==1)
                {
                    $('#ifnotify-success').text(' Added');
                    $('#ifnotify-success').trigger('click');
                    $('#mymultis').multiSelect('deselect_all');
                    $('#offer_title').val("");
                    $('#start_date').val("");
                    $('#end_date').val("");
                    $('#org_price').val(0);
                    $('#dis_price').val("");
                    $('#dis_pricea').val("");
                    $('#dis_pricep').val("");
                    $('#offer_image').val(null);
                    $('#offer_image_preview').attr('src',base_url+'assets/images/noimage.png');
                }
                else if(response==2)
                {
                    $('#ifnotify-warning').text(' Offer with same title already exists');
                    $('#ifnotify-warning').trigger('click');
                }
                else if(response==0)
                {
                    $('#ifnotify-error').text(' Error try again');
                    $('#ifnotify-error').trigger('click');
                }
                else
                {   
                    $('#ifnotify-warning').text(response);
                    $('#ifnotify-warning').trigger('click');
                }
                $('#offersTable').DataTable().ajax.reload();
            }
        });
    });

    $('#emymultis').multiSelect({
        afterSelect: function(values){
            getePrices();
        },
        afterDeselect: function(values){
            getePrices();
        }
    });

    $('#edis_pricea').on('keyup',function(e){
        var orgprc = parseFloat($('#eorg_price').val());
        var amount = parseFloat($('#edis_pricea').val());
        var prcent = parseFloat($('#edis_pricep').val());
        if(isNaN(orgprc)){orgprc=0;}
        if(isNaN(amount)){amount=0;}
        if(isNaN(prcent)){prcent=0;}
        $('#edis_pricep').val((amount/orgprc)*100);
        ediscounted_price();
    });

    $('#edis_pricep').on('keyup',function(e){
        var orgprc = parseFloat($('#eorg_price').val());
        var amount = parseFloat($('#edis_pricea').val());
        var prcent = parseFloat($('#edis_pricep').val());
        if(isNaN(orgprc)){orgprc=0;}
        if(isNaN(amount)){amount=0;}
        if(isNaN(prcent)){prcent=0;}
        $('#edis_pricea').val((orgprc*prcent)/100);
        ediscounted_price();
    });

    $('#offer-edit-modal').on('show.bs.modal',function(e){
        var offer_id = e.relatedTarget.id;
        $('#e_cus-msg').html("");
        $('#offer_id').val(offer_id);
        $.ajax({
            url:base_url+'offers/get_offers',
            type:'POST',
            data:{offer_id:offer_id},
            success:function(msg)
            {
                var res = $.parseJSON(msg);
                $('#eoffer_title').val(res[0]);
                $('#estart_date').val(res[1]);
                $('#eend_date').val(res[2]);   
                $('#eorg_price').val(res[3]);
                $('#edis_price').val(res[4]);
                $('#edis_pricea').val("");
                $('#edis_pricep').val(res[5]);
                $('#emymultis').multiSelect('deselect_all');
                $('#emymultis').multiSelect('select',res[6]);
                $('#eoffer_image_preview').attr('src',res[7]);
            }
        });
    });

    $('#btn_eoffer_image').on('click',function(e){
        $('#eoffer_image').trigger('click');
    });

    $('#eoffer_image').on('change',function(e){
        $('#eoffer_image_preview').attr('src', window.URL.createObjectURL(this.files[0]));
    });

    $('#btn-update-offer').on('click',function(e){
        var offer_id    = $('#offer_id').val();   
        var offer_title = $('#eoffer_title').val();
        var start_date = $('#estart_date').val();
        var end_date = $('#eend_date').val();
        var services    = $('#emymultis').val();
        var offer_image =$('#eoffer_image')[0].files.length;
        var org_price   = parseFloat($('#eorg_price').val());
        if(isNaN(org_price)){org_price=0;}
        var dis_price   = parseFloat($('#edis_price').val());
        if(isNaN(dis_price)){dis_price=0;}
        var dis_pricep   = parseFloat($('#edis_pricep').val());
        if(isNaN(dis_pricep)){dis_pricep=0;}
        if(services==null)
        {
            $('#ifnotify-warning').text(' Add some services');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(offer_title=="")
        {
            $('#ifnotify-warning').text(' Add Title');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(start_date=="")
        {
            $('#ifnotify-warning').text(' Add Start Date');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(end_date=="")
        {
            $('#ifnotify-warning').text(' Add End Date');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(org_price==0)
        {
            $('#ifnotify-warning').text(' Add some services');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(dis_price==0)
        {
            $('#ifnotify-warning').text(' Add Discounted Price');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        if(dis_price>=org_price)
        {
            $('#ifnotify-warning').text(' Discounted Price should be less than original price');
            $('#ifnotify-warning').trigger('click');
            return false;
        }
        var form_data = new FormData();
        form_data.append('offer_id',offer_id);
        form_data.append('offer_title',offer_title);
        form_data.append('start_date',start_date);
        form_data.append('end_date',end_date);
        form_data.append('services',JSON.stringify(services));
        form_data.append('org_price',org_price);
        form_data.append('dis_price',dis_price);
        form_data.append('dis_pricep',dis_pricep);
        if(offer_image!=0)
        {
            form_data.append('offer_image',$('#eoffer_image')[0].files[0]);
        }
        $.ajax({
            url:base_url+'offers/update_offers',
            type:'POST',
            processData:false,
            contentType: false,
            data:form_data,
            success:function(response)
            {
                if(response==1)
                {
                    $('#ifnotify-success').text(' Added');
                    $('#ifnotify-success').trigger('click');
                }
                else if(response==2)
                {
                    $('#ifnotify-warning').text(' Offer with same title already exists');
                    $('#ifnotify-warning').trigger('click');
                }
                else if(response==0)
                {
                    $('#ifnotify-error').text(' Error try again');
                    $('#ifnotify-error').trigger('click');
                }
                else
                {   
                    $('#ifnotify-warning').text(response);
                    $('#ifnotify-warning').trigger('click');
                }
                $('#offersTable').DataTable().ajax.reload();
            }
        });
    });

    $('#offersTable').on('click','.acdc',function(e){
        e.preventDefault();
        var status = $(this).attr('label');
        var title_text =null;
        var text_text =null;
        if(status==0)
        {
            title_text = 'Are you sure you want to activate this offer?';
            text_text = 'This action will activate this offer and it will be available for users';
        }
        else if(status==1)
        {
            title_text = 'Are you sure you want to de-activate this offer?';
            text_text = 'This action will de-activate this offer and it will not be available for users';
        }
        var href = $(this).attr('href');
        if(typeof(href) != "undefined" && href !== null)
        {
          swal({
              title:title_text,
              text: text_text,
              type: "info",
              showCancelButton: true,
              confirmButtonClass: 'btn-danger btn-md waves-effect waves-light',
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "Yes, continue!",
              cancelButtonText: "No, cancel !",
              closeOnConfirm: true,
              closeOnCancel: true
          }, function (isConfirm) {
              if (isConfirm) 
              {
                    $.ajax({
                        url:base_url+'offers/change_status',
                        type:'POST',
                        data:{offer_id:href},
                        success:function(response)
                        {
                            if(response==1)
                            {
                                $('#ifnotify-success').text(' Updated');
                                $('#ifnotify-success').trigger('click');
                            }
                            else if(response==2)
                            {
                                $('#ifnotify-warning').text(' No offrs found');
                                $('#ifnotify-warning').trigger('click');
                            }
                            else if(response==0)
                            {
                                $('#ifnotify-error').text(' Error try again');
                                $('#ifnotify-error').trigger('click');
                            }
                            $('#offersTable').DataTable().ajax.reload();
                        }
                    });
              } 
              else 
              {
                  return false;
              }
          });
        }
    });

    $('#offersTable').on('click','.ifdel',function(e){
        e.preventDefault();
        var href = $(this).attr('href');
        if(typeof(href) != "undefined" && href !== null)
        {
          swal({
              title:"Are you sure?",
              text: "You will not be able to recover this data!",
              type: "warning",
              showCancelButton: true,
              confirmButtonClass: 'btn-danger btn-md waves-effect waves-light',
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "Yes, delete it!",
              cancelButtonText: "No, cancel it!",
              closeOnConfirm: true,
              closeOnCancel: true
          }, function (isConfirm) {
              if (isConfirm) 
              {
                window.location=href;
              } 
              else 
              {
                  return false;
              }
          });
        }
    });

    $('#offer-details-modal').on('show.bs.modal',function(e){
    	var offer_id = e.relatedTarget.id;
    	$.ajax({
    		url:base_url+'offers/get_offer_details',
    		type:'POST',
    		data:{offer_id:offer_id},
    		success:function(msg)
    		{
    			var res = $.parseJSON(msg);
    			$('#ofd-mbody').html("");
    			$('#ofd-mbody').html(res[0]);
    		}
    	});
    });

    $('#make-payment-modal').on('show.bs.modal',function(e){
    	var invoice = e.relatedTarget.id;
    	var amount  = parseFloat(e.relatedTarget.getAttribute('href'));
    	var advance = parseFloat(e.relatedTarget.getAttribute('title'));
        $('#invoice_number').html("");
    	$('#invoice_number').html(invoice);
    	$('#payment-tbody').html("");
    	$('#payment-tbody').html('<tr><td></td><td></td><td class="pamount">'+amount+'</td></tr>');
    	if(advance>0)
    	{
    		$('#payment-tbody').append('<tr><td></td><td class="adv">'+advance+'</td><td class="pamount">'+(amount-advance)+'</td><td></td></tr>')	
    	}
    	amount = (amount-advance);
    	recalcId();
    	$.ajax({
    		url:base_url+'customers/get_customer_payments',
    		type:'POST',
    		data:{invoice:invoice,amount:amount,advance:advance},
    		success:function(msg)
    		{
    			var res = $.parseJSON(msg);
    			$('#payment-tbody').append(res[0]);
    			recalcId();
    		}	
    	});
    });

    $('#ptext').on('keyup',function(e){
    	var amount  = parseFloat($('.pamount:last').text());
    	var pamount = parseFloat($(this).val());
    	if(pamount>amount)
    	{
    		$('#ifnotify-warning').text(' Amount must be less or equal last payment');
    		$('#ifnotify-warning').trigger('click');
    		return false;
    	}
    });

    $("#btn-make-payment").on('click',function(e){
    	var famount  = parseFloat($('.pamount:first').text());
    	var amount  = parseFloat($('.pamount:last').text());
    	var pamount = parseFloat($('#ptext').val());
    	var advance = parseFloat($('.adv').text());
       if(isNaN(pamount)){pamount=0;}
    	if(pamount==0)
    	{
    		$('#ifnotify-warning').text(' Please enter amount to pay');
    		$('#ifnotify-warning').trigger('click');
    		return false;
    	}
    	if(pamount>amount)
    	{
    		$('#ifnotify-warning').text(' Amount must be less or equal last payment');
    		$('#ifnotify-warning').trigger('click');
    		return false;
    	}
    	var invoice = $('#invoice_number').text();
       $.ajax({
    		url:base_url+'customers/make_customer_payments',
    		type:'POST',
    		data:{invoice:invoice,pamount:pamount},
    		success:function(msg)
    		{
    			$('#ptext').val('');
    			var res = $.parseJSON(msg);
    			if(res[0]!=0)
    			{
    				$.ajax({
    					url:base_url+'customers/get_customer_payments',
    					type:'POST',
    					data:{invoice:invoice,amount:famount,sadv:'yes'},
    					success:function(msg)
    					{
    						var res = $.parseJSON(msg);
    						$('#payment-tbody').html("");
    						$('#payment-tbody').html('<tr><td></td><td></td><td class="pamount">'+famount+'</td></tr>');
    						if(!isNaN(advance))
    						{
    							$('#payment-tbody').append('<tr><td></td><td class="adv">'+advance+'</td><td class="pamount">'+eval(famount-advance)+'</td></tr>');
    						}
    						$('#payment-tbody').append(res[0]);
    						recalcId();
    					}	
    				});
    			}
    		}
    	});
    });
});// End Ready Function
