$(document).ready(function(){
   $("#pi_quotationdetails").hide();
   $("#picreate").css("width","1000px");
    
   $('#quotation_select').select2({
      ajax: {
        url: url_getquotationforpi,
        type: "get",
        dataType: 'json',
        delay: 100,
        data: function (params) {
         
           return {
              searchTerm: params.term // search term
           };
        },
        processResults: function (response) {
         
           return {
              results: response
                   
           };		   
		 },
        cache: true
      }
 });

 $('#quotation_select').on('select2:select', function (e) {
   var quotation = e.params.data.id;
   var option="";
   
   $.ajax(url_quotationdetails,{
      type : 'get',
      data :{'quotation' : quotation} ,
      success : function(data){
         
         $("#piproductsectionbody").empty();
         $("#piproductsectionfoot").empty();
         quotationdetails(data); 
         productforpi(data);
         banksection(data.bank);
         $(document).find('#quotationselected').val(quotation);
         $(document).find('#pi_company').val(data.company.name);
         $(document).find('#pi_gst').val(data.company.gstin);
         $("#pi_quotationdetails").show();
         $("#address_selection").click(function(){
            addresschange(data);
         }); 
      },
      error: function (jqXhr, textStatus, errorMessage) {
         console.log('Error' + errorMessage);
 }
   });
});

});


function quotationdetails(data)
{

   $('#pi_quotationno').val(data.data.quotation_no);
   $('#pi_companyname').val(data.company.name);
   $('#pi_gstno').val(data.company.gstin);
   $('#pi_emailid').val(data.company.email);

   $('#pi_billaddl1').val(data.billing.address_line1);
   $('#pi_billaddl2').val(data.billing.address_line2);
   $('#pi_billaddl3').val(data.billing.address_line3);
   $('#pi_billcity').val(data.billing.name);
   $('#pi_billstate').val(data.billing.state_title);
   $('#pi_billcountry').val(data.billing.country);
   $('#pi_billpincode').val(data.billing.pincode);
   $('#pi_billmobile').val(data.billing.mobile);
   
   $('#pi_shippingid').val(data.shipping.address_id);
    
   $('#pi_shipaddl1').val(data.shipping.address_line1);
   $('#pi_shipaddl2').val(data.shipping.address_line2);
   $('#pi_shipaddl3').val(data.shipping.address_line3);
   $('#pi_shipcity').val(data.shipping.name);
   $('#pi_shipstate').val(data.shipping.state_title);
   $('#pi_shipcountry').val(data.shipping.country);
   $('#pi_shippincode').val(data.shipping.pincode);
   $('#pi_shipmobile').val(data.shipping.mobile);
   $('#pi_shipreceiver').val(data.shipping.person_name);
   
   
}

function addresschange(data)
{
   $('#changebutton').hide();
   
   $('#pi_shipaddl1').val("");
   $('#pi_shipaddl2').val("");
   $('#pi_shipaddl3').val("");
   $('#pi_shipcity').val("");
   $('#pi_shipstate').val("");
   $('#pi_shipcountry').val("");
   $('#pi_shippincode').val("");
   $('#pi_shipmobile').val("");
   $('#pi_shipreceiver').val("");
   $('#changeable_address').show();

   var datas=data.shipping_select;
   var option="";
   for(result in datas)

   option=option+'<option value='+datas[result].address_id+' data-value='+result+'>'+datas[result].alias_name+':-'+datas[result].address_line1+','+datas[result].name+','+datas[result].state_title+'-'+datas[result].pincode+'</option>'

   $("#pi_addresselect").append(option);

   $('.pi_addresselect').on('change', function () {
            
      var selid=$(this).find(':selected').val();
      
      var selidforarray=$(this).find(':selected').data("value");

      $(document).find('#pi_shippingid').val(selid);
      
      $(document).find('#pi_shipaddl1').val(datas[selidforarray].address_line1);
      $(document).find('#pi_shipaddl2').val(datas[selidforarray].address_line2);
      $(document).find('#pi_shipaddl3').val(datas[selidforarray].address_line3);
      $(document).find('#pi_shipcity').val(datas[selidforarray].name);
      $(document).find('#pi_shippincode').val(datas[selidforarray].pincode);
      $(document).find('#pi_shipstate').val(datas[selidforarray].state_title);
      $(document).find('#pi_shipcountry').val(datas[selidforarray].country);
      $(document).find('#pi_shipmobile').val(datas[selidforarray].mobile);
      $(document).find('#pi_shipreceiver').val(datas[selidforarray].person_name);

   });

}

function productforpi(data)
{
   var total=0;
   var subttl=0;
   var gstttl=0;
   var grndttl=0;
   var text="";

   var tax25=0;
   var tax6=0;
   var tax9=0;
   var tax14=0;

   var tax5=0;
   var tax12=0;
   var tax18=0;
   var tax28=0;

   var i_show=0;
   var cs_show=0;

   var countofproduct=(data.product).length;
   var count=1;

   for(var i=0;i<countofproduct;i++)
		{		
			var section=""	;
			if(data.product[i]['c_s_gst']=='null')
			{
               var test1=(data.product[i]['i_gst']).replace(/[^a-z0-9\s]/gi, '');
               $('#finalthcspi').hide();
               i_show=1;
               
               total=(data.product[i]['unit_cost']*data.product[i]['quantity']);
               gst=(((data.product[i]['unit_cost']/100)*(data.product[i]['i_gst'].replace(/[\*\^\'\!\%\+\.]/g, '')))*data.product[i]['quantity']);
               subttl=subttl+total;
               gstttl=gstttl+gst;
               

				   section=section+'<tr>'+'<td>'+count+'</td>'+'<td class="preview_item" style="max-width: 40ch !important; word-break: break-word !important; hyphens: auto !important;" data-id="'+data.product[i]['item_id']+'">'+data.product[i]['name']+'</td>'+'<td class="preview_HSN">'+data.product[i]['HSN']+'</td>'+'<td class="preview_unitcost">₹'+data.product[i]['unit_cost']+'</td>'+'<td class="preview_quantity">'+data.product[i]['quantity']+'</td>'+'<td id="finalthcs" class="preview_csgst" style="display:none;">'+data.product[i]['c_s_gst']+'</td>'+'<td id="finalthi" class="preview_igst">'+data.product[i]['i_gst']+'</td>'+'<td class="preview_rowtotal amountalign">₹'+total+'</td>'+'</tr>';

               if(test1==5)
               {
                 tax5=tax5+gst;
               }
               if(test1==12)
               {
                 tax12=tax12+gst;
               }
               if(test1==18)
               {
                 tax18=tax18+gst;
               }
               if(test1==28)
               {
                 tax28=tax28+gst;
               }

			}
			else if(data.product[i]['i_gst']=='null')
			{
               var test=(data.product[i]['c_s_gst']).replace(/[\*\^\'\!\%\+\.]/g, '').split(' ')[0];
               $('#finalthipi').hide(); 
               cs_show=1;

               total=(data.product[i]['unit_cost']*data.product[i]['quantity']);
               gst=((((data.product[i]['unit_cost']/100)*((data.product[i]['c_s_gst']).replace(/[\*\^\'\!\%\+\.]/g, '').split(' ')[0]))*data.product[i]['quantity'])*2);
               subttl=subttl+total;
               gstttl=gstttl+gst;
               
				   section=section+'<tr>'+'<td>'+count+'</td>'+'<td class="preview_item" style="max-width: 40ch !important; word-break: break-word !important; hyphens: auto !important;" data-id="'+data.product[i]['item_id']+'">'+data.product[i]['name']+'</td>'+'<td class="preview_HSN">'+data.product[i]['HSN']+'</td>'+'<td class="preview_unitcos">₹'+data.product[i]['unit_cost']+'</td>'+'<td class="preview_quantity">'+data.product[i]['quantity']+'</td>'+'<td id="finalthcs" class="preview_csgst">'+data.product[i]['c_s_gst']+'</td>'+'<td id="finalthi" class="preview_igst" style="display:none;">'+data.product[i]['i_gst']+'</td>'+'<td class="preview_rowtotal amountalign">₹'+total+'</td>'+'</tr>';

               if(test==25)
               {
                 tax25=tax25+gst;
               }
               if(test==6)
               {
                 tax6=tax6+gst;
               }
               if(test==9)
               {
                 tax9=tax9+gst;
               }
               if(test==14)
               {
                 tax14=tax14+gst; 
               }

			}
			$("#piproductsectionbody").append(section);
      count++;
		}
      grndttl=subttl+gstttl;

      if(i_show==1)
      {
         text=text+
         
         '<tr>'+
            '<td colspan="4"></td>'+
            '<td></td>'+
            '<td><h4>Sub Total</h4></td>'+
            '<td class="amountalign">₹'+((subttl).toFixed(0))+'</td>'+
         '</tr>'+
         '<tr>'+
            '<td><h4>GST(5%)</h4></td>'+
            '<td class="amountalign">₹'+((tax5).toFixed(0))+'</td>'+
            '<td><h4>GST(18%)</h4></td>'+
            '<td class="amountalign">₹'+((tax18).toFixed(0))+'</td>'+
            '<td></td>'+
            '<td><h4>GST Total</h4></td>'+
            '<td class="amountalign">₹'+((gstttl).toFixed(0))+'</td>'+
         '</tr>'+
         '<tr>'+
            '<td><h4>GST(12%)</h4></td>'+
            '<td class="amountalign">₹'+((tax12).toFixed(0))+'</td>'+
            '<td><h4>GST(28%)</h4></td>'+
            '<td class="amountalign">₹'+((tax28).toFixed(0))+'</td>'+
            '<td></td>'+
            '<td><h4>Grand Total</h4></td>'+
            '<td class="amountalign">₹'+((grndttl).toFixed(0))+'</td>'+
         '</tr>'
      
         $("#piproductsectionfoot").append(text);
      }
      else if(cs_show==1)
      {
         text=text+
         
         '<tr>'+
            '<td colspan="4"></td>'+
            '<td></td>'+
            '<td><h4>Sub Total</h4></td>'+
            '<td class="amountalign">₹'+((subttl).toFixed(0))+'</td>'+
         '</tr>'+
         '<tr>'+
            '<td><h4>GST(2.5%+2.5%)</h4></td>'+
            '<td class="amountalign">₹'+((tax25).toFixed(0))+'</td>'+
            '<td><h4>GST(9%+9%)</h4></td>'+
            '<td class="amountalign">₹'+((tax9).toFixed(0))+'</td>'+
            '<td></td>'+
            '<td><h4>GST Total</h4></td>'+
            '<td class="amountalign">₹'+((gstttl).toFixed(0))+'</td>'+
         '</tr>'+
         '<tr>'+
            '<td><h4>GST(6%+6%)</h4></td>'+
            '<td class="amountalign">₹'+((tax6).toFixed(0))+'</td>'+
            '<td><h4>GST(14%+14%)</h4></td>'+
            '<td class="amountalign">₹'+((tax14).toFixed(0))+'</td>'+
            '<td></td>'+
            '<td><h4>Grand Total</h4></td>'+
            '<td class="amountalign">₹'+((grndttl).toFixed(0))+'</td>'+
         '</tr>'
      
         $("#piproductsectionfoot").append(text);
          $(document).find('#pi_create_note').val(data.data.note);
          CKEDITOR.instances.pi_create_note.setData(data.data.note);
      }
}

function banksection(data)
{
   var option="";
   for(result in data)
         option=option+
         '<option value='+data[result].id+' data-value='+result+'>'+data[result].bank_aliasname+':'+data[result].bank_name+','+data[result].ac_no+'</option>';

         $("#pibank_select").append(option);

         $('.pibank_select').on('change', function () {
             
            var selid=$(this).find(':selected').data("value");
            
               $("#pi_bankname").val(data[selid].bank_name);
               $("#pi_bankbranch").val(data[selid].bank_branch);
               $("#pi_bankifsc").val(data[selid].bank_ifsc);
               $("#pi_bankbranchcode").val(data[selid].ac_no);
            
            $('#bank_detailssecton').show();
        
          });

}