<?php
$PageSecurity = 1;
include('includes/DefinePaymentClass.php');
$title = _('Invoice');
include('includes/SQL_CommonFunctions.inc');
$exciserate=$s->getField('excise_tax','label','Excise','def_rate');
$modid=$_REQUEST['modid'];
$frmid=$_REQUEST['frmid'];
$rurl="&modid=".$modid."&frmid=".$frmid;

$getLastId=DB_query("Select invoiceNo from invoice order by invoice_id DESC LIMIT 1",$db);
$getLastIdResult=DB_fetch_array($getLastId);
$NewID=$getLastIdResult['invoiceNo']+1;

$time=date('h:i', time());
$period=date(A);
$timestamp = date("H:i", time());

function convertTime($time,$period)
{
	$timeBRK=explode(':',$time);
	if($period=='PM' && $timeBRK[0]!='12')
	{
		$time=$timeBRK[0]+12;
	}
	else 
	{
		$time=$timeBRK[0];
	}
	return $time.":".$timeBRK[1];
}

if($_REQUEST['Save_invoice'])
{
  $fstatus=true;
  if($_REQUEST['branch_name']=='000')
  {
  	  $msgErr[]="Please Select Branch Name"	;
      $fstatus=false;
  }
  if($_REQUEST['voucher_no']=='')
  {
  	  $msgErr[]="Please Enter Voucher no"	;
      $fstatus=false;
  }
   if($_REQUEST['Dates']=='')
  {
  	  $msgErr[]="Please Enter Date"	;
      $fstatus=false;
  }
  
  if($_REQUEST['Ref_no']=='')
  {
  	  $msgErr[]="Please Enter Reference No"	;
      $fstatus=false;
  }
  if(count($_SESSION['ACGLedgerId'])==0 && $_REQUEST['action']!='Edit')
  {
      	  $msgErr[]="Please Select DR/CR Amount "	;
     	 $fstatus=false;
   }

}


//************************Delete*********************************************** 
if($_REQUEST['daction']=='delete')
{
	$condition="id='".$_REQUEST['pid']."'";
	$s->DeleteRecord('invoice_details',$condition);
 	$s->pageLocation('index.php?route=invoice&action=edit&id='.$_REQUEST['id'].$rurl);	
}
if($_REQUEST['action']=='view')
{
	$s->pageLocation('index.php?route=invoice.php&action=addnew'.$rurl);
}
 //*******************************************
$_SESSION['editid']=$_REQUEST['id'];
function number_to_words ($x)
{
	  $nwords = array("","one","two","three","four","five","six", 
                  "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
                  "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", 
                  "nineteen", "twenty", 30 => "thirty", 40 => "fourty",
                     50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eigthy",
                     90 => "ninety" );

     if(!is_numeric($x))
     {
         $w = '#';
     }else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }else{
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }else{
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= ' '. $nwords[$r];
             }
         } else if($x < 1000)
         {
                
                $w .= $nwords[floor($x/100)] .' hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' '. number_to_words($r);
             }
         } else if($x < 1000000)
         {
                $w .= number_to_words(floor($x/1000)) .' thousand';
             $r = fmod($x, 1000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $w .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         } else {
             $w .= number_to_words(floor($x/1000000)) .' million';
             $r = fmod($x, 1000000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $word .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         }
     }
     return $w;}
if($_REQUEST['id'])
{
    $id=$_REQUEST['id'];
  $arr=array();
 for($kp=0;$kp<count($_SESSION['invoice_items']);$kp++)
 {
   if($id!=$_SESSION['invoice_items'][$kp])
   {
 		$arr[]=$_SESSION['invoice_items'][$kp];
   }
 }
 $_SESSION['invoice_items']=$arr;
 }
 ?>
<script language="javascript" type="text/javascript">
function GetURL(str)
{
	var branch_name=document.getElementById("branch_name").value;
	var client=document.getElementById("client_id").value;
	location.replace("index.php?route=invoice&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&action=addnew&po_no="+str+"&branch_name="+branch_name+"&client_id="+client);
}
function calculateAmount(j)
{
	var qty=document.getElementById("Quantity_"+j).value;
	var rate=document.getElementById("RatePerThousand_"+j).value;
	var rateperthousand=rate/1;
	var total=qty*rateperthousand;
	document.getElementById("Amount_"+j).value=total.toFixed(2);
}
function showclient111(str)
{
var branch=document.getElementById("branch_name").value;
if (str=="")
  {
  document.getElementById("partyDispatch").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
	xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
   	//alert(xmlhttp.responseText);
    document.getElementById("partyDispatch").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ShowClient_details1.php?q="+str+"&branch="+branch,true);
xmlhttp.send();
}

function showDispatchDetails(str)
{
	if (str=="")
  {
  document.getElementById("productId").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
	xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
   	//alert(xmlhttp.responseText);
    document.getElementById("productId").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getDispatchItems1.php?dispatchNum="+str,true);
xmlhttp.send();
}

function calsaleamount(i)
{
	
if(document.getElementById("saleqty_"+i).value=='')
{
var salqty=0;	
}
else
{
var salqty=parseFloat(document.getElementById("saleqty_"+i).value);	
}	
if(document.getElementById("salerate_"+i).value=='')
{
var salerate=0;	
}
else
{
var salerate=parseFloat(document.getElementById("salerate_"+i).value);	
}

var amount=salerate*salqty;

document.getElementById("totalsalerate_"+i).value=amount;
	
}


function calculateBasic()
{
	var totalBasic=0;
	var cnt=document.getElementById("rowcount").value;
	for(var i=0;i<cnt;i++)
	{
		var totalValue=document.getElementById("totalsalerate_"+i).value;
		if(totalValue==''){totalValue=0;}
		totalBasic=parseFloat(totalBasic)+parseFloat(totalValue);	
	}
	document.getElementById("basicAmount").value=totalBasic.toFixed(2);
}
function calculateDiscounted()
{
	var totalDiscounted=0;
	var cnt=document.getElementById("rowcount").value;
	for(var i=0;i<cnt;i++)
	{
		var totaldisc=document.getElementById("valueAfterDisc_"+i).value;
		totalDiscounted=parseFloat(totalDiscounted)+parseFloat(totaldisc);	
	}
	document.getElementById("totalDiscountedPrice").value=totalDiscounted.toFixed(2);
}
function claculateExcise(str)
{
	var discounted=document.getElementById("totalDiscountedPrice").value;
	if (str.length==0)
  		{
  			document.getElementById("exciseId").innerHTML="";
  			return;
  		}
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			document.getElementById("exciseId").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","calculateExcise.php?taxId="+str+"&discounted="+discounted,true);
		xmlhttp.send();
}
function calculateVATCST(str)
{
	var taxableAmount=document.getElementById("taxableAmount").value;
	if (str.length==0)
  		{
  			document.getElementById("VATId").innerHTML="";
  			return;
  		}
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			document.getElementById("VATId").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","calculateExcise.php?salesId="+str+"&taxable="+taxableAmount,true);
		xmlhttp.send();
}
function calculateECess()
{
	var exciseValue=document.getElementById("exciseValue").value;
	var ECessPercentage=document.getElementById("ECessPercentage").value;
	var total=(exciseValue*(ECessPercentage/100)).toFixed(2);
	document.getElementById("ECessValue").value=total;
}
function calculateSAHCess()
{
	var exciseValue=document.getElementById("exciseValue").value;
	
	var SAHCessPercentage=document.getElementById("SAHCessPercentage").value;
	
	var total=exciseValue*(SAHCessPercentage/100).toFixed(2);
	document.getElementById("SAHCessValue").value=total;
}
function calculateTaxable()
{
	var totalDiscountedPrice=document.getElementById("totalDiscountedPrice").value;
	var exciseValue=document.getElementById("exciseValue").value;
	var ECessValue=document.getElementById("ECessValue").value;
	var SAHCessValue=document.getElementById("SAHCessValue").value;
	
	if(totalDiscountedPrice==''){totalDiscountedPrice=0;}
	if(exciseValue==''){exciseValue=0;}
	if(ECessValue==''){ECessValue=0;}
	if(SAHCessValue==''){SAHCessValue=0;}
	
	var TOTAL=parseFloat(totalDiscountedPrice)+parseFloat(exciseValue)+parseFloat(ECessValue)+parseFloat(SAHCessValue);
	document.getElementById("taxableAmount").value=TOTAL.toFixed(2);
}
function calculateGrand()
{
	//var a=document.getElementById("totalDiscountedPrice").value;
	var b=document.getElementById("taxableAmount").value;
	var c=document.getElementById("VatCstValue").value;
	var d=document.getElementById("value2").value;
	var e=document.getElementById("value1").value;
	var f=document.getElementById("value4").value;
	
	//if(a==''){a=0;}
	if(b==''){b=0;}
	if(c==''){c=0;}
	if(d==''){d=0;}
	if(e==''){e=0;}
	if(f==''){f=0;}
	
	
	
	var GRAND=parseFloat(b)+parseFloat(c)+parseFloat(d)+parseFloat(e)+parseFloat(f);
	
	//alert(GRAND.toFixed(2));
	grandBrk=GRAND.toFixed(2).split('.');
	grandA=grandBrk[0];
	grandB=grandBrk[1];
	//alert(grandA);
	//alert(grandB);
	if(grandB>'50' || grandB=='50')
	{
		GRAND11=parseInt(GRAND)+1;
	}
	else
	if(grandB<'50')
	{
		GRAND11=parseInt(GRAND);
	}	
	document.getElementById("grandTotal").value=GRAND11.toFixed(2);
	document.getElementById("roundOff").value="."+grandB;
}


function calculateDiscount(str,a)
{
	var discType=document.getElementById("discountType_"+a).value;
	var value=document.getElementById("totalsalerate_"+a).value;
	if(str==''){str=0;}
	if(discType=='A') 
	{
		var discount=str;
	}
	else
	if(discType=='P') 
	{
		var discount=value*(str/100);	
	}
	document.getElementById("valueAfterDisc_"+a).value=(parseFloat(value)-parseFloat(discount)).toFixed(2);
}
function getTarrifHeading(str)
{
	if (str.length==0)
  		{
  			document.getElementById("commID").innerHTML="";
  			return;
  		}
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			document.getElementById("commID").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","get_category.php?comm="+str,true);
		xmlhttp.send();
}

var th = ['','Thousand','Million', 'Billion','Trillion'];
var dg = ['Zero','One','Two','Three','Four', 'Five','Six','Seven','Eight','Nine']; var tn = ['Ten','Eleven','Twelve','Thirteen', 'Fourteen','Fifteen','Sixteen', 'Seventeen','Eighteen','Nineteen']; var tw = ['Twenty','Thirty','Forty','Fifty', 'Sixty','Seventy','Eighty','Ninety']; 

function toWords()
{
	s=document.getElementById("exciseValue").value;
	s = s.toString(); s = s.replace(/[\, ]/g,'');  if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) {if ((x-i)%3==2) {if (n[i] == '1') {str += tn[Number(n[i+1])] + ' '; i++; sk=1;} else if (n[i]!=0) {str += tw[n[i]-2] + ' ';sk=1;}} else if (n[i]!=0) {str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred ';sk=1;} if ((x-i)%3==1) {if (sk) str += th[(x-i-1)/3] + ' ';sk=0;}} 
if (x != s.length) {var y = s.length; str += 'point '; for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';} 
document.getElementById("excise_duty_inwords").value=str;
//return str.replace(/\s+/g,' ');
 


}
function tonumber()
{
	s=document.getElementById("exciseValue").value;
	document.getElementById("total_excise_duty").value=s;
}
function invoiceCode(str)
{
	if (str.length==0)
  		{
  			document.getElementById("invoiceDiv").innerHTML="";
  			return;
  		}
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			document.getElementById("invoiceDiv").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","generateInvoiceNo.php?site="+str,true);
		xmlhttp.send();
}

function calculateedamount()
{	
	var cnt=document.getElementById("rowcount").value;
	var tataledamount=0;
	for(var i=0;i<cnt;i++)
	{
	var EDAmount=document.getElementById("EDAmt_"+i).value;
	tataledamount=parseFloat(tataledamount)+parseFloat(EDAmount);
	}
	if(tataledamount!='0')
	{
		document.getElementById("exciseValue").value=tataledamount.toFixed(2);
	}
	
	
}


</script>
  <?php 
if( $_REQUEST['action'])
{
	$data['invoiceType'] = $_REQUEST['invoiceType'];	
	$data['branch_name'] = $_REQUEST['branch_name'];
	//$client_code=$s->getField('clientmaster','id',$_REQUEST['client_id'],'client_code');
	$data['invoiceNo'] = $_REQUEST['invoiceNo'];
	$data['invoiceDate'] = FormatDateForSQL($_REQUEST['invoiceDate']);
	$data['invoiceTime'] = $_REQUEST['invoiceTime'];
	$data['invoiceAMPM'] = $_REQUEST['invoiceAMPM'];
	$data['removalDate'] = FormatDateForSQL($_REQUEST['removalDate']);	
	$data['removalTime'] = $_REQUEST['removalTime'];
	$data['removalAMPM'] = $_REQUEST['removalAMPM'];
	$data['documentType'] = $_REQUEST['documentType'];
	$data['grNo'] = $_REQUEST['grNo'];
	$data['grDate'] = FormatDateForSQL($_REQUEST['grDate']);
	$data['client_id'] = $_REQUEST['client_id'];
	$data['partyPO'] = $_REQUEST['partyPO'];
	$data['dispatchNo'] = $_REQUEST['dispatchNo'];
	$data['cuurentBalance'] = $_REQUEST['cuurentBalance'];
	$data['creditLimit'] = $_REQUEST['creditLimit'];
	$data['dispatchThrough'] = $_REQUEST['dispatchThrough'];
	$data['excisableComm'] = $_REQUEST['excisableComm'];
	$data['transportMode'] = $_REQUEST['transportMode'];
	$data['transporter'] = $_REQUEST['transporter'];
	$data['vehicleNo'] = $_REQUEST['vehicleNo'];
	$data['formType'] = $_REQUEST['formType'];
	$data['formNo'] =$_REQUEST['formNo'];
	$data['payTerms'] = $_REQUEST['payTerms'];
	$data['challanNo'] = $_REQUEST['challanNo'];
	$data['basicAmount'] = $_REQUEST['basicAmount'];	
	$data['totalDiscountedPrice'] = $_REQUEST['totalDiscountedPrice'];	
	$data['exciseDuty'] = $_REQUEST['exciseDuty'];
	$data['exciseValue'] = $_REQUEST['exciseValue'];
	$data['ECessPercentage'] = $_REQUEST['ECessPercentage'];
	$data['ECessValue'] = $_REQUEST['ECessValue'];
	$data['SAHCessPercentage'] = $_REQUEST['SAHCessPercentage'];
	$data['SAHCessValue'] = $_REQUEST['SAHCessValue'];
	$data['taxableAmount'] = $_REQUEST['taxableAmount'];
	$data['VatCst'] = $_REQUEST['VatCst'];
	$data['VatCstValue'] = $_REQUEST['VatCstValue'];
	$data['freightValue'] =$_REQUEST['freightValue'];
	$data['packagingCharges'] = $_REQUEST['packagingCharges'];
	$data['additionalCharges'] = $_REQUEST['additionalCharges'];
 	$data['roundOff'] =$_REQUEST['roundOff'];
	$data['grandTotal'] = $_REQUEST['grandTotal'];
	$data['pending_amount'] = $_REQUEST['grandTotal'];
	$data['excise_duty_inwords'] = $_REQUEST['excise_duty_inwords'];
	$data['ledger_id'] = $_REQUEST['ledger_id'];     
	 $data['Excise_Effect'] = $_REQUEST['Excise_Effect'];     
	 
	$data['CompanyId'] = $_SESSION['ACGCompanyId'];
	$data['created_by'] = $_SESSION['UserID'];
	$data['created_date'] = date('Y-m-d');
}
if($_REQUEST['action']=='edit' && !$_REQUEST['Save_invoice'] )
{
	//unset($_SESSION['invoice_items']);
 	$cond="invoice_id='".$_REQUEST['id']."'";
    $GetRecord=$s->GetRecord("invoice",$cond);
    $result=DB_query($GetRecord,$db);
 	$row_invoice=DB_fetch_array($result);
	$_REQUEST['client_id']= $row_invoice['client_id'];
	$_REQUEST['invoice_type']= $row_invoice['invoice_type'];
 	$getclient_address=DB_query('select * from clientmaster where id="'.$row_invoice['client_id'].'"',$db);
	$rdata=DB_fetch_array($getclient_address);
	$_REQUEST['pre_address1']= $rdata['pre_address1'];
	$_REQUEST['pre_address2']= $rdata['pre_address2'];
	$_REQUEST['pre_address3']= $rdata['pre_address3'];
	$_REQUEST['fax']= $rdata['fax'];
	$_REQUEST['ledger_id']= $row_invoice['ledger_id'];
	$_REQUEST['Excise_Effect']= $row_invoice['Excise_Effect'];
	$_REQUEST['branch_name']= $row_invoice['branch_name'];
	$_REQUEST['invoice_number']= $row_invoice['invoice_number'];
	$_REQUEST['invoice_code']= $row_invoice['invoice_code'];
	$_REQUEST['our_ref_no']= $row_invoice['our_ref_no'];
	$_REQUEST['our_ref_date']= $row_invoice['our_ref_date'];
	$_REQUEST['invoice_date']= $row_invoice['invoice_date'];
	$_REQUEST['vendorcode']= $row_invoice['vendorcode'];
	$_REQUEST['po_date']=$row_invoice['po_date'];
	$_REQUEST['po_no']=$row_invoice['po_no'];
	$_REQUEST['form_type']= $row_invoice['form_type'];
	$_REQUEST['form_no']= $row_invoice['form_no'];
	$_REQUEST['cst_vat_no']= $row_invoice['cst_vat_no'];
	$_REQUEST['ecc_no']= $row_invoice['ecc_no'];
	$_REQUEST['despatch_mode']= $row_invoice['despatch_mode'];
	$_REQUEST['gr_no']= $row_invoice['gr_no'];
	$_REQUEST['gr_no_date']= $row_invoice['gr_no_date'];
	$_REQUEST['name_of_commmodity']= $row_invoice['name_of_commmodity'];
	$_REQUEST['destination']= $row_invoice['destination'];
	$_REQUEST['salesmanid']= $row_invoice['salesmanid'];	
	$_REQUEST['tarrif_heading']= $row_invoice['tarrif_heading'];	
	$_REQUEST['payment_terms']= $row_invoice['payment_terms'];	
	$_REQUEST['value_of_goods']= $row_invoice['value_of_goods'];
	$_REQUEST['excise_duty']= $row_invoice['excise_duty'];
	$_REQUEST['edu_cess']= $row_invoice['edu_cess'];
	$_REQUEST['she_cess']= $row_invoice['she_cess'];	
	$_REQUEST['total_taxable'] = $row_invoice['total_taxable'];
	$_REQUEST['vat_cst_ledger']= $row_invoice['vat_cst_ledger'];
	$_REQUEST['vat_cst']= $row_invoice['vat_cst'];
	$_REQUEST['calvatcst']= $row_invoice['calvatcst'];
	
	$_REQUEST['grand_total']= $row_invoice['grand_total'];	
	$_REQUEST['issue_invoice_date']= $row_invoice['issue_invoice_date'];	
	$_REQUEST['removal_invoicedate']= $row_invoice['removal_invoicedate'];
	$_REQUEST['issue_invoice_datetime']= $row_invoice['issue_invoice_datetime'];
	$_REQUEST['removal_invoicedatetime']= $row_invoice['removal_invoicedatetime'];
	$_REQUEST['issue_invoice_time']= substr($row_invoice['issue_invoice_time'],0,5);	
	$_REQUEST['removal_invoicetime']= substr($row_invoice['removal_invoicetime'],0,5);
	$_REQUEST['mode_of_transport']= $row_invoice['mode_of_transport'];	
	$_REQUEST['vehicle_registration']= $row_invoice['vehicle_registration'];	
 	$_REQUEST['excise_duty_inwords']=$row_invoice['excise_duty_inwords'];	
  }

if($_REQUEST['Save_invoice'] ) 
{
	$data['invoiceType'] = $_REQUEST['invoiceType'];	
	$data['branch_name'] = $_REQUEST['branch_name'];
	//$client_code=$s->getField('clientmaster','id',$_REQUEST['client_id'],'client_code');
	$data['invoiceNo'] = $_REQUEST['invoiceNo'];
	$data['invoiceDate'] = FormatDateForSQL($_REQUEST['invoiceDate']);
	$data['invoiceTime'] = $_REQUEST['invoiceTime'];
	$data['invoiceAMPM'] = $_REQUEST['invoiceAMPM'];
	$data['removalDate'] = FormatDateForSQL($_REQUEST['removalDate']);	
	$data['removalTime'] = $_REQUEST['removalTime'];
	$data['removalAMPM'] = $_REQUEST['removalAMPM'];
	$data['documentType'] = $_REQUEST['documentType'];
	$data['grNo'] = $_REQUEST['grNo'];
	$data['grDate'] = FormatDateForSQL($_REQUEST['grDate']);
	$data['client_id'] = $_REQUEST['client_id'];
	$data['partyPO'] = $_REQUEST['partyPO'];
	$data['dispatchNo'] = $_REQUEST['dispatchNo'];
	$data['cuurentBalance'] = $_REQUEST['cuurentBalance'];
	$data['creditLimit'] = $_REQUEST['creditLimit'];
	$data['dispatchThrough'] = $_REQUEST['dispatchThrough'];
	$data['excisableComm'] = $_REQUEST['excisableComm'];
	$data['transportMode'] = $_REQUEST['transportMode'];
	$data['transporter'] = $_REQUEST['transporter'];
	$data['vehicleNo'] = $_REQUEST['vehicleNo'];
	$data['formType'] = $_REQUEST['formType'];
	$data['formNo'] =$_REQUEST['formNo'];
	$data['payTerms'] = $_REQUEST['payTerms'];
	$data['challanNo'] = $_REQUEST['challanNo'];
	$data['basicAmount'] = $_REQUEST['basicAmount'];	
	$data['totalDiscountedPrice'] = $_REQUEST['totalDiscountedPrice'];	
	$data['exciseDuty'] = $_REQUEST['exciseDuty'];
	$data['exciseValue'] = $_REQUEST['exciseValue'];
	$data['ECessPercentage'] = $_REQUEST['ECessPercentage'];
	$data['ECessValue'] = $_REQUEST['ECessValue'];
	$data['SAHCessPercentage'] = $_REQUEST['SAHCessPercentage'];
	$data['SAHCessValue'] = $_REQUEST['SAHCessValue'];
	$data['taxableAmount'] = $_REQUEST['taxableAmount'];
	$data['VatCst'] = $_REQUEST['VatCst'];
	$data['VatCstValue'] = $_REQUEST['VatCstValue'];
	$data['freightValue'] =$_REQUEST['freightValue'];
	$data['packagingCharges'] = $_REQUEST['packagingCharges'];
	$data['additionalCharges'] = $_REQUEST['additionalCharges'];
 	$data['roundOff'] =$_REQUEST['roundOff'];
	$data['grandTotal'] = $_REQUEST['grandTotal'];
	$data['pending_amount'] = $_REQUEST['grandTotal'];
	$data['excise_duty_inwords'] = $_REQUEST['excise_duty_inwords'];
	$data['ledger_id'] = $_REQUEST['ledger_id'];     
	 $data['Excise_Effect'] = $_REQUEST['Excise_Effect'];     
	 
	$data['CompanyId'] = $_SESSION['ACGCompanyId'];
	$data['created_by'] = $_SESSION['UserID'];
	$data['created_date'] = date('Y-m-d'); 
  	$insert_invoice=$s->insertRecord('invoice', $data);
 	$insertResult = DB_query($insert_invoice,$db,$ErrMsg); 
		if(!$insertResult)
			{
			  die("Not Inserted".DB_error_msg($db));
			}
			$Lastreq_id=DB_Last_Insert_ID($db,'invoice',$ErrMsg);
			for($i=0;$i<$_REQUEST['rowcount'];$i++)
			{
					$data_arr['invoiceid']= $Lastreq_id;
					$data_arr['saleOrderNo']= $_POST['saleOrderNo'][$i];
					$data_arr['ItemCode']= $_POST['ItemCode'][$i];
					$data_arr['PackageDesc']= $_POST['PackageDesc'][$i];
					$data_arr['Quantity']= $_REQUEST['Quantity'][$i];
					$data_arr['RatePerThousand']= $_POST['RatePerThousand'][$i];
					$data_arr['Amount']= $_POST['Amount'][$i];
					$data_arr['discountType']= $_REQUEST['discountType'][$i];
					$data_arr['discount']= $_REQUEST['discount'][$i];
					$data_arr['EdRate']= $_REQUEST['HidRate'][$i];
					$data_arr['EdAmount']= $_REQUEST['EDamount'][$i];
					$data_arr['valueAfterDisc']= $_REQUEST['valueAfterDisc'][$i];
					$data_arr['otherSpecs']= $_REQUEST['otherSpecs'][$i];					
					$data_arr['saleqty']= $_REQUEST['saleqty'][$i];
					$data_arr['salerate']= $_REQUEST['salerate'][$i];
					$data_arr['totalsaleamount']= $_REQUEST['totalsalerate'][$i];
					
					$insert_invoice=$s->insertRecord('invoice_details', $data_arr);
					$insertResult = DB_query($insert_invoice,$db,$ErrMsg); 
			}
$updateDispatchStat=DB_query("Update addmrn set invoice_status='1' where id='".$_REQUEST['dispatchNo']."'",$db);
$updateFormStatus=DB_query("Update party_form_master set invoice_status=1 where id='".$_REQUEST['formNo']."'",$db);

	 $s->pageLocation('index.php?route=ViewInvoicetrading&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].$rurl);
}

if(isset($_POST['Save_invoice']))
{
	/*$check_form=DB_query("select formNo from invoice where invoice_id='".$_REQUEST['id']."'",$db);
	$form_res=DB_fetch_array($check_form);
	if($form_res['formNo']!=$_REQUEST['formNo'])
	{
		$update1=DB_query("Update party_form_master set invoice_status=0 where id='".$form_res['formNo']."'",$db);
		$update1=DB_query("Update party_form_master set invoice_status=1 where id='".$_REQUEST['formNo']."'",$db);
	}*/
	
	for($i=0;$i<$_REQUEST['rowcount'];$i++)
			{
					$data_arr['PackageDesc']= $_POST['PackageDesc'][$i];
					$data_arr['Quantity']= $_REQUEST['Quantity'][$i];
					$data_arr['RatePerThousand']= $_POST['RatePerThousand'][$i];
					$data_arr['Amount']= $_POST['Amount'][$i];
					$data_arr['discountType']= $_REQUEST['discountType'][$i];
					$data_arr['discount']= $_REQUEST['discount'][$i];
					$data_arr['EdRate']= $_REQUEST['HidRate'][$i];
					$data_arr['EdAmount']= $_REQUEST['EDamount'][$i];
					$data_arr['valueAfterDisc']= $_REQUEST['valueAfterDisc'][$i];
					$data_arr['otherSpecs']= $_REQUEST['otherSpecs'][$i];
					
					$insert="update invoice_details set 
									PackageDesc='".$data_arr['PackageDesc']."', 
									RatePerThousand='".$data_arr['RatePerThousand']."',
									Amount='".$data_arr['Amount']."',
					         		discountType='".$data_arr['discountType']."',
									discount='".$data_arr['discount']."',
									EdRate='".$data_arr['EdRate']."',
									EdAmount='".$data_arr['EdAmount']."',
					         		valueAfterDisc='".$data_arr['valueAfterDisc']."',
									otherSpecs='".$data_arr['otherSpecs']."' 
									where id='".$_REQUEST['invoieid'][$i]."'"; echo "<br>";
					$query=DB_query($insert,$db);
			}
		$upadate1="update invoice set 
					invoiceDate='".FormatDateForSQL($_REQUEST['invoiceDate'])."',
					removalDate='".FormatDateForSQL($_REQUEST['removalDate'])."',
					grNo='".$_REQUEST['grNo']."',
					grDate='".FormatDateForSQL($_REQUEST['grDate'])."',
					partyPO='".$_REQUEST['partyPO']."',
	                dispatchThrough='".$_REQUEST['dispatchThrough']."',
					excisableComm ='".$_REQUEST['excisableComm']."',
	                transportMode ='". $_REQUEST['transportMode']."',
					transporter ='".$_REQUEST['transporter']."',
					vehicleNo='".$_REQUEST['vehicleNo']."',
					formType='".$_REQUEST['formType']."',
					formNo ='".$_REQUEST['formNo']."',
	                payTerms ='". $_REQUEST['payTerms']."',
					challanNo ='".$_REQUEST['challanNo']."',
					invoiceType ='".$_REQUEST['invoiceType']."',
					branch_name ='". $_REQUEST['branch_name']."',
	             	invoiceNo ='".$_REQUEST['invoiceNo']."',
					invoiceTime ='".$_REQUEST['invoiceTime']."',
	            	removalTime = '".$_REQUEST['removalTime']."',
					documentType='".$_REQUEST['documentType']."',
	                basicAmount='".$_REQUEST['basicAmount']."',
					totalDiscountedPrice='".$_REQUEST['totalDiscountedPrice']."',
					exciseDuty ='".$_REQUEST['exciseDuty']."',
					exciseValue='".$_REQUEST['exciseValue']."',
					ECessPercentage='".$_REQUEST['ECessPercentage']."',
                 	ECessValue ='".$_REQUEST['ECessValue']."',
					SAHCessPercentage='".$_REQUEST['SAHCessPercentage']."',
					SAHCessValue='".$_REQUEST['SAHCessValue']."',
	                taxableAmount='".$_REQUEST['taxableAmount']."',
				    VatCst='".$_REQUEST['VatCst']."',
					VatCstValue ='".$_REQUEST['VatCstValue']."',
	      			freightValue ='".$_REQUEST['freightValue']."',
					packagingCharges ='".$_REQUEST['packagingCharges']."',
					additionalCharges='".$_REQUEST['additionalCharges']."',
 					roundOff ='".$_REQUEST['roundOff']."',
					grandTotal='".$_REQUEST['grandTotal']."',
					excise_duty_inwords ='".$_REQUEST['excise_duty_inwords']."',
					Excise_Effect='".$_REQUEST['Excise_Effect']."',
					ledger_id ='".$_REQUEST['ledger_id']."' 
					where invoice_id='".$_REQUEST['id']."'"; exit;
	$query11=DB_query($upadate1,$db);   
	$s->pageLocation('index.php?route=ViewInvoice&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].$rurl);  
}


if($_REQUEST['action']=='edit' && $_REQUEST['id']!='')
{
	$sql="Select * from invoice where invoice_id='".$_REQUEST['id']."'";
	$result=DB_query($sql,$db);
	$invoiceRow=DB_fetch_array($result);	
	
	$productSql="SELECT * FROM `invoice_details` where invoiceid='".$_REQUEST['id']."'";
	$productResult=DB_query($productSql,$db);		
	
	$invoiceType=$invoiceRow['invoiceType'];  
	$branch_name=$invoiceRow['branch_name'];  
	$invoiceNo=$invoiceRow['invoiceNo'];  
	$invoiceDate=ConvertSQLDate($invoiceRow['invoiceDate']);  
	$invoiceTime=$invoiceRow['invoiceTime'];  
	$invoiceAMPM=$invoiceRow['invoiceAMPM'];  
	$removalDate=ConvertSQLDate($invoiceRow['removalDate']);  
	$removalTime=$invoiceRow['removalTime'];  
	$removalAMPM=$invoiceRow['removalAMPM'];  
	$documentType=$invoiceRow['documentType'];  
	$grNo=$invoiceRow['grNo'];    
	$grDate=ConvertSQLDate($invoiceRow['grDate']);  
	$client_id=$invoiceRow['client_id'];  
	$partyPO=$invoiceRow['partyPO'];  
	$dispatchNo=$invoiceRow['dispatchNo'];  
	$cuurentBalance=$invoiceRow['cuurentBalance'];  
	$creditLimit=$invoiceRow['creditLimit'];  
	$dispatchThrough=$invoiceRow['dispatchThrough'];  
	$excisableComm=$invoiceRow['excisableComm'];  
	$transportMode=$invoiceRow['transportMode'];  
	$transporter=$invoiceRow['transporter'];  
	$vehicleNo=$invoiceRow['vehicleNo'];   
	$formType=$invoiceRow['formType'];  
	$formNo=$invoiceRow['formNo'];  
	$payTerms=$invoiceRow['payTerms'];  
	$challanNo=$invoiceRow['challanNo'];  
	$basicAmount=$invoiceRow['basicAmount'];  
	$totalDiscountedPrice=$invoiceRow['totalDiscountedPrice'];  
	$exciseDuty=$invoiceRow['exciseDuty'];  
	$exciseValue=$invoiceRow['exciseValue'];  
	$ECessPercentage=$invoiceRow['ECessPercentage'];  
	$ECessValue=$invoiceRow['ECessValue'];  
	$SAHCessPercentage=$invoiceRow['AHCessPercentage'];  
	$SAHCessValue=$invoiceRow['SAHCessValue'];  
	$taxableAmount=$invoiceRow['taxableAmount'];  
	$VatCst=$invoiceRow['VatCst'];  
	$VatCstValue=$invoiceRow['VatCstValue'];  
	$freightValue=$invoiceRow['freightValue'];  
	$packagingCharges=$invoiceRow['packagingCharges'];  
	$additionalCharges=$invoiceRow['additionalCharges'];  
	$roundOff=$invoiceRow['oundOff'];  
	$grandTotal=$invoiceRow['oundOff'];  
	$excise_duty_inwords=$invoiceRow['excise_duty_inwords'];     
	$ledger_id=$invoiceRow['ledger_id'];
	$Excise_Effect=$invoiceRow['Excise_Effect'];
	
}
else
{
	$invoiceType=$_REQUEST['invoiceType'];  
	$branch_name=$_REQUEST['branch_name'];  
	$invoiceNo=$_REQUEST['invoiceNo'];  
	$invoiceDate=date('d/m/Y');  
	$invoiceTime=$timestamp;  
	$invoiceAMPM=$_REQUEST['invoiceAMPM'];  
	$removalDate=date('d/m/Y');  
	$removalTime=$timestamp;  
	$removalAMPM=$_REQUEST['removalAMPM'];  
	$documentType=$_REQUEST['documentType'];  
	$grNo=$_REQUEST['grNo'];    
	$grDate=date('d/m/Y');  
	$client_id=$_REQUEST['client_id'];  
	$partyPO=$_REQUEST['partyPO'];  
	$dispatchNo=$_REQUEST['dispatchNo'];  
	$cuurentBalance=$_REQUEST['cuurentBalance'];  
	$creditLimit=$_REQUEST['creditLimit'];  
	$dispatchThrough=$_REQUEST['dispatchThrough'];  
	$excisableComm=$_REQUEST['excisableComm'];  
	$transportMode=$_REQUEST['transportMode'];  
	$transporter=$_REQUEST['transporter'];  
	$vehicleNo=$_REQUEST['ehicleNo'];   
	$formType=$_REQUEST['formType'];  
	$formNo=$_REQUEST['formNo'];  
	$payTerms=$_REQUEST['payTerms'];  
	$challanNo=$_REQUEST['challanNo'];  
	$basicAmount=$_REQUEST['basicAmount'];  
	$totalDiscountedPrice=$_REQUEST['totalDiscountedPrice'];  
	$exciseDuty=$_REQUEST['exciseDuty'];  
	$exciseValue=$_REQUEST['exciseValue'];  
	$ECessPercentage=$_REQUEST['ECessPercentage'];  
	$ECessValue=$_REQUEST['ECessValue'];  
	$SAHCessPercentage=$_REQUEST['AHCessPercentage'];  
	$SAHCessValue=$_REQUEST['SAHCessValue'];  
	$taxableAmount=$_REQUEST['taxableAmount'];  
	$VatCst=$_REQUEST['VatCst'];  
	$VatCstValue=$_REQUEST['VatCstValue'];  
	$freightValue=$_REQUEST['freightValue'];  
	$packagingCharges=$_REQUEST['packagingCharges'];  
	$additionalCharges=$_REQUEST['additionalCharges'];  
	$roundOff=$_REQUEST['oundOff'];  
	$grandTotal=$_REQUEST['oundOff'];  
	$excise_duty_inwords=$_REQUEST['excise_duty_inwords'];     
	$ledger_id=$_REQUEST['ledger_id'];
	$Excise_Effect=$_REQUEST['Excise_Effect'];
}
?>                                
<div style="width:800px; margin-left:auto; margin-right:auto;">
<fieldset>
<legend>INVOICE</legend>
<form name="invoice" action="" method="post">
	<table>
		<tr>
		<th>Invoice Type<label><font color="#FF0000">*</font></label></th>
		<td><select name="invoiceType" style="width:107px; height:20px;">
				<option value="Trading">Trading</option>
		</select></td>
	</tr>
	</table>
	<br>
<table width="80%" cellpadding="0" cellspacing="0"  border="0" align="center">
<tr><td bgcolor="#CCCCCC">
<table width="100%" cellpadding="0" cellspacing="1" border="0">	
<tr>
<td bgcolor="#FFFFFF">
<table width="100%" border="0" cellspacing="1" cellpadding="1" align="center">
<tr>
<th width="21%" scope="row">Branch Name<label><font color="#FF0000">*</font></label></th>
<td width="28%"><?php 
if($_SESSION['AssignedSites']!='0')
	  {
	 	$site_sql = DB_query("SELECT prefix,loccode,locationname from locations   where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in ('".$_SESSION['AssignedBranch']."')",$db);}
		else
		{
		$site_sql = DB_query("SELECT prefix,loccode,locationname from locations  where CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
		}


?>
<select name="branch_name" id="branch_name" style="width:100%; height:20px;" tabindex="1"  onChange="invoiceCode(this.value)">
	<option value="0">Select</option>
<?php
while($row_client=DB_fetch_array($site_sql))
{
?>
<option value="<?php  echo $row_client['prefix']?>" <?php echo ($branch_name==$row_client['prefix']?'selected':''); ?> >
<?php  echo $row_client['locationname']?>
</option>
<?php }?>
</select></td>
<th width="26%">Invoice No.<label><font color="#FF0000">*</font></label></th>
<td width="25%" id="invoiceDiv"><input type="text" name="invoiceNo" id="invoiceNo" value="<?php echo $invoiceNo;?>" style="width:100%" /></td>
</tr>

<tr>
<th scope="row">Invoice Date/Time<label><font color="#FF0000">*</font></label></th>
<td><input type="text" name="invoiceDate" id="invoiceDate" value="<?php echo $invoiceDate;?>"  style="width:50%"  /> <input type="text" name="invoiceTime" id="invoiceTime" value="<?php echo $invoiceTime;?>"  style="width:48%" /></td>
<th>Removal Date/Time<label><font color="#FF0000">*</font></label></th>
<td><input type="text" name="removalDate" id="removalDate" value="<?php echo $removalDate;?>"  style="width:50%"  /> <input type="text" name="removalTime" id="removalTime" value="<?php echo $removalTime;?>" style="width:48%" /></td>
</tr>

<tr>
<th scope="row">Document Type<label><font color="#FF0000">*</font></label></th>
<td><select  name="documentType" id="documentType" style="width:100%; height:20px;">	
  <option value="0">Select</option>
  <option value="Bill"<?php echo ($documentType=='Bill'?'selected':'')?>>Bill</option>
  
</select></td>
<th>GR. No.</th>
<td><input type="text" name="grNo" id="grNo" value="<?php echo $grNo;?>" style="width:100%" /></td>
</tr>
<tr>
<th scope="row">Party Name<label><font color="#FF0000">*</font></label></th>
<td><?php

//$arr_con_acc=array();
//$con_accountSql=DB_query("Select Convert_AccountId from crm_leads where deleted_status='N' and Convert_IntoAccountStatus='Y'",$db);
//if(DB_num_rows($con_accountSql)>0)
//{
//while($row_Conacc=DB_fetch_array($con_accountSql))
//{
//$arr_con_acc[]=$row_Conacc['Convert_AccountId'];
//}
//$x="'";
//if(count($arr_con_acc)>0)
//{
//$x.=implode("', '",$arr_con_acc)."'";
//}

//$AccountCompany= "SELECT * FROM accountledger WHERE  ledgertype IN('client') or AccountsID IN ($x)";
//}
//else{
//$AccountCompany= "SELECT * FROM accountledger WHERE  ledgertype IN('client') ";

//}

//echo $AccountCompany;

//$Account_sql=DB_query($AccountCompany,$db);

?><select name="client_id" id="client_id" style="width: 100%" onChange="showclient111(this.value)">
<option value="0">Select</option>
<?php

//while($Account_row=DB_fetch_array($Account_sql))
//{

 //if($Account_row['ledgertype']=='client'){
	//  	 $ClientSQL="Select Site,Zone from clientmaster where CompanyId='".$_SESSION['ACGCompanyId']."' and  Site='".$_SESSION['AssignedBranch']."' 
		// and id='".$Account_row['vender_client']."' and  Zone in(".$_SESSION['AssignedSites'].") ";
		 //}
		 //else  if($Account_row['ledgertype']=='leads')
		 //{
		 //$ClientSQL="Select Site,Zone from clientmaster where CompanyId='".$_SESSION['ACGCompanyId']."' and  Site='".$_SESSION['AssignedBranch']."' 
		 //and id='".$Account_row['AccountName']."' and  Zone in(".$_SESSION['AssignedSites'].") ";
 		 //}
		 
// echo $ClientSQL;
$ClientSQL=DB_query("select * from clientmaster",$db);
		while($ClientRes=DB_fetch_array($ClientSQL))
		{
		  
?>
<option value="<?php echo $ClientRes['id']?>"<?php echo($client_id==$ClientRes['id'] ? 'selected':'');?>><?php
//if($Account_row['ledgertype']=='leads')
		//echo $s->GetFieldValue('clientmaster',"id='".$Account_row['AccountName']."'",'c_name');
		//else 
	  echo $ClientRes['c_name'];?>

 </option>

<?php 	 }

?>
</select></td>
<th>GR. Date</th>
<td><input type="text" name="grDate" id="grDate" value="<?php echo $grDate;?>"  style="width:100%" class="datepicker"/></td>
</tr>

</table>
<?php 
$partySql=DB_query("Select client_code,pre_address1,pre_address2,pre_address3,pre_country,pre_state,pre_city from clientmaster where id='".$client_id."'",$db);
$partyRow=DB_fetch_array($partySql);
$countryName=$s->getField('country_master','id',$partyRow['pre_country'],'country');
$stateName=$s->getField('state_master','id',$partyRow['pre_state'],'state');
$cityName=$s->getField('city_master','id',$partyRow['pre_city'],'city');
?>
</td>
</tr>

<tr>
<td bgcolor="#FFFFFF" > <div id="partyDispatch">
<table width="100%" cellspacing="1" cellpadding="1"  border="0">
<tr>
<th width="21%" scope="row" rowspan="4">Address</th>
<td width="28%"><input type="text" name="address1" id="" value="<?php echo $partyRow['pre_address1'];?>"  style="width:100%" /></td>
<th width="26%">MRN. No.</th>
<td width="25%">
<select  name="dispatchNo" id="dispatchNo" style="width:100%; height:20px;" >
  <option value="0">Select</option>
  <?php
  $site_code=$s->getField('locations','prefix',$branch_name,'loccode');
 $dispatch_Sql=DB_query("Select id,adviceNo from dispatch where party='".$partyRow['client_code']."' and site='".$site_code."'",$db);
while($dispatchRow=DB_fetch_array($dispatch_Sql))
{
?>
<option value="<?php  echo $dispatchRow['id']?>"<?php echo ($dispatchNo==$dispatchRow['id']?'selected':'');?>><?php  echo $dispatchRow['adviceNo']?></option>
<?php }?>
</select></td>
</tr>
<tr>
<td scope="row"><input type="text" name="address2" id="address2" value="<?php echo $partyRow['pre_address2'];?>"  style="width:100%" /></td>
<th>Form No.</th>
<td><?php
//echo "Select * from party_form_master where party='".$client_id."'";
$form_no=DB_query("Select * from party_form_master where party='".$client_id."'",$db);
?>	
<select name="formNo" style="width:100%">
<?php 
while($form_row=DB_fetch_array($form_no))
{?>
	<option value="<?php echo $form_row['id'];?>"<?php if($formNo==$form_row['id']) echo "selected";?>><?php echo $form_row['formNo'];?></option>
<?php 	
}
?>
</select></td>
</tr>
<tr>
<td scope="row"><input type="text" name="address3" id="address3" value="<?php echo $partyRow['pre_address3'];?>"  style="width:100%" /></td>
<th>&nbsp;</th>
<td>&nbsp;</td>
</tr>
<tr>
<td scope="row"><input type="text" name="address4" id="address4" value="<?php echo $cityName." ".$stateName." ".$countryName;?>"  style="width:100%" /></td>
<th>&nbsp;</th>
<td>&nbsp;</td>
</tr>
</table></div>
</td>
</tr>

<tr>
<td bgcolor="#FFFFFF">
<table width="100%" cellspacing="1" cellpadding="1"  border="0">
	<tr>
	<th>Party PO No.<label><font color="#FF0000">*</font></label></th>
	<td>
	<?php 
	$item=array();
	 $SQLPNO="select * from dispatch where status='0'";
	$SQLPNO1=DB_query($SQLPNO,$db);
	if(DB_num_rows($SQLPNO1)>0)
	{
	while($SQLROW=DB_fetch_array($SQLPNO1))
	{
	$item[]=$SQLROW['againstSOP'];
	
}

$SOPList=implode(',',$item);
//print_r($SOPList);
//echo "select PORefNo from salesorder where id in(".$SOPList.")";
	$SQLDISde=DB_query("select PORefNo from salesorder where id in(".$SOPList.")",$db);
	while($SQLDISdeROW=DB_fetch_array($SQLDISde))
		{
			$PONo[]=$SQLDISdeROW['PORefNo'];
		}
	$PORef=implode(',',$PONo);
	}
	?>
	
	<input type="text" name="PO" id="PO" value="<?php echo $PORef; ?>"   style="width:100%" />
	<input type="hidden" name="partyPO" id="partyPO" value="<?php echo $SOPList; ?>"   style="width:100%" />
	</td>
	<th>Dispatch Through</th>
	<td><input type="text" name="dispatchThrough" id="dispatchThrough" value="<?php echo $dispatchThrough;?>" style="width:100%" /></td>	
	</tr>
	<tr>
	<th>Commodity<label><font color="#FF0000">*</font></label></th>
	<td>
	<select name="excisableComm" style="width:100%;height:20px;" onchange="getTarrifHeading(this.value)" >
		<option value="">Select</option>
		<?php 
		$excisableSql=DB_query("Select * from excisable_commodity_master",$db);
		while($excisableRow=DB_fetch_array($excisableSql))
		{?>
			<option value="<?php echo $excisableRow['id']?>"<?php echo ($excisableComm==$excisableRow['id']?'selected':'')?>><?php echo $excisableRow['commodityName']?></option>
		<?php 	
		}
		?>
	</select>
		</td>
		<?php 
	$tariffSql=DB_query("Select tarrifHeading from excisable_commodity_master where id='".$excisableComm."'",$db);
	$tariffRow=DB_fetch_array($tariffSql);
		?>
	<th>Tarrif Heading</th>
	<td id="commID"><input type="text" name="tarrifHeading" value="<?php echo $tariffRow['tarrifHeading']?>" style="width:100%; height:20px;"/>
	</td>	
	</tr>
<tr>
<th width="21%">Transporter </th>
<td width="28%"><select name="transporter" id="transporter" style="width:100%; height:20px;">
<?php
$transSql=DB_query("Select id,vendor_name from suppliers where vendor_type='Transporter'",$db);
while($transRow=DB_fetch_array($transSql))
{
?>
  <option value="<?php  echo $transRow['id']?>"<?php echo ($transporter==$transRow['id']?'selected':'')?>><?php  echo $transRow['vendor_name']?></option>
  <?php }?>
</select></td>
<th width="26%">Vehicle No.</th>
<td width="25%"><input type="text" name="vehicleNo" id="vehicleNo" value="<?php echo $vehicleNo;?>"  style="width:100%" /></td>
</tr>
<tr>
<th>Form Type</th>
<td><select  name="formType" id="formType" style="width:100%; height:20px;">
	<option value="0">Select</option>
  <?php
 $formSql=DB_query("Select * from form_type_master where CompanyId='".$_SESSION['ACGCompanyId']."'",$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>
<th>Mode Of Transport</th>
	<td>
	<select name="transportMode" id="transportMode"  style="width:100%; height:20px;">
		<option value="Road"<?php echo ($transportMode=='Road'?'selected':'')?>>By Road</option>
		<option value="Air"<?php echo ($transportMode=='Air'?'selected':'')?>>By Air</option>
		<option value="Sea"<?php echo ($transportMode=='Sea'?'selected':'')?>>By Sea</option>
	</select>	
	</td>
</tr>
<tr>
<th>Payment Terms</th>
<td><select  name="payTerms" id="payTerms" style="width:100%; height:20px;">
  <?php
$paySql=DB_query("Select termsindicator,terms from paymentterms",$db);
while($payRow=DB_fetch_array($paySql))
{
?>
  <option value="<?php  echo $payRow['termsindicator']?>"<?php echo ($payTerms==$payRow['termsindicator']?'selected':'')?>><?php  echo $payRow['terms']?></option>
  <?php }?>
</select></td>
<th>Challan No.</th>
<td><input type="text" name="challanNo" id="challanNo" value="<?php echo $challanNo;?>" style="width:100%"  /></td>
</tr>
</table>
</td>
</tr>
</table>
</td></tr>
</table>
<br />
<h3 align="center">Product Details</h3>
<table width="100%" cellpadding="0" cellspacing="0"  border="0">
<tr>
<td valign="top">
<?php 
if($_REQUEST['po_no']=='')
{ $height='50px';}
else
{ $height='150px'; }
?>
<div align="center" id="productId" >
  <div style="overflow:auto; width:800px" >
    <table width="100%" border="0" cellspacing="2" cellpadding="2" class="maintable" align="center" >
      <tr>
        <th>SNo. </th>
        <th>SOP No.</th>
        <th>Item Code
          <label><font color="#FF0000">*</font></label>        </th>
        <th nowrap="nowrap"> Description
          <label><font color="#FF0000">*</font></label></th>
        <th>Unit</th>
        <th>No &amp; Description of Packaging(Box Details)
          <label><font color="#FF0000">*</font></label></th>
        <th> Quantity
          <label><font color="#FF0000">*</font></label></th>
        <th>Purchase Rate</th>
        <th>Total Bill Amt.</th>
        <th>Sale Rate </th>
        <th>Total Sale Amt.</th>

        <th>Discount</th>
        <th>Discounted Price</th>
        <th>EDRate</th>
        <th>EDAmount</th>
      </tr>
      <?php 
	 if($_REQUEST['id']!=''){
	 $i=0;
		  $sql11="select * from invoice_details where invoiceid='".$_REQUEST['id']."'";
		 $productResult1=DB_query($sql11,$db);
	 while($detail_row=DB_fetch_array($productResult1))
	 {
	 
	 	$item_sql=DB_query("Select item_name, unit from item_master where StockID='".$detail_row['ItemCode']."'",$db);
		$item_row=DB_fetch_array($item_sql);

	 ?>
      <tr bgcolor="#FFFFFF">
	  <td>&nbsp;</td>
        <td><?php echo $i+1;?>
            <input type="hidden" name="invoieid[<?php echo $i;?>]" value="<?php echo $detail_row['id']; ?>" /></td>
        <td><input type="text" name="saleOrderNo[<?php echo $i;?>]" id="saleOrderNo[<?php echo $i;?>]" value="<?php echo $detail_row['saleOrderNo'];?>" />
            <?php 
      echo $SOPCode=$s->getField('salesorder','id',$detail_row['saleOrderNo'],'orderNo');
      ?></td>
        <td><?php echo $detail_row['ItemCode'];?>
            <input type="hidden" name="ItemCode[<?php echo $i;?>]" id="ItemCode_<?php echo $i;?>" value="<?php echo $detail_row['ItemCode'];?>" /></td>
        <td><?php  $itemname=$s->getField('item_master','StockID',$detail_row['ItemCode'],'item_desc');
      	
      	 echo $itemname;?></td>
        <td><?php echo $unitname=$s->getField('unitsofmeasure','unitid',$item_row['unit'],'unitname');?> </td>
        <td><input type="text" name="PackageDesc[<?php echo $i;?>]" id="PackageDesc_<?php echo $i;?>" value="<?php echo $detail_row['PackageDesc'];?>" size="20" /></td>
        <td><input type="text" name="Quantity[<?php echo $i;?>]" id="Quantity_<?php echo $i;?>" value="<?php echo $detail_row['Quantity'];?>" size="15" readonly /></td>
        <?php
	 
	  ?>
        <td><input type="text" name="RatePerThousand[<?php echo $i;?>]"  id="RatePerThousand_<?php echo $i;?>" value="<?php echo $detail_row['RatePerThousand'];?>" size="22" /></td>
        <td><input type="text" name="Amount[<?php echo $i;?>]" id="Amount_<?php echo $i;?>" value="<?php echo $detail_row['Amount'];?>" size="15" onfocus="calculateAmount(<?php echo $i;?>)"/></td>
        <td><select name="discountType[<?php echo $i;?>]" id="discountType_<?php echo $i;?>" style="width: 98%">
            <option value="A"<?php echo ($prod_dispatch_row['DiscountType']=='A'?'selected':'')?>>Amount</option>
            <option value="P"<?php echo ($prod_dispatch_row['DiscountType']=='P'?'selected':'')?>>Percent</option>
        </select></td>
        <td><input type="text" name="discount[<?php echo $i;?>]" id="discount_<?php echo $i;?>" value="<?php echo $detail_row['discount']?>" size="15" onblur="calculateDiscount(this.value,<?php echo $i;?>)" /></td>
        <td><input type="text" name="valueAfterDisc[<?php echo $i;?>]" id="valueAfterDisc_<?php echo $i;?>" value="<?php echo $detail_row['valueAfterDisc']; ?>" size="15" readonly/></td>
        <td><select name="EDRate[<?php echo $i;?>]" id="EDRate_<?php echo $i?>" style="width:107px" 
		onchange="ShowDiv(this.value,'hid_ED_div_<?php echo $i?>','calculateExcise.php?type=TELORD&i=<?php echo $i;?>&amount='+document.getElementById('valueAfterDisc_<?php echo $i;?>').value)">
            <option value="0">--Select--</option>
            <?php
    		$ServiceSql="select * from  excise_tax WHERE caption LIKE '%excise%'" ;
			$ServiceRes=DB_query($ServiceSql,$db);
			while($ServiceRow=DB_fetch_array($ServiceRes))
			{
			?>
            <option value="<?php echo $ServiceRow['id']?>" <?php echo $detail_row['EDRate']==$ServiceRow['id']?'selected':''?>><?php echo $ServiceRow['caption']?> </option>
            <?php	
			}
    		
    		?>
          </select>
            <input type="hidden" name="HidRate[<?php echo $i;?>]" id="HidRate_<?php echo $i;?>" value="<?php echo $s->GetFieldValue('excise_tax','id',$detail_row['EDRate'],'id');?>" />        </td>
        <td><div id='hid_ED_div_<?php echo $i?>'>
            <input type="text" name="EDamount[<?php echo $i;?>]" id="EDAmt_<?php echo $i;?>" value="<?php echo $detail_row['EDAmount']; ?>" />
        </div></td>
      </tr>
      <?php $i++; } }?>
      <input name="rowcount" id="rowcount" 	type="hidden" value="<?php echo $i;?>" />
    </table>
  </div>
</div> </td>
</tr>
<tr>
<td valign="top" >
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2">&nbsp;</td>
</tr>

<tr>
<td width="50%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="4">
<tr>
<td width="33%">Total Excise Duty Payable </td>
<td width="67%">(Rs 
	<input name="total_excise_duty" id="total_excise_duty" type="text" value="<?php echo $invoiceRow['excise_duty']?>" onfocus="tonumber()"/><!-- onblur="toWords(this.value)"  -->
	 )</td>
</tr>
<tr>
<td valign="top" >Excise Duty in words Rupees.</td>
<td valign="top" ><b >
	  </b>
	 
	<input name="excise_duty_inwords" id="excise_duty_inwords" type="text" value="<?php echo $invoiceRow['excise_duty_inwords']?>" size="40" onfocus="toWords()" />	</td>
</tr>
 
<tr>
<td valign="top" >SI. No. of RG-23A Part-||</td>
<td valign="top" >&nbsp;</td>
</tr>
<tr>
<td valign="top" >SI. No. of RG-23C Part-||</td>
<td valign="top" >&nbsp;</td>
</tr>
  <tr>
    <td valign="top" >Ledger:<label><font color="#FF0000">*</font></label></td>
    <td valign="top" ><?php echo $UnderLedger;
		$result_ledger = DB_query("SELECT AccountsID,AccountName FROM accountledger",$db);
	?>
      <select name="ledger_id">
        <option value="000">Please select Ledger</option>
        <?php 			
	while($myrow_ledger = DB_fetch_row($result_ledger))
	{
	  $p='';
	  if($myrow_ledger[0]==$_REQUEST['ledger_id'] )
	  $p="selected";
	?>
        <option value="<?php echo $myrow_ledger[0]; ?>"<?php echo $p; ?>><?php echo $myrow_ledger[1]; ?></option>
        <?php }?>
        </select>            </td>
  </tr>
  <tr>
    <td valign="top" >Excise Effect<label><font color="#FF0000">*</font></label></td>
    <td valign="top" ><select name='Excise_Effect' style="width:auto">
	<option value="0">---</option>
	<option value="RG-1"  <?php echo ( $invoiceRow['Excise_Effect']=='RG-1')?'selected':''?>  >RG-1</option>
		<option value="Supplementry"  <?php echo ( $invoiceRow['Excise_Effect']=='Supplementry')?'selected':''?>  >Supplementry</option>
	</select>&nbsp;</td>
  </tr>
  <tr>
    <td valign="top" >&nbsp;</td>
    <td valign="top" >&nbsp;</td>
  </tr>
</table></td>
<td width="30%" valign="top">



<table width="95%" border="0" cellspacing="1" cellpadding="0" align="right" bgcolor="#FFFFFF" style="border:1px solid #ccc;">
    		<tr>
    	<th style="text-align:center;" colspan="2">Amount And Taxes</th>
    </tr>
    <tr>
    	  <tr>
    	    <th width="14%">Basic Amount<label><font color="#FF0000">*</font></label></th>
    	    <td width="31%"><input name="basicAmount" type="text" value="<?php echo $invoiceRow['basicAmount'];?>" size="25" style="width:98%;" onfocus="calculateBasic()" id="basicAmount" readonly /></td>
  	    </tr>
    	  <tr>
    	    <th nowrap="nowrap">Discounted Price<label><font color="#FF0000">*</font></label></th>
    	    <td><input name="totalDiscountedPrice" id="totalDiscountedPrice" type="text" value="<?php echo $invoiceRow['totalDiscountedPrice']?>" size="25" style="width:98%;" onfocus="calculateDiscounted()" /></td>
  	    </tr>
    	  <tr>
    	    <th>Excise<label><font color="#FF0000">*</font></label></th>
    	    <td nowrap="nowrap">
    	    <select name="exciseDuty" style="width:98%;" onchange="claculateExcise(this.value)">
    	       	    <option value="0">Select</option>
    	       	    <?php 
    	    $excise_sql=DB_query("Select * from excise_tax where caption like '%excise%' and form_type='Sales'",$db);
			while($excise_row=DB_fetch_array($excise_sql))
			{
				$ee='';
				if($excise_row['id']==$invoiceRow['exciseDuty'])
				{
					$ee="selected";
				}
				
				?>
				<option value="<?php echo $excise_row['id'];?>"<?php echo $ee; ?>><?php echo $excise_row['caption'];?></option>
			<?php 	
			}
    	    ?> 
  	      </select><div id="exciseId"><input name="exciseValue" id="exciseValue" type="text" value="<?php echo $invoiceRow['exciseValue']; ?>" size="25" style="width:98%;" onfocus="calculateedamount()" /></div>    	   </tr>
    	     
    	     <?php 
    	     $cessSql=DB_query("Select caption from excise_tax where caption like '%cess%'",$db);
			 $k=1;
			 while($cessRow=DB_fetch_array($cessSql))
			 {
			 	$caption[$k]=$cessRow['caption']; 
				
				$rate_sql=DB_query("Select def_rate from excise_tax where caption='".$caption[$k]."'",$db);
				while($rate_row=DB_fetch_array($rate_sql))
				{
					$rate[$k]=$rate_row['def_rate'];
				}
				$k++;
			 } 
    	     ?>
    	     <tr>
    	    <th>E-Cess</th>
    	    <td><input name="ECessPercentage" id="ECessPercentage" type="text" value="<?php if(!empty($invoiceRow['ECessPercentage'])){echo $invoiceRow['ECessPercentage']; ?><?php }else { echo $rate[1]; } ?>" size="25" style="width:20%;"  />
    	    	<input name="ECessValue" id="ECessValue" type="text" value="<?php echo $invoiceRow['ECessValue']; ?>" size="25" style="width:75%;" readonly onfocus="calculateECess()"/></td>
    	    </tr>
    	    <tr>
            <th nowrap="nowrap">SAH-E Cess </th>
    	    <td><input name="SAHCessPercentage" id="SAHCessPercentage" type="text" value="<?php if(!empty($invoiceRow['SAHCessPercentage'])){echo $invoiceRow['SAHCessPercentage']; ?><?php }else {  echo $rate[2]; }?>" size="25" style="width:20%;" />
    	    	<input name="SAHCessValue" id="SAHCessValue" type="text" value="<?php echo $invoiceRow['SAHCessValue']; ?>" size="25" style="width:75%;" readonly onfocus="calculateSAHCess()"/></td>
  	    	</tr>
    	  
    	  
   <tr>
   	<th>Taxable Amount</th>
   	<td><input name="taxableAmount" id="taxableAmount" type="text" value="<?php echo $invoiceRow['taxableAmount']; ?>" size="25" style="width:98%;" onfocus="calculateTaxable()"/></td>
   </tr>
    	  
    	  
    	  
    	  <tr>
    	    <th>VAT/CST</th>
    	    <td nowrap="nowrap">
    	    <select name="VatCst" id="value3" style="width:98%;" onchange="calculateVATCST(this.value)">
    	    <option value="">Select</option>
    	    <?php 
    	    $salesSql=DB_query("Select * from sales_tax_master",$db);
			while($salesRow=DB_fetch_array($salesSql))
			{ $aa='';
			if($salesRow['salestax_id']==$invoiceRow['VatCst'])
			{
			$aa="selected";	
			}
				?>
				<option value="<?php echo $salesRow['salestax_id'];?>"<?php echo $aa; ?>><?php echo $salesRow['tax_code'];?></option>
			<?php 	
			}
    	    ?>
  	      </select>
    	      <div id="VATId"><input name="VatCstValue" id="VatCstValue" type="text" value="<?php echo $invoiceRow['VatCstValue']; ?>" size="25" style="width:98%;" readonly /></div></td>
  	    </tr>
    	  <tr>
    	    <th>Freight</th>
    	    <td><input name="freightValue" id="value2" type="text" value="<?php echo $invoiceRow['freightValue']; ?>" size="25" style="width:98%;" /></td>
  	    </tr>
    	  <tr>
    	    <th>Pkg Charges</th>
    	    <td><input name="packagingCharges" id="value1" type="text" value="<?php echo $invoiceRow['packagingCharges']; ?>" size="25" style="width:98%;" /></td>
  	    </tr>
  	    <tr>
    	    <th>Additional Charges</th>
    	    <td><input name="additionalCharges" id="value4" type="text" value="<?php echo $invoiceRow['additionalCharges']; ?>" size="25" style="width:98%;" /></td>
  	    </tr>
    	  <tr>
    	    <th>Rounded Off Value</th>
    	    <td><input name="roundOff" id="roundOff" type="text" value="<?php echo $invoiceRow['roundOff']; ?>" size="25" style="width:98%;" readonly="true" /></td>
  	    </tr>
    	  <tr>
    	    <th>Grand Total<label><font color="#FF0000">*</font></label></th>
    	    <td><input name="grandTotal" id="grandTotal" type="text" value="<?php echo $invoiceRow['grandTotal']; ?>" size="25" style="width:98%;" onfocus="calculateGrand()" /></td>
  	    </tr>
  	    </table></td>
</tr>
<tr>
<td colspan="2"><center>
  <input name="Save_invoice"  value="Save" type="submit" class="bottonsview" onclick="return validate_invoice()" />
  <a href="index.php?route=ViewInvoice<?php  echo $rurl; ?>"><input name="Cancel" type="button" value="Cancel"  class="bottonsview" /></a>
</center></td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
</table></td>
</tr>
<tr>
  	<td valign="top" >&nbsp;</td>
  </tr>
</table>
</form>
</fieldset>
</div>
<script language="javascript"  type="text/javascript">
 function validate_invoice()
 	{
		if(document.invoice.invoiceType.value=='0')
			{
				alert("Please Select Invoice Type First");
				return false;
			}
			else if(document.invoice.branch_name.value=='0')
			{
				alert("Please Select Branch First");
				return false;
			}
			else if(document.invoice.invoiceNo.value=='')
			{
				alert("Please Enter The Invoice No.");
				return false;
			}
			else if(document.invoice.invoiceDate.value=='')
			{
				alert("Please Enter The Invoice Date");
				return false;
			}
			else if(document.invoice.invoiceTime.value=='')
			{
				alert("Please Enter The Invoice Time");
				return false;
			}
			else if(document.invoice.removalDate.value=='')
			{
				alert("Please Enter The Removal Date");
				return false;
			}
			else if(document.invoice.removalTime.value=='')
			{
				alert("Please Enter The Removal Time");
				return false;
			}
			else if(document.invoice.documentType.value=='0')
			{
				alert("Please Select The Document Type");
				return false;
			}
			else if(document.invoice.client_id.value=='0')
			{
				alert("Please Select The Party");
				return false;
			}
			else if(document.invoice.partyPO.value=='')
			{
				alert("Please Enter The Party PO No");
				return false;
			}
			else if(document.invoice.excisableComm.value=='')
			{
				alert("Please Enter The Excisable Commodity");
				return false;
			}
			var counter=document.getElementById("rowcount").value;
			for(var x=0;x<counter;x++)
				{
					 if(document.getElementById("ItemCode_"+x).value=='')
						{
							alert("Please Enter The Item Code");
							return false;
						}
						else if(document.getElementById("PackageDesc_"+x).value=='')
						{
							alert("Please Enter The Package Description");
							return false;
						}
						else if(document.getElementById("Quantity_"+x).value=='')
						{
							alert("Please Enter The Quantity");
							return false;
						}
				}
			 if(document.invoice.ledger_id.value=='000')
				{
					alert("Please Enter the Ledger");
					return false;
				}
				else if(document.invoice.Excise_Effect.value=='0')
				{
					alert("Please Enter The Excise Effect");
					return false;
				}
				else if(document.invoice.basicAmount.value=='')
				{
					alert("Please Enter The basic Ammount");
					return false;
				}
				else if(document.invoice.totalDiscountedPrice.value=='')
				{
					alert("Please Enter The Discount Price");
					return false;
				}
				else if(document.invoice.exciseDuty.value=='0' && document.invoice.exciseValue.value=='')
				{
					alert("Please Enter The Excise Duty");
					return false;
				}
				else if(document.invoice.grandTotal.value=='')
				{
					alert("Please Enter the Grand Total Ammount");
					return false;
				}
				return true;
	}
</script>