<script type="text/javascript" src="POModule/po_calculation.js"></script>
<script>
 $(function() {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' ,changeMonth: true,
		changeYear: true,
		yearRange: '-80:+20'});
});


</script>
<script>
  $("#bill_date").datepicker(
      {  inlue: true } );
</script>
<script>

function validateFrm()
{


	if(document.getElementById("site").value=='000')
	{
	    alert("Must Select Site");
		document.getElementById("site").focus();
		return false;
	}
	if(document.getElementById("ledger").value=='000')
    {
        alert("Must Select Ledger First");
			document.getElementById("ledger").focus();
			return false;

    }


 if(document.getElementById("radio").checked==false && document.getElementById("radio2").checked==false)
 {
     alert("Must Select Against Bill");			
	 return false;

 }

	if(document.getElementById("doc_type").value=='Challan')
	{
		if(document.getElementById("bill_no").value=='')
		{
			alert("Must Enter Bill No");
			document.getElementById("bill_no").focus();
			return false;
		}
		if(document.getElementById("bill_date").value == '')
		{
			alert("Enter Bill Date");
			document.getElementById("bill_date").focus();
			return false;
		}
	}
	
	else
	{
		if(document.getElementById("challan_no").value=='')
		{
			alert("Must Enter Challan No");
			document.getElementById("challan_no").focus();
			return false;
		}
		if(document.getElementById("challan_date").value == '')
		{
			alert("Enter Challan Date");
			document.getElementById("challan_date").focus();
			return false;
		}
		
	}



}

 function isNumberKey(sender, evt) {
    var txt = sender.value;
    //alert(evt.which);
    var dotcontainer = txt.split('.');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    //alert(event.keyCode);
    if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
function validate_floating(val,id)
{
   var data=id.split("_");
   var val1=parseFloat(val);
 
   if(val=="" || val1==0)
       {   //document.getElementById(id).value="";
           //document.getElementById(id).focus();
       }else{   
         document.getElementById(id).value=val1.toFixed(2); 
         //document.getElementById(id).value=Math.floor(val1 * 100) / 100;   /* Fixing decimal two points*/ 
       }   
}
 
 function calculateAgainst3(str)
 {
$("#against_purch").val(str);
	var totAmount=0;
	var count =document.getElementById("count").value;
if(str=='bill')
{
   
	var flag=0;
	for(var h=0; h<count;h++)
		{
		if(document.getElementById("itemrate_"+h).value!='')
		{
		flag=flag+1;
		}
		}
	
	if(flag!=count)
	{
	alert("Must Fill Item Rate First");
	document.getElementById("bill_id").checked=false;
	}
	else
	{
		for(var h=0; h<count;h++)
		{
				if(billQty==''){billQty=0;}
				if(itemRate==''){itemRate=0;}
				var billQty=document.getElementById("qty_as_per_bill_"+h).value;
				var itemRate=document.getElementById("itemrate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("itemamount_"+h).value = amtVal;
				var discount = document.getElementById("Discount1_"+h).value;
				if(discount==''){discount=0;}
				var discount_type = document.getElementById("PerAmo_"+h).value;
				if(discount_type=='Amount')
				{
					if(parseFloat(amtVal)>parseFloat(discount))
					{
						var basicAmt = parseFloat(amtVal)-parseFloat(discount);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
					
				}
				else 
				{
					var midRes= (discount*amtVal)/100;
					if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
						
						
				}
			}

			if(totAmount==''){totAmount=0;}
			document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
				
				
		}
}
else
{
		var flag=0;
		for(var h=0; h<count;h++)
			{
				if(document.getElementById("itemrate_"+h).value!='')
				{
					flag=flag+1;
				}
			}

		if(flag!=count)
		{
			alert("Must Fill Item Rate First");
			document.getElementById("received_id").checked=false;
		}
		else
		{
				for(var h=0; h<count;h++)
				{
					var recQty=document.getElementById("reciveqty_"+h).value;
					var itemRate=document.getElementById("itemrate_"+h).value;
					var amtVal=parseFloat(recQty)*parseFloat(itemRate);
					document.getElementById("itemamount_"+h).value = amtVal;
					var discount = document.getElementById("Discount1_"+h).value;
					if(discount==''){discount=0;}
					var discount_type = document.getElementById("PerAmo_"+h).value;
					if(discount_type=='Amount')
					{
						 	if(parseFloat(amtVal)>parseFloat(discount))
							{
								var basicAmt = parseFloat(amtVal)-parseFloat(discount);
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
							}else{
								alert("Discount Amount cannot be greater than Basic Amount");
								var basicAmt = parseFloat(amtVal)-0;
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
								document.getElementById("Discount1_"+h).value=0;
							}
					}
					else 
					{
						var midRes= (discount*amtVal)/100;
						if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						}else{
							alert("Discount Amount cannot be greater than Basic Amount");
							var basicAmt = parseFloat(amtVal)-0;
							document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
							var totAmount =  totAmount+parseFloat(basicAmt);
							document.getElementById("Discount1_"+h).value=0;
						}
					}
				}
			
				document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
		   }
}

    cal_po_charges_billbook('');
		//calculate_taxable_totalamt();
 }
 function calculateAgainst_per()
 {
 var str=$("#against_purch").val();
	var totAmount=0;
	var count =document.getElementById("count").value;
if(str=='bill')
{
   
	var flag=0;
	for(var h=0; h<count;h++)
		{
		if(document.getElementById("itemrate_"+h).value!='')
		{
		flag=flag+1;
		}
		}
	
	if(flag!=count)
	{
	alert("Must Fill Item Rate First");
	document.getElementById("bill_id").checked=false;
	}
	else
	{
		for(var h=0; h<count;h++)
		{
				if(billQty==''){billQty=0;}
				if(itemRate==''){itemRate=0;}
				var billQty=document.getElementById("qty_as_per_bill_"+h).value;
				var itemRate=document.getElementById("itemrate_"+h).value;
				var amtVal=parseFloat(billQty)*parseFloat(itemRate);
				document.getElementById("itemamount_"+h).value = amtVal;
				var discount = document.getElementById("Discount1_"+h).value;
				if(discount==''){discount=0;}
				var discount_type = document.getElementById("PerAmo_"+h).value;
				if(discount_type=='Amount')
				{
					if(parseFloat(amtVal)>parseFloat(discount))
					{
						var basicAmt = parseFloat(amtVal)-parseFloat(discount);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
					
				}
				else 
				{
					var midRes= (discount*amtVal)/100;
					if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
					}else{
						alert("Discount Amount cannot be greater than Basic Amount");
						var basicAmt = parseFloat(amtVal)-0;
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						document.getElementById("Discount1_"+h).value=0;
					}
						
						
				}
			}

			if(totAmount==''){totAmount=0;}
			document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
				
				
		}
}
else
{
		var flag=0;
		for(var h=0; h<count;h++)
			{
				if(document.getElementById("itemrate_"+h).value!='')
				{
					flag=flag+1;
				}
			}

		if(flag!=count)
		{
			alert("Must Fill Item Rate First");
			document.getElementById("received_id").checked=false;
		}
		else
		{
				for(var h=0; h<count;h++)
				{
					var recQty=document.getElementById("reciveqty_"+h).value;
					var itemRate=document.getElementById("itemrate_"+h).value;
					var amtVal=parseFloat(recQty)*parseFloat(itemRate);
					document.getElementById("itemamount_"+h).value = amtVal;
					var discount = document.getElementById("Discount1_"+h).value;
					if(discount==''){discount=0;}
					var discount_type = document.getElementById("PerAmo_"+h).value;
					if(discount_type=='Amount')
					{
						 	if(parseFloat(amtVal)>parseFloat(discount))
							{
								var basicAmt = parseFloat(amtVal)-parseFloat(discount);
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
							}else{
								alert("Discount Amount cannot be greater than Basic Amount");
								var basicAmt = parseFloat(amtVal)-0;
								document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
								var totAmount =  totAmount+parseFloat(basicAmt);
								document.getElementById("Discount1_"+h).value=0;
							}
					}
					else 
					{
						var midRes= (discount*amtVal)/100;
						if(parseFloat(amtVal)>parseFloat(midRes)){
						var basicAmt = parseFloat(amtVal)-parseFloat(midRes);
						document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
						var totAmount =  totAmount+parseFloat(basicAmt);
						}else{
							alert("Discount Amount cannot be greater than Basic Amount");
							var basicAmt = parseFloat(amtVal)-0;
							document.getElementById("basic_"+h).value = basicAmt.toFixed(2);
							var totAmount =  totAmount+parseFloat(basicAmt);
							document.getElementById("Discount1_"+h).value=0;
						}
					}
				}
			
				document.getElementById("total_item_amount").value = totAmount.toFixed(2);
				
		   }
}

    cal_po_charges_billbook('');
		//calculate_taxable_totalamt();
 }
 
 
function chkdteformat(obj){
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
  var input=$(obj).val();
  if(!pattern.test(input))
  {
      alert("Date should be in dd/mm/yyyy Format");
      $(obj).val("");
  }
}
function calculatetotalrate(i)
{
 	if(document.getElementById("bill_id").checked==true || document.getElementById("received_id").checked==true)
 	{
 		   if(document.getElementById("received_id").checked==true)
		 	var recQty=document.getElementById("reciveqty_"+i).value;
		  else  if(document.getElementById("bill_id").checked==true)
		 	var recQty=document.getElementById("qty_as_per_bill_"+i).value;

			var itemRate=document.getElementById("itemrate_"+i).value;
			if(itemRate==""){
				var itemRate=0;
			}
			var amtVal=parseFloat(recQty)*parseFloat(itemRate);
			document.getElementById("itemamount_"+i).value = amtVal.toFixed(2);
			var dis=document.getElementById("Discount1_"+i).value;

	      DiscountAmounts(dis,i);
	  }
 }
function DiscountAmounts(val,i)
 {

 	if(document.getElementById("bill_id").checked==true || document.getElementById("received_id").checked==true)
 	{

	var itemAmt=document.getElementById("itemamount_"+i).value;
	if(val==''){val=0;}
	if(itemAmt==''){itemAmt=0;}
	var distype=document.getElementById("PerAmo_"+i).value;
	if(distype=='Amount')
	{
	var subTotal = parseFloat(itemAmt)-parseFloat(val);
   }
   else
   {
   	var subTotal = parseFloat(itemAmt)-(parseFloat(itemAmt)*parseFloat(val)/100);
   }

	document.getElementById("basic_"+i).value = subTotal.toFixed(2);
	
	var count =document.getElementById("count").value;
	var totAmount=0;
	for(var h=0; h<count;h++)
	{
		var subTotal1 = document.getElementById("basic_"+h).value;
		totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
	}
	document.getElementById("total_item_amount").value = totAmount.toFixed(2);

	 cal_po_charges_billbook('');
  }
 }
 function DiscountAmountNew(val,i)
{
	var disAmt = document.getElementById("Discount1_"+i).value;
	var itemAmt=document.getElementById("itemamount_"+i).value;
	var totAmount=0;
	if(disAmt==''){disAmt=0;}
	if(itemAmt==''){itemAmt=0;}
	if(val=='%')
	{
		var percent = parseFloat(itemAmt) * parseFloat(disAmt)/100;
		var subTotal = parseFloat(itemAmt)-parseFloat(percent);
		document.getElementById("basic_"+i).value = subTotal.toFixed(2);
		var count =document.getElementById("count").value;
		for(var h=0; h<count;h++)
		{
			var subTotal1 = document.getElementById("basic_"+h).value;
           if(subTotal1=='') { subTotal1=0;}

			totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
		}
		document.getElementById("total_item_amount").value = totAmount.toFixed(2);
	}
	else
	{
		var count =document.getElementById("count").value;
	var subTotal = parseFloat(itemAmt)-parseFloat(disAmt);
	document.getElementById("basic_"+i).value = subTotal.toFixed(2);
	for(var h=0; h<count;h++)
		{
			var subTotal1 = document.getElementById("basic_"+h).value;
			  if(subTotal1=='') { subTotal1=0;}
			totAmount=parseFloat(totAmount)+parseFloat(subTotal1);
		}
		document.getElementById("total_item_amount").value = totAmount.toFixed(2);
	}
	calculate_taxable_totalamt();
}
function calculate_taxable_totalamt()
{
 	
var pkg=document.getElementById("pkg_charges").value;
if(pkg=='') {pkg=0;}
/*var addcharge=document.getElementById("additionalCharges1").value;
if(addcharge==''){ addcharge=0;}*/
var addcharge=0;
var basic=document.getElementById("total_item_amount").value;
var diss_out=document.getElementById("discount_amt").value;
var diss_out=parseFloat(diss_out).toFixed(2);
if(diss_out==''){ diss_out=0;}
//alert(diss_out);
cal_po_charges(diss_out);
//if(basic==''){ basic=0;}
//var totalamt=parseFloat(pkg)+parseFloat(addcharge)+parseFloat(basic);
//document.getElementById("tot_taxable_amt3").value=totalamt.toFixed(2);
//var taxrate=document.getElementById("taxname1").value;
//tax_rate3(taxrate);


 }
</script>
<?php 
$PageSecurity = 4;
$PageName = 'Purchase Bill Book';
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');

	$title = _('Purchase Bill Book');

$Fin1ExpS1=explode("-",$_SESSION['financialYrStart']);
$_SESSION['YearStart']=$Fin1ExpS1[0];
$Fin1ExpE1=explode("-",$_SESSION['financialYrEnd']);
$_SESSION['YearEnd']=$Fin1ExpE1[0];
?>
<?php 
/**************************************************************************************************************************/
if($_REQUEST['Save']) 
{
                    for($cr=0; $cr<count($_REQUEST['item_id']); $cr++){
	                $item_row[]=$_REQUEST['item_id'][$cr];}
                    if(isset($item_row)){ $item=implode(',',$item_row);}

					for($str=1;$str<$_REQUEST['count_tax'];$str++){
							$caption_val[$str] = $_REQUEST['caption_value'][$str];
							$percent[$str] = $_REQUEST['rate'][$str];}	
						
					$financial=substr($_SESSION['YearStart'],-2)."-".substr($_SESSION['YearEnd'],-2);
					$prefix_sql=DB_query("Select * from prefix_tbl where prefix_name='".$title."'",$db);
					$prefix_row=DB_fetch_array($prefix_sql);
					$prefixf=explode("/",$prefix_row['prefix_code']);
					$prefix=$prefixf[1];
					$prefix1=$prefixf[0];	
	
					$sql="select bill_book_no from purchase_billbook where site = '".$_REQUEST['site']."' 
					and INSTR(`bill_book_no`, '$financial') > 0 order by id DESC LIMIT 0,1";
					
					$result = DB_query($sql,$db);
					$numrows = DB_num_rows($result);
					if($numrows>0)
					{
						$myrow=DB_Fetch_array($result);
						$ExplBill=explode("/",$myrow['bill_book_no']);
						$maxval = $ExplBill[2];
					}
					else
					{$maxval=0;}	
					
					$strChar=$_REQUEST['site']."/".$financial."/";
					$strFinal = $maxval+1;
					$strBothFinal = $strChar.str_pad($strFinal,5,"0",STR_PAD_LEFT);   
  
                    $vat_cst=explode('**',$_REQUEST['vat_cst']);
			         $data['site']                 =$_REQUEST['site'];
			 		 $data['bill_book_no']         =$strBothFinal;
					 $data['bill_book_date']       =FormatDateForSQL($_REQUEST['voucher_date']);
					 $data['due_date']       =FormatDateForSQL($_REQUEST['bill_book_date']);
					 $data['vendor']               =$_REQUEST['vendor']; 
					 $data['mrn_no']               =$_REQUEST['id'];
					 $data['mrnqty_ids']           =$item;
					 $data['po_no']                =$_REQUEST['po_no'];
					 $data['po_type']              =$_REQUEST['po_type']; 
					 $data['doc_type']             =$_REQUEST['doc_type'];
					 $data['bill_no']              =$_REQUEST['bill_no']; 
					 $data['bill_date']            =FormatDateForSQL($_REQUEST['bill_date']);  
					 $data['challan_no']           =$_REQUEST['challan_no']; 
					 $data['challan_date']         =FormatDateForSQL($_REQUEST['challan_date']); 
					 $data['duty_type']            =$_REQUEST['duty_type']; 
					 $data['remarks']              =$_REQUEST['remarks'];
					 $data['Excise_Effect']        =$_REQUEST['Excise_Effect'];
					 $data['against_type']         =$_REQUEST['calc_total_against'];

			         $data['total_item_amount']    =$_REQUEST['basic_amt'];	
			         $data['discount_per']         =$_REQUEST['discount_percent'];
					 $data['discount_amt']         =$_REQUEST['discount_amt'];	
					 $data['discounted_amt']       =$_REQUEST['discounted_amt'];
					 $data['pckg_ledger']           =$_REQUEST['pckg_ledger'];
					 $data['pkg_per']              =$_REQUEST['pkg_per'];
					 $data['pkg_charges']          =$_REQUEST['pkg_charges'];  
					 $data['insurance_ledger']     =$_REQUEST['insurance_ledger'];  
					 $data['insurance']            =$_REQUEST['insr_amt'];
                     $data['total_amt']            =$_REQUEST['total_amt'];
                     $excise_id=explode('**',$_REQUEST['excise']);
					 $data['excise_id']            =$excise_id[0];
					 $data['excise_value']         =$_REQUEST['excise_amt'];
					 $ecess=explode('**',$_REQUEST['ecess']);
					 $data['educess']                =$ecess[0];
					 $data['educess_value']            =$_REQUEST['ecess_amt'];
					 $secess=explode('**',$_REQUEST['shecess']);
					 $data['shecess']              =$secess[0];
					 $data['she_ecess_value']          =$_REQUEST['shecess_amt'];
                     $data['tot_tax_amt']          =$_REQUEST['tot_tax_amt'];  
                     $data['vat_cst']              =$vat_cst[0];
					 $data['taxvalue']             =$_REQUEST['vat_amt'];
					 $data['surcharge_ledger']     =$_REQUEST['surcharge_ledger'];
					 $data['surcharge_per']        =$vat_cst[2];
					 $data['sur_oct_amt']          =$_REQUEST['sur_amt'];
					 $data['addcharge_ledger']     =$_REQUEST['addcharge_ledger'];
					 $data['add_charges']          =$_REQUEST['entry_tax_amt'];	
					 //$data['insurance']            =$_REQUEST['insr_amt']; 					
					 $data['freight_ledger']       =$_REQUEST['freight_ledger'];
					 $data['Freight']              =$_REQUEST['Freight'];
                     $data['round_ledger']         =$_REQUEST['round_ledger'];
					 $data['round_off']            =$_REQUEST['roundVal'];
					 $data['round_off_sign']               =$_REQUEST['pluMin'];
					 $data['GrandTotal']           =$_REQUEST['GrandTotal'];
					 $data['ledger']               =$_REQUEST['ledger'];			
					
					
					

				//	if($_REQUEST['pocat']=='AT')  {
		                //************************ For Excise Duty *********************//	
		           //     $total_exciseant=$_REQUEST['excise_amt']/2;	
		           //     $exise_caption=$s->GetFieldValue("excise_tax","id='".$excise_id[0]."'","caption");
		           //     $exise_id2=$s->GetFieldValue("excise_tax","id!='".$excise_id[0]."' and caption='".$exise_caption."'","id");
			      //          $data['Excise_Duty_value1']=$total_exciseant;
			      //          $data['Deffered_Duty_id']=$exise_id2;
			     //           $data['Deffered_Duty_value']=$total_exciseant;
		               //***************** Ecess Duty Value ************************//
		        //        $total_ecessamt=$_REQUEST['ecess_amt']/2;	
		       //         $ecess_caption=$s->GetFieldValue("excise_tax","id='".$ecess[0]."'","caption");
		      //          $ecess_id2=$s->GetFieldValue("excise_tax","id!='".$ecess[0]."' and caption='".$ecess_caption."'","id");
			//                $data['Ecess_Duty_value1']=$total_ecessamt;
			//                $data['Deffered_E_Cess_id']=$ecess_id2;
			//                $data['Deffered_E_Cess_value']=$total_ecessamt;
		    //           //****************** SHE Cess Value *************************// 
		    //            $total_shaecessamt=$_REQUEST['shecess_amt']/2;	
		    //            $ecess_caption=$s->GetFieldValue("excise_tax","id='".$secess[0]."'","caption");
		    //            $shaecess_id2=$s->GetFieldValue("excise_tax","id!='".$secess[0]."' and caption='".$ecess_caption."'","id");
			//                $data['SHE_Cess_value1']=$total_shaecessamt;
			//                $data['Deffered_SHE_id']=$shaecess_id2;
			 //               $data['Deffered_SHE_value']=$total_shaecessamt; 

		           //     $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$excise_id[0]."' and ledgertype='excisetax'","AccountsID"),"amount"=>$total_exciseant,"amount_type"=>'DR');		               
		        //        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$exise_id2."' and ledgertype='excisetax'","AccountsID"),"amount"=>$total_exciseant,"amount_type"=>'DR');
                //        $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$total_ecessamt,"amount_type"=>'DR');
              //          $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess_id2."' and ledgertype='cess'","AccountsID"),"amount"=>$total_ecessamt,"amount_type"=>'DR');
             //           $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$secess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$total_shaecessamt,"amount_type"=>'DR');
               //         $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$shaecess_id2."' and ledgertype='cess'","AccountsID"),"amount"=>$total_shaecessamt,"amount_type"=>'DR');

		     //            } 

		            //     else if($_REQUEST['pocat']=='MT' || $_REQUEST['pocat']=='SV'){//

			              // $data['Excise_Duty_value1']=$_REQUEST['excise_amt'];
			               //  $data['Ecess_Duty_value1']=$_REQUEST['ecess_amt'];
			               //  $data['SHE_Cess_value1']=$_REQUEST['shecess_amt']; 

                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$excise_id[0]."' and ledgertype='excisetax'","AccountsID"),"amount"=>$_REQUEST['excise_amt'],"amount_type"=>'DR');
                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$ecess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$_REQUEST['ecess_amt'],"amount_type"=>'DR');
                       $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$secess[0]."' and ledgertype='cess'","AccountsID"),"amount"=>$_REQUEST['shecess_amt'],"amount_type"=>'DR');
  
		            // }
		              
                      $insurnace_amt=$_REQUEST['insr_amt']+$_REQUEST['insurance'];
		              $data2[]=array("ledgerid"=>$_REQUEST['insurance_ledger'],"amount"=>$insurnace_amt,"amount_type"=>'DR');
		              $data2[]=array("ledgerid"=>$_REQUEST['pckg_ledger'],"amount"=>$_REQUEST['pkg_charges'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$_REQUEST['freight_ledger'],"amount"=>$_REQUEST['Freight'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$_REQUEST['surcharge_ledger'],"amount"=>$_REQUEST['sur_amt'],"amount_type"=>'DR');
                      if($_REQUEST['pluMin']=='+')
                      $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['roundVal'],"amount_type"=>'DR');
                      else
			          $data2[]=array("ledgerid"=>$_REQUEST['round_ledger'],"amount"=>$_REQUEST['roundVal'],"amount_type"=>'CR');  
			          $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","vender_client='".$_REQUEST['vendor']."' and ledgertype='vendor'","AccountsID"),"amount"=>$_REQUEST['GrandTotal'],"amount_type"=>'CR');  
			          $data2[]=array("ledgerid"=>$_REQUEST['addcharge_ledger'],"amount"=>$_REQUEST['entry_tax_amt'],"amount_type"=>'DR');
                      $data2[]=array("ledgerid"=>$s->GetFieldValue("accountledger","taxid='".$vat_cst[0]."' and ledgertype='salestax'","AccountsID"),"amount"=>$_REQUEST['vat_amt'],"amount_type"=>'DR'); 
                      $data2[]=array("ledgerid"=>$_REQUEST['ledger'],"amount"=>$_REQUEST['discounted_amt'],"amount_type"=>'DR'); 

						
						
						
						 $data['po_cat']               =$_REQUEST['pocat'];
						 //$data['misCharge']            =$_REQUEST['other_amt'];						
						 $data['form_type']            =$_REQUEST['form_type'];
						 $data['created_date']         =date('Y-m-d'); 
						 $data['created_by']           =$_SESSION['UserID'];
						 $data['company_id']           =$_SESSION['ACGCompanyId'];
						 			
				
		               $insertsql=$s->RecordInsert('purchase_billbook', $data);
                       $Lastreq_id=DB_Last_Insert_ID($db,'purchase_billbook',$ErrMsg);

                        $countval= count($_REQUEST['itemcode']);	
			   	for($i=0;$i<$countval;$i++)
				{			
			
				    $data_arr['purch_billbookid']   =$Lastreq_id;
					$data_arr['mst_productid']      =$_POST['mst_itemid'][$i];				
					$data_arr['qty_as_per_bill']    =$_POST['qty_as_per_bill'][$i];
					$data_arr['quantity']           =$_REQUEST['reciveqty'][$i];
					$data_arr['short_qty']          =$_REQUEST['short_accessid'][$i];
					$data_arr['rate']               =$_REQUEST['itemrate'][$i];	
					$data_arr['total_price']        =$_REQUEST['itemamount'][$i];	
					$data_arr['discount']           =$_REQUEST['discount'][$i];
					$data_arr['discount_type']      =$_REQUEST['DiscountType'][$i];				
					$data_arr['basic_amt']          =$_REQUEST['basic'][$i];
					$data_arr['sub_total']          =$_REQUEST['basic'][$i];				
					$data_arr['remarks']            =$_REQUEST['remarks'][$i];  
			       $sql=$s->RecordInsert('purchase_bill_details', $data_arr);
		      }

	$update_mrn="Update addmrn set mrnstatus='closed' where id='".$_REQUEST['mrn_no']."'";
	$update_res=DB_query($update_mrn,$db);

       /***************************** Posting In Account ********************************/
        $dataArray['Branch']= $_REQUEST['site'] ;
        $dataArray['VPrefix']= $s->getField('voucher_master','VPrefix','PBill','VoucherType') ;
        $dataArray['Voucher_NO']= $strBothFinal;  
        $dataArray['voucher_type']='Auto';     
        $dataArray['Dates']= FormatDateForSQL($_REQUEST['voucher_date']); 
        $dataArray['conv_rate']='1' ;  
        $dataArray['posted_date']= date('Y-m-d');
        $dataArray['AccountBookType']= 'voucher';   
        $dataArray['created_date']= date('Y-m-d');
        $dataArray['created_by']= $_SESSION['UserID'];   
        $dataArray['narration']=$_REQUEST['remarks'];  
        $dataArray['transation_date_and_time']=FormatDateForSQL($_REQUEST['voucher_date'])." ".date('h:i:s');
        $dataArray['trans_type_id']=$Lastreq_id;
        $dataArray['trans_type']='PURCHASE BILL';
        $s->RecordInsert('account_book', $dataArray);
        $getlastid=DB_Last_Insert_ID($db,'account_book', 'id');

        $total_credit='';
        $total_debit='';
       foreach($data2 as $key=>$value1)
       {
              if($value1[amount]!='0.00')
              {
                $data3['account_bookid']=$getlastid;
                $data3['ledgerid']=$value1[ledgerid];
                $data3['amount']=$value1[amount];
                $data3['converted_amount']=$value1[amount];
                $data3['currency']=$s->getField('currency_master','abbreviation','INR','id');
                $data3['conv_currency']=$s->getField('currency_master','abbreviation','INR','id');
                $data3['amount_type']=$value1[amount_type];
                if($value1[amount_type]=='DR') {  $total_debit[]=$value1[amount];  }
                else if($value1[amount_type]=='CR') {  $total_credit[]=$value1[amount]; }      
              $s->RecordInsert('account_book_details', $data3);
              //  echo "<pre>";
             //   print_r($data3);
             }
       }

      if(!empty($total_credit)) $credit=array_sum($total_credit); else $credit=0;
      if(!empty($total_debit)) $debit=array_sum($total_debit); else $debit=0;

      $update=DB_query("update account_book set total_cramount='".$credit."',total_dramount='".$debit."',total_cramount_conv='".$credit."',total_dramount_conv='".$debit."' ,pending_amount='".$debit."' where id='".$getlastid."'",$db);
    

       /********************************************************************************/

	$s->pageLocation("index.php?route=PurchBillBook_list".$rurl);

}


if($_REQUEST['id'] != ''){
  
	$sqlmrn=DB_query("select * from addmrn where id='".$_REQUEST['id']."'",$db);
	$rowmrn=DB_fetch_array($sqlmrn);
	extract($rowmrn);}

$purch_cat=$s->getField('purchorders','id',$order_no,'po_category');if($purch_cat=='')$purch_cat=$Po_category;
$purch_type=$s->getField('purchorders','id',$order_no,'purchase_ord_Type');
$arr_type=array("IO"=>"Import Order","DO"=>"Domestic Order");$arr_po_cattype=array("AT"=>"Asset","MT"=>"Material","SV"=>"Service");
$arr_doc=array("Challan"=>"Challan","Bill"=>"Bill");$arr_duty=array("Itemwise"=>"Itemwise","Consolidated"=>"Consolidated");

?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div"> 
<h1 align="center">Process Purchase Bill Book</h1>
<form  name="purchase" action="" method="post" onsubmit="return validateFrm();">
<table width="100%" border="0"  cellspacing="0" cellpadding="3">
<tr class="row1">
	<td class="tabledata1"><strong>Branch <font color="#FF0000">*</font></strong></td>
	<td><?php $sql = "select loccode, locationname from locations where mst_companyid='".$_SESSION['ACGCompanyId']."' and loccode='".$rowmrn['site']."'";
	    $result=DB_query($sql, $db);	?>
	<select name="site" id="site" onchange="getreqitemdataNew(this.value)"  style="width:200px;">  
	<?php
	while($myrow=DB_fetch_array($result))
	{ $p='';if($myrow['loccode']==$rowmrn['site'])	$p="selected";	?>
	<option value="<?php echo $myrow['loccode']; ?>"<?php if($p!="") {echo $p;} ?>> <?php echo $myrow['locationname']; ?> </option>
	<?php } ?>
	</select></td>
	<td class="tabledata1"><strong>Voucher No</strong></td>
	<td><input name="voucher_no" type="text" value="Auto Generated"  style="width:200px;" id="bill" readonly="true"/></td>
	<td class="tabledata1"><strong>Voucher Date</strong></td>
	<td><input name="voucher_date" id="voucher_date" type="text" class="datepicker" style="width:200px;" value="<?php echo ConvertSQLDate(date('Y-m-d')); ?>" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>
	
</tr>
<tr class="row1">
<td class="tabledata1"><strong>Vendor</strong></td>
	<td><div id="vender"><select name="vendor" id="vendor" onchange="showmrn(this.value)"   style="width:200px;">
        <?php $sql_supplier = "select id,vendor_code, vendor_name from suppliers where id='".$rowmrn['ReceivedFrom']."'";
	           $result_supplier=DB_query($sql_supplier, $db);
	           while($mysupplier=DB_fetch_array($result_supplier))	{ 	?>
	<option value="<?php echo $mysupplier['id']; ?>"> <?php echo $mysupplier['vendor_name']; ?> </option>
	<?php } ?> </select></div></td>
	<td class="tabledata1"><strong>MRN No</strong></td>
	<td><?php $sql_m =DB_query("select id, MRNNo from addmrn where id='".$rowmrn['id']."'", $db);
	      $result_m=DB_fetch_array($sql_m);	?>
	<div id="getmrn"><select name="mrn_no" id="mrn_no"  onchange="get_mrn_details(this.value)"   style="width:200px;">
	<option value="<?php echo $result_m['id']; ?>"> <?php echo $result_m['MRNNo']; ?> </option>
	</select></div></td> 
    <td class="tabledata1"><strong>MRN Date</strong></td>
	<td><input type="text" name="mrn_date" id="mrnDate" style="width:200px;" readonly value="<?php echo  ConvertSQLDate($rowmrn['MRNDate']);?>" /></td> 
</tr>
<tr class="row1">	
	<td class="tabledata1"><strong>PO NO</strong></td>
	<td><input name="po_no" id="poNO" type="text"  style="width:200px;" readonly value="<?php echo $s->getField('purchorders','id',$rowmrn['order_no'],'purchase_ordNo')?>"/></td>
    <td class="tabledata1"><strong>PO Date</strong></td>
	<td><input type="text" name="po_date" id="po_date" readonly style="width:200px;" value="<?php echo ConvertSQLDate($s->getField('purchorders','id',$rowmrn['order_no'],'po_date'));?>" /></td>
    <td class="tabledata1"><strong>Due Dates</strong></td>
	<td><input type="text" name="bill_book_date" id="bill_book_date" class="datepicker" value="<?php echo date('d/m/Y'); ?>"  style="width:200px;" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>
    </tr>
    <tr class="row1">
	<td class="tabledata1"><strong>PO Type</strong></td>
	<td><?php  $po_purch_type=$s->GetFieldValue("addmrn","id='".$_REQUEST['id']."'","type");	echo $arr_type[$po_purch_type]; ?>
		<input type="hidden" name="po_type" value="<?php echo $po_purch_type; ?>">
	</td>	
	<td class="tabledata1"><strong>Document Type</strong></td>
	<td id="doc_type_data">
    <select name="doc_type" id="doc_type" style="width:200px;">
    <option value="<?php echo $rowmrn['DocumentType'];?>" ><?php echo $arr_doc[$rowmrn['DocumentType']];?></option>
    </select></td>
    <td class="tabledata1"><strong>Duty Type</strong></td>	
	<td id="doc_type_data"><select name="duty_type" id="duty_type" style="width:200px;">
    <option value="<?php echo $rowmrn['duty_type'];?>" ><?php echo $arr_duty[$rowmrn['duty_type']];?></option>
    </select></td>
    </tr>
    <tr class="row1">
	<td class="tabledata1"><strong>Challan No.</strong></td>
	<td><input type="text" name="challan_no" id="challanno" readonly style="width:200px;" value="<?php echo  $rowmrn['BillNo'];?>" /></td>	
	<td class="tabledata1"><strong>Challan Date</strong></td>
	<td id="doc_type_data"><input type="text" name="challan_date" id="challan_date" readonly style="width:200px;" 
		value="<?php echo  ConvertSQLDate($rowmrn['MRNVoucherDate']);?>" />	</td>
    <td class="tabledata1"><strong>PO Category</strong></td>
	<td id="doc_type_data"><?php 
		$po_type_code=$s->GetFieldValue("addmrn","id='".$_REQUEST['id']."'","Po_category");
	echo $arr_po_cattype[$po_type_code]; ?>
		<input type="hidden" name="pocat" value="<?php echo $po_type_code; ?>"></td>
   </tr>
   <tr class="row1">
   	<td class="tabledata1">Bill No</td>
   	<td><input type="text" name="bill_no" id="bill_no"  style="width:200px;" value="" /></td>
   	<td class="tabledata1">Bill Date</td>
   	<td><input type="text" name="bill_date" id="bill_date" class="datepicker" style="width:200px;" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)"></td>
   	<td></td>
   	<td></td>
   </tr>
	</table>
 <div>
<div id="importPo4" style="width:1250px;overflow:auto;">
<table width="100%" border="1" cellspacing="0" cellpadding="3" style="border:1px solid #333333;">
 <tr class="row1">
 <td colspan="14" style="text-align:center;" class="tabledata1"><strong>Against :</strong> <input type="radio" name="calc_total_against" id="bill_id" value="bill" onclick="calculateAgainst3(this.value)" /><strong>Bill Qty</strong><input type="radio" name="calc_total_against" id="received_id" value="received" checked onclick="calculateAgainst3(this.value)"/>
<input type="hidden" id="against_purch" value="" />
 <strong>Received Qty</strong></td>
  </tr>
   <tr>
        <td class="tabledata"><strong>Sr.No.</strong></td>
        <td class="tabledata"><strong>Item Code</strong></td>
        <td class="tabledata"><strong>Description</strong></td>
        <td class="tabledata"><strong>UOM</strong></td>
        <td class="tabledata"><strong>PO QTY</strong></td>
        <td class="tabledata"><strong>Bill QTY</strong></td>
        <td class="tabledata"><strong>Recieved QTY</strong></td>
        <td class="tabledata"><strong>Short Quantity</strong></td>
        <td class="tabledata"><strong>Rate</strong></td>
        <td class="tabledata"><strong>Amount</strong></td>
        <td class="tabledata" colspan="2" width="15%"><strong>Discount</strong></td>
        <td class="tabledata"><strong>Basic<br /> Amt.</strong></td>
    </tr>
      <?php 
$i=0;
$sql=DB_query("select * from addmrnqty where issue_id='".$rowmrn['id']."' and reciveqty!='0.00'",$db);
while($row=DB_fetch_array($sql))
{	
	$itemcode=$s->getField('item_master','id',$row['mst_itemid'],'StockID');
	$itemname=$s->getField('item_master','id',$row['mst_itemid'],'item_name');
	$unit=$s->getField('item_master','id',$row['mst_itemid'],'mst_unitid');
    $oldCur = $row['currency'];
    $rate=$s->GetFieldValue("purchorderdetails","parantId='".$rowmrn['order_no']."' and mst_itemid='".$row['mst_itemid']."'","Rate");
   if($rowmrn['order_no']!='')
   {
    $discounttype=$s->GetFieldValue("purchorderdetails","parantId='".$rowmrn['order_no']."' and mst_itemid='".$row['mst_itemid']."'","DiscountType");
    $discountamt=$s->GetFieldValue("purchorderdetails","parantId='".$rowmrn['order_no']."' and mst_itemid='".$row['mst_itemid']."'","Discount");
   if($discounttype=='Amount')
   {
  // echo $poqty;
    $discountper=$discountamt*100/($row['POQty']*$rate);
   }
   else 	
   $discountper=$discountamt;
   
   
   $discounttype1=array("%"=>"%","Amount"=>"Amount");
    //if($rate=='') ($rate=0;) if($discountamt==''){  }
   }
   else 
   {
   $discounttype='';	
   $discounttype1=array("%"=>"%","Amount"=>"Amount");
   $disamt_total='';
   $rate='';
   }   
?>
      <tr >
        <td><?php echo $i+1;?></td>
        <td><?php echo $itemcode;?>
        <input type="hidden" readonly="" id="mst_itemid[]" name="mst_itemid[]" size="15" value="<?php echo $row['mst_itemid']; ?>" />
        <input type="hidden" readonly="" id="itemcode[]" name="itemcode[]" size="15"  value="<?php echo $itemcode; ?>" />
        <input type="hidden" readonly="" id="tolrancees[]" name="tolrancees[]" size="15"  value="<?php echo $tolerance; ?>" />
        <input type="hidden" readonly="" id="pending[]" name="pending[]" size="15"  value="<?php echo $pending_qty; ?>" />
        </td>
        <td><?php echo $itemname ?></td>
        <td><?php $unitname=$s->getField('unitsofmeasure','unitid',$unit,'unitname');	echo $unitname;?></td>
        <td><?php   echo $poqty=$row['POQty']; ?><input name="poqty[]" type="hidden" id="poqty[]" value="<?php echo $poqty;?>" size="10"/></td>
        <td><input name="qty_as_per_bill[]" type="text" id="qty_as_per_bill_<?php echo $i; ?>" value="<?php echo $row['qty_as_per_bill'];?>"  size="8" readonly oonblur="check_bill_qty(this.value,<?php echo $i;?>)" readonly />
        </td>
        <td><input name="reciveqty[]" readonly type="text" id="reciveqty_<?php echo $i; ?>" value="<?php echo $row['reciveqty'];?>" size="8"/></td>
        <td><input name="short_accessid[]" type="text" id="short_accessid[]" value="<?php echo $row['short_accessid'];?>" size="8" readonly="true" oonfocus="calculate_poshort(<?php echo $i ?>);" readonly  /></td>
        <td><input name="itemrate[]" type="text" id="itemrate_<?php echo $i; ?>" onkeyup="calculatetotalrate(<?php echo $i;?>)" 
        	value="<?php echo $ratVal=$rate; ?>"   size="8"    <?php if($rate!=''){?> readonly="true" <?php }?> onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'/>
        </td>
        <td><input name="itemamount[]" readonly type="text" id="itemamount_<?php echo $i; ?>" value="<?php echo $ratVal*$row['reciveqty']; ?>" 
        	oonfocus="calculatetotalrate(<?php echo $i; ?>)"  size="8"  />
        </td> 
       <?php  if($discounttype=='Amount') { $disamt_total=($ratVal*$row['reciveqty']*$discountper/100); } else { $disamt_total=$discountper; } ?>
         <td ><input type="text"  value="<?php echo $curId =$disamt_total; 
		?>" name="discount[]"  size="8" id="Discount1_<?php echo $i; ?>" onkeyup="calculateAgainst_per();" 
		oonfocus="calculateAgainst3(this.value);" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'/>
        </td>
       <td><select  name="DiscountType[]" type="text"  id="PerAmo_<?php echo $i; ?>" onchange="DiscountAmountNew(this.value,<?php echo $i;?>)" >        
         	<?php  foreach($discounttype1 as $key=>$value) 	{  	$t1='';	if($discounttype==$key)	$t1="selected";	?>
         	<option value="<?php echo $key; ?>" <?php echo $t1; ?> ><?php echo $value; ?></option>
         	<?php } ?></select></td>
         	<?php 
                $ab= $ratVal*$row['reciveqty'];
			   if($discounttype=='Amount')  {	  $result = $ab-$curId;  }
			   else   {	  $resultMid = ($ab*$curId)/100;    $result = $ab-$resultMid;  }     
			   $result_sum[]=$result; 
         	?>
	   <td ><input type="text" style="width:70px" id="basic_<?php echo $i; ?>" value="<?php echo $result;	  ?>" name="basic[]" readonly/></td>      
      </tr>
      <?php $i++; }	 ?>
      <input type="hidden" name="countval2" value="<?php echo $i; ?>"  id="count"/>
    </table>
</div>
 <div align="right" id="charges4">	
		<table width="100%" border='0'>
			<tr>
			<td class="tabledata1" colspan="4">
		<table width="100%" cellpadding="3" cellspacing="0" border="0">
			<tr class="row1">
				<td valign="top" width="75%">
				<table width="100%" cellpadding="3" cellspacing="0" border="0">
				<tr class="row1">
				<td class="tabledata1"><strong>Ledger</strong></td>
				<td>
				<select name="ledger" id="ledger" style="width:200px;">
				<option value="000">---Select Ledger---</option>
				<?php				
				$ledger_sql=DB_query("select AccountsID, AccountName from accountledger  where ledgertype='purchase'
									 ORDER BY AccountName ASC",$db);
				while($ledger_row=DB_fetch_array($ledger_sql))
				{
				?>
				<option value="<?php echo $ledger_row['AccountsID'];?>"<?php echo ($ledger_row['AccountsID']==$_REQUEST['ledger']?'selected':'')?>><?php echo $ledger_row['AccountName'];?></option>
				<?php } ?>
				</select></td>
				</tr>
				<tr class="row1">
				<td class="tabledata1"><strong>Remarks If Any</strong></td>
				<td>
				<textarea name="remarks" id="remarks" style="width:200px;"><?php echo $_REQUEST['remarks'];?></textarea></td>
				</tr>
				  <tr class="row1">
					<td class="tabledata1"><strong>Excise Effect</strong></td>
					<td><select name='Excise_Effect' style="width:200px;">
					<option value="0">---</option>
					<option value="RG-23A"<?php echo ( $mrn_row['Excise_Effect']=='RG-23A')?'selected':''?>  >RG 23A &Iota; &Iota;nd</option>
						<option value="RG-23C"<?php echo ( $mrn_row['Excise_Effect']=='RG-23C')?'selected':''?>  >RG 23C &Iota; &Iota;nd</option>
						<option value="RG-23D"<?php echo ( $mrn_row['Excise_Effect']=='RG-23D')?'selected':''?>  >RG 23D &Iota; &Iota;nd</option>
						<option value="Non Modvat"<?php echo ( $mrn_row['Excise_Effect']=='Non Modvat')?'selected':''?>  >Non Modvat</option>
					</select>&nbsp;</td>
				  </tr>
				  <tr class="row1">
				  <td class="tabledata1"><strong>Form Type</strong></td>
				  <td><select  name="form_type" id="form_type" style="width:200px; height:20px;">
				  <option value="">Select</option>
				  <?php $formSql=DB_query("Select * from form_type_master",$db);
				     while($formRow=DB_fetch_array($formSql)) {	?>
				  <option value="<?php  echo $formRow['id']?>"<?php echo ($formType==$formRow['id']?'selected':'')?>><?php  echo $formRow['form_name']?></option> <?php }?>	</select></td> </tr> </table></td>
		<td ><table width='100%' border='0' cellspacing='0' cellpadding='3'>
		<tr class='row1'>
		<td class='tabledata1'><strong>Basic Amount</strong> </td>
		<td><input type='text' readonly value='<?php echo array_sum($result_sum); ?>'  name='basic_amt' id='total_item_amount' style='width:150px;' readonly  /></td>
		</tr>
		<tr class='row1'>
	    <td class='tabledata1'><strong>Discount</strong></td>
	    <td>
	   
	    <?php 
             $purch_discount=$s->getField('purchorders','id',$order_no,'discount_amt');
             $purch_pkg=$s->getField('purchorders','id',$order_no,'pkg_per');
             $purch_taxable_insurance=$s->getField('purchorders','id',$order_no,'non_tax_insurance');
             $purch_basicamt=$s->getField('purchorders','id',$order_no,'total_amount');
             if($purch_basicamt!=0) $purch_disper=round($purch_discount*100/$purch_basicamt,2);
             else $purch_disper=0;	
             $excise_id=$s->getField('purchorders','id',$order_no,'excise');
             $ecess_id=$s->getField('purchorders','id',$order_no,'ecess');
             $s_ecess_id=$s->getField('purchorders','id',$order_no,'shecess');
             $vatcst=$s->getField('purchorders','id',$order_no,'vatcst');
             $entry_tax=$s->getField('purchorders','id',$order_no,'entry_tax_amt');
             $non_insurance=$s->getField('purchorders','id',$order_no,'insurancecharges_amt');
             $Freight=$s->getField('purchorders','id',$order_no,'Freight');
             $other_charges=$s->getField('purchorders','id',$order_no,'other_amt');
	         $dicamt=array_sum($result_sum)*$purch_disper/100; 
             $total_discountamt=round(array_sum($result_sum)-$dicamt,2);
             $pkgcharges_amt=round($purch_pkg*$total_discountamt/100,2);
             $total_sum_amt=$pkgcharges_amt+$total_discountamt+$purch_taxable_insurance;
             $excise_per=$s->getField('excise_tax','id',$excise_id,'def_rate');
             $ecess_per=$s->getField('excise_tax','id',$ecess_id,'def_rate');
             $she_per=$s->getField('excise_tax','id',$s_ecess_id,'def_rate');            
             $excise_amt1=round($total_sum_amt*$excise_per/100,2);
             $ecess_amt1=round($excise_amt1*$ecess_per/100,2);
             $s_ecess_amt1=round($excise_amt1*$she_per/100,2);
             $total_taxable_amt1=round($excise_amt1+$ecess_amt1+$s_ecess_amt1+$total_sum_amt,2);
             $vat_per=$s->getField('sales_tax_master','salestax_id',$vatcst,'taxrate');
             $surcharge_per=$s->getField('sales_tax_master','salestax_id',$vatcst,'surcharge_rate');
             $vat_amt1=round($total_taxable_amt1*$vat_per/100,2);
             $surcharge_amt=round($vat_amt1*$surcharge_per/100,2);
             $grandtotalamt=round($surcharge_amt+ $vat_amt1+ $total_taxable_amt1+$entry_tax+$non_insurance+$Freight+$other_charges,2);
             $grossamt12=round($grandtotalamt,2);
             $gramt=explode(".",$grossamt12);	

		if($gramt[1]<10 && strlen($gramt[1])==1)
		{$decimal=$gramt[1]*10;}
	    else {$decimal=$gramt[1];}

			if($decimal>=50)
			{
				$sign1="+";
				$round1=(100-$decimal)/100;
				$grossamt1=round($grossamt12);
			}
			else 
			{
				$sign1="-";
				$round1=$decimal/100;
				$grossamt1=$gramt[0];
			}	

	    ?>
	     <input type='text'  name='discount_percent' placeholder='Percent' id='discount_percent' value='<?php echo $purch_disper; ?>' onkeyup='cal_po_charges(this)' style='width:70px;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' >
	     <input type='text'  name='discount_amt' value='<?php echo $dicamt; ?>' id='discount_amt' placeholder='Amount' onkeyup='cal_po_charges(this)'  style='width:70px;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' ></td>
	    </tr>
        <tr class='row1'>
		<td class='tabledata1'><strong>Discounted Amount</strong></td>
		<td><input type='text' readonly name='discounted_amt' value='<?php echo $total_discountamt; ?>' id='discnted_amt' style='width:150px;' ></td>
		</tr>
		<?php 
	   
		$excise=DB_query("select * from excise_tax where ledgertype like '%excisetax%' and form_type='Purchase' group by caption ",$db);
        
		//$option="<option value=''>Select</option>";
		while($excise_res=DB_fetch_assoc($excise))
		{
		$p='';
		if($excise_res['id']==$excise_id)
			$p='selected';
		else
			$p='';
		$option.="<option ".$p." value='".$excise_res['id']."**".$excise_res['def_rate']."'>".$excise_res['caption']."</option>";
	    }
	   $cess=DB_query("select * from excise_tax where ledgertype='cess'  group by caption limit 0,1 ",$db);	
	   while($cess_res=DB_fetch_assoc($cess)){
		$p1='';
		if($cess_res['id']==$ecess_id)
			$p1='selected';
		else
			$p1='';
		$option1.="<option ".$p1." value='".$cess_res['id']."**".$cess_res['def_rate']."'>".$cess_res['caption']."</option>";
	}
	$scess=DB_query("select * from excise_tax where ledgertype='cess'  group by caption limit 1,1 ",$db);
	
	while($scess_res=DB_fetch_assoc($scess)){
		$p2='';
		if($scess_res['id']==$s_ecess_id)
			$p2='selected';
		else
			$p2='';
		$option2.="<option ".$p2." value='".$scess_res['id']."**".$scess_res['def_rate']."'>".$scess_res['caption']."</option>";
	}
	?>
	
	    <tr class='row1'>
        <td class='tabledata1'><strong>Pkg Charges</strong> </td>
        <td><select name="pckg_ledger" style="width:70px;"><?php  $pckLedger=DB_query("Select * from accountledger where ledgertype='pckcharge'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger)) {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php  }  ?> </select>
		<input type='text'  name='pkg_per' placeholder='percent' value='<?php echo $purch_pkg; ?>' id='pkg_perc' onkeyup='cal_po_charges(this)' style='width:75px' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'  />	<br>												        
		<input name='pkg_charges'  id='pkg_charges' placeholder='Amount' value='<?php echo $pkgcharges_amt;?>' onkeyup='cal_po_charges(this)' style='width:150px' type='text' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' readonly/></td>
        </tr>        
		
        <tr class='row1'>
	    <td class='tabledata1'><strong>Total Amt</strong></td>
	    <td><input type='text' readonly name='total_amt' readonly id='total_amt' value='<?php echo $total_sum_amt; ?>' style='width:150px;' ><input type='hidden'  name='insurance' placeholder='' value='0'  id='insurance_non_taxable' onkeyup='cal_po_charges(this)' style='width:150px' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'  />
	    </td>
	    </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>Excise Duty </strong> </td>
        <td>
		<select id='excise' readonly  name='excise' onchange='cal_po_charges(this)' style="width:70px;">
             <option value="">Select</option> 
			<?php echo $option; ?></select>													        
		<input name='excise_amt' readonly  value='<?php echo $excise_amt1; ?>' readonly id='excise_amt' style='width:75px' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>E Cess</strong> </td>
        <td><select  name='ecess' id='ecess' style="width:70px;" onchange='cal_po_charges(this)'>
        	<option value="0">Select</option>
        	 <?php echo $option1; ?></select>												
		<input name='ecess_amt' readonly id='ecess_amt'  value='<?php echo $ecess_amt1; ?>' style='width:75px' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>SHE Cess</strong> </td>
        <td><select name='shecess' id='shecess' style="width:70px;" onchange='cal_po_charges(this)'> 
        	<option value="0">Select</option>
        	<?php echo $option2; ?></select>												
		<input name='shecess_amt' readonly id='shecess_amt'  value='<?php echo $s_ecess_amt1; ?>' style='width:75px' type='text'/></td>
        </tr>
		<tr class='row1'>
        <td class='tabledata1'><strong>Total Taxable Amount</strong> </td>
        <td><input name='tot_tax_amt' readonly id='tot_tax_amt' value='<?php echo $total_taxable_amt1; ?>' style='width:150px' type='text'/></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>Input Tax </strong> </td>
        <?php
	 	$Taxsql="SELECT salestax_id,tax_code, taxrate,surcharge_rate FROM sales_tax_master
	 	 where account_group in('VI','CI')";
		$Taxresult=DB_query($Taxsql,$db);
		?>
        <td><select id='vat_cst' name='vat_cst' onchange='cal_po_charges(this)' style='width:70px;'>
	    <option value=''>---Select---</option>
	    <?php 
		while($Taxmyrow=DB_fetch_array($Taxresult)){
			$p4='';
			if($Taxmyrow['salestax_id']==$vatcst)
			$p4='selected';
		    else
			$p4='';
		?>
        <option <?php echo $p4; ?>  value='<?php echo $Taxmyrow['salestax_id']."**".$Taxmyrow['taxrate']."**".$Taxmyrow['surcharge_rate']; ?>'><?php echo $Taxmyrow['tax_code'].' --- '.$Taxmyrow['taxrate'].'%'; ?></option>
        <?php } ?>
        </select> <input name='vat_amt' value='<?php echo $vat_amt1; ?>' readonly id='vat_amt' style='width:75px' type='text'/></td>
        </tr>      
     	<tr class='row1'>
        <td class='tabledata1'><strong>Surcharge Tax</strong> </td>
        <td><select name="surcharge_ledger" id="sur_oct_per3" style="width:70px;" >
				  <?php 
				  $surLedger=DB_query("Select * from accountledger where ledgertype='surcharge'",$db);
				  while($surLedgerRow=DB_fetch_array($surLedger))
				  {?>
				  <option value="<?php echo $surLedgerRow['AccountsID'];?>"><?php echo $surLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select><input type='text' readonly  name='sur_per' value='<?php echo $surcharge_per; ?>' id='sur_per' style='width:25px;'/><input type='text' readonly value='<?php echo $surcharge_amt; ?>' name='sur_amt' id='sur_amt' style='width:55px;'/></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>Entry Tax</strong> </td>
        <td><select name="addcharge_ledger" style="width:70px;" >
				  <?php 
				  $pckLedger=DB_query("Select * from accountledger where ledgertype='addcharge'",$db);
				  while($pckLedgerRow=DB_fetch_array($pckLedger))
				  {?>
				  <option value="<?php echo $pckLedgerRow['AccountsID'];?>"><?php echo $pckLedgerRow['AccountName'];?></option>
				  <?php  }  ?>
				  </select>	
        	<input type='text'   name='entry_tax_amt' value='<?php echo $entry_tax; ?>' onkeyup='cal_po_charges(this)' id='entry_amt' style='width:75px;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'/></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>Insurance</strong> </td>
        <td><select name="insurance_ledger" style="width:70px;" >
				  <?php 
				  $pckLedger1=DB_query("Select * from accountledger where ledgertype='insurance'",$db);
				  while($pckLedgerRow1=DB_fetch_array($pckLedger1))
				  {?>
				  <option value="<?php echo $pckLedgerRow1['AccountsID'];?>"><?php echo $pckLedgerRow1['AccountName'];?></option>
				  <?php  }  ?>
				  </select>	<input type='text'  name='insr_amt' value='<?php echo $non_insurance; ?>' onkeyup='cal_po_charges(this)' id='insr_amt' style='width:75px;' onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'/>
				<input type='hidden' readonly name='other_amt' value='<?php echo $other_charges; ?>' onkeyup='cal_po_charges(this)'
         id='other_amt' style='width:150px;' /></td>
        </tr>
        <tr class='row1'>
        <td class='tabledata1'><strong>Freight</strong></td>
        <td><select name="freight_ledger" id="TotalCharge" style="width:70px;" >
				  	<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype='freight'",$db);
				  while($frLedgerRow=DB_fetch_array($frLedger))
				  {?>
				  <option value="<?php echo $frLedgerRow['AccountsID'];?>"><?php echo $frLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				  </select>
		<input type='text'  name='Freight' value='<?php echo $Freight; ?>' onkeyup='cal_po_charges(this)' id='freight_amt' style='width:75px;' /> </td>
        </tr>
        <!--<tr class='row1'>
        <td class='tabledata1'><strong>Other</strong></td>
        <td><input type='hidden' readonly name='other_amt' value='<?php echo $other_charges; ?>' onkeyup='cal_po_charges(this)'
         id='other_amt' style='width:150px;' />  </td>
        </tr>-->
     	<tr class="row1">
		<td class="tabledata1"><strong>Round Off</strong></td>
        <td><select name="round_ledger" id="round_ledger" style="width:70px;">
                   			<?php 
				  $frLedger=DB_query("Select * from accountledger where ledgertype='round'",$db);
				  while($frLedgerRow=DB_fetch_array($frLedger))
				  {?>
				  <option value="<?php echo $frLedgerRow['AccountsID'];?>"><?php echo $frLedgerRow['AccountName'];?></option>
				  <?php 	
				  }
				  ?>
				 
				  </select><input type="text" readonly name="pluMin" readonly value='<?php echo $sign1; ?>' id="pluMin" style="width:20px;" />
        <input type="text" readonly name="roundVal" readonly  id="roundVal" value='<?php echo $round1; ?>' style="width:55px;"/>
        </td>
        </tr>          
        <tr class="row1">
        <td class="tabledata1"><strong>Grand Total</strong></td>
        <td><input type="text" readonly name="GrandTotal" readonly id="GrandTotal" value='<?php echo $grossamt1; ?>' style="width:150px;" />       
        </td>
        </tr>
                
	</table>
				  
		    </td>
		</tr></table>
		
   </table>
</div>

 </div> 

</table>
   <div align="center">
   <input type="submit" name="Save" class="search" value="Save"/>
   </div>
</form>



