<?ob_start();
require_once('functions.php');
require_once('print.php');
$now = new DateTime();
    $now->setTimezone(new DateTimeZone('Africa/Nairobi'));
     //$now->format('H:i:s');
    $dates = date("Y/m/d");
      $vff=$now->format('Y-m-d H:i:s');
      $vgx=$now->format('H:i:s');
$type='SALES';


?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US"><head><!-- Created by Artisteer v4.0.0.58475 -->
        <meta charset="utf-8">
        <title>POS</title>
        <!--<meta name="viewport" content="initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width">-->
        <meta name="HandheldFriendly" content="True"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
        <meta name="HandheldFriendly" content="true" />
        <meta name="MobileOptimized" content="true" />

        <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
        <link rel="stylesheet" href="style.css" media="screen">
		<link rel="stylesheet" href="test.css" media="screen">
        <!--[if lte IE 7]><link rel="stylesheet" href="style.ie7.css" media="screen" /><![endif]-->
        <link rel="stylesheet" href="style.responsive.css" media="all">


        <script src="jquery.JS"></script>
        <script src="script.js"></script>
        <script src="script.responsive.js"></script>
        <meta name="description" content="NEURO DATA">
        <meta name="keywords" content="EZ-SACCO">
				


 <nav class="art-nav clearfix">
                <?php headermenu($_SESSION['department'],'SALES'); ?> 
            </nav>

        

<?

	ini_set('display_errors', 0);
	$user=$_SESSION['user'];
	$level=$_SESSION['admin_level'];


$dbc=mysqli_connect('localhost','wqvsodvt_porr','@@W!QSER765VBlkj@@@!!','wqvsodvt_point');
	if(isset($_POST['submitted'])){
	$_SESSION['HOLD']=session_id();
	if(isset($_SESSION["products"])){
$ip=get_client_ip() ;
$tiller=teller($ip);
$session=$_SESSION['HOLD'];
	foreach ($_SESSION["products"] as $cart_itm)
    {
	 $price= $cart_itm["price"];
	$name=$cart_itm["name"];
	//$code=$cart_itm["code"];
	$system=$cart_itm["system"];
	$qty=$cart_itm["qty"];
	$vat=$cart_itm["vat"];
	$product_id=$cart_itm["product_id"];
	$r="insert into hold(product_id,product,price,qty,session,time,date,user,syste,sorc)
	values('$product_id','$name','$price','$qty','$session','$dates','$vgx','$user','$system','RETAIL')";
	$Sql=mysqli_query($dbc,$r);
	
	
	}
		unset($_SESSION['products']);

  unset($_SESSION['HOLD']);
    session_regenerate_id();

}
	
	
}
	if (isset($_POST['title']) && $_POST['title'] != '') {
	//Add slashes to any quotes to avoid SQL problems.
	$search = $_POST['title'];

	$r=("SELECT * FROM products WHERE code ='$search'");
	$sql=mysqli_query($dbc,$r);
$row=mysqli_fetch_array($sql);
	$id=$row['product_id'];
	
	
if($id&&1){
$s="select * from products where product_id='$id'";
$sql=mysqli_query($dbc,$s);
$row=mysqli_fetch_array($sql);
$product_code=$row['code'];
$product_id=$row['product_id'];
	$new_product = array(array('name'=>$row['description'],
	'system'=>$row['system'], 'code'=>$row['code'], 'qty'=>'1',
	'price'=>$row['price'],'product_id'=>$row['product_id'],'vat'=>$row['vat'],'selling'=>$row['buying']));

	if(isset($_SESSION["products"])) //if we have the session
		{
			$found = false; //set found item to false
			
			foreach ($_SESSION["products"] as $cart_itm) //loop through session array
			{
				if($cart_itm["product_id"] == $product_code){ //the item exist in array
$cart=$cart_itm["qty"]+1;
					$product[] = array('name'=>$cart_itm["name"], 'system'=>$cart_itm["system"],
					'code'=>$cart_itm["code"], 'qty'=>$cart,
					'price'=>$cart_itm["price"],'product_id'=>$cart_itm['product_id'],'vat'=>$cart_itm['vat'],'selling'=>$cart_itm['selling']);
					$found = true;
				}else{
				
					//item doesn't exist in the list, just retrive old info and prepare array for session var
					$product[] = array('name'=>$cart_itm["name"],
					'system'=>$cart_itm["system"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"],
					'price'=>$cart_itm["price"],'product_id'=>$cart_itm['product_id'],'vat'=>$cart_itm['vat'],'selling'=>$cart_itm['selling']);
				}
			}
			
			if($found == false) //we didn't find item in array
			{
				//add new user item in array
				$_SESSION["products"] = array_merge($product, $new_product);
				
			}else{
			
			
			
			
			
			
				//found user item in array list, and increased the quantity
				$_SESSION["products"] = $product;
			}
			
		}else{
			//create a new session var if does not exist
			 $_SESSION["products"] = $new_product;
		}
		//header("location: cash_sale.php");
}
	
}

if(isset($_POST['sbb'])){

$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
		$number=$rew['number']+1;
		$_SESSION['SESSION']=session_id();
		
		$user=$_SESSION['user'];
		$i ="update socode set code='$number'";
		$sqi=mysqli_query($dbc,$i);
			
foreach ($_SESSION["products"] as $cart_itm)
    {
	 $price= $cart_itm["price"];
	 $qty=$cart_itm["qty"];
	  $gtotal+=($qty*$price);
	}
	


		$ip=get_client_ip() ;
		$tiller=teller($ip);
		$receipt=$_SESSION['RECEIPT'];
		$total=$_POST['gTotal'];
		
		$type=$_POST['ttype'];
		 $ptype=$_POST['ptype'];
		
$ip=get_client_ip() ;
		$tiller=teller($ip);
		 $mpesav=$_POST['amountt'];
		 $ccode=$_POST['codee'];
		
		$D="SELECT * FROM sales where number='$receipt' and type='RECEIPT'";
		$dd=mysqli_query($dbc,$D);
		if(mysqli_num_rows($dd)==0){
		$_SESSION['RECEIPT']=$number;}
		if(mysqli_num_rows($dd)>0){
		$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
			$number=$rew['number']+1;
		$_SESSION['RECEIPT']=$number;
		}
		if($mpesav==$gtotal||$mpesav>$gtotal){
	foreach ($_SESSION["products"] as $cart_itm)
    {
	$receipt=$_SESSION['RECEIPT'];
	 $price= $cart_itm["price"];
	$name=mysqli_real_escape_string($dbc,$cart_itm["name"]);
	$code=$cart_itm["code"];
	$qty=$cart_itm["qty"];
	$id=$cart_itm["product_id"];
	$system=$cart_itm["system"];
	$tax=$cart_itm["vat"];
	
	$TOTAL=($qty*$price);
	if($tax>0){
	$totalv=0.16*($qty*$price)/1.16;
	}
	$ttv+=$totalv;
	$x=$_SESSION['SESSION'];
	$ip=get_client_ip() ;
$y="select * from products where product_id='$id'";
	$yy=mysqli_query($dbc,$y);
	$yyy=mysqli_fetch_array($yy);
	$buying=$yyy["buying"];
	$totall+=$TOTAL;
	$session=$x;
	$buy=$buying*$qty;



$buyy+=$buying*$qty;



		$tiller=teller($ip);
		$current=maximum($id);
	$t="INSERT INTO sales (p_name, qty, total_p,number, date, time,price, p_code, p_price,vat,user,session,system,current)
VALUES ('$name', '$qty', ('$TOTAL'), '$receipt', NOW(), NOW(), '$price', '$code','$buying',round('$totalv'),'$user','$x','$system','$current')";
$st=mysqli_query($dbc,$t);
$d="UPDATE products SET sold =sold + '$qty', left_p =left_p - '$qty'
WHERE product_id = '$id'";
$t=mysqli_query($dbc,$d);
$ti="select * from products where product_id='$id'";
$tt=mysqli_query($dbc,$ti);
$tu=mysqli_fetch_array($tt);
$stock=$tu['left_p'];
$f="insert into audit(product,date,value,reason,qty,number,user,stock,session)values
('$id',NOW(),'Product Sales','$tiller','$qty','$receipt','$user','$stock','$session')";
$ff=mysqli_query($dbc,$f);
	}
	$sl=GetSALES();
$ch=$ptype;
	$cc=GetCostG();
$sss=GetStock();
$desc="Sales Transaction Code $ccode";
	SalesRecOthers($totall,$receipt,$sl,$ch,$session,$desc);
	BuysRec($buyy,$receipt,$sss,$cc,$session);
	TaxRecord(GetVat(), GetKra(),date("Y/m/d"),$ttv,$receipt,$session);
	
		$t="insert into x_report(date,till,user,amount,time,type,receipt,session,number)
		values(NOW(),'$tiller','$user','$totall',NOW(),'$type','$receipt','$x','$ccode')";
		$sql=mysqli_query($dbc,$t);
		
	
	$url="mpesa.php?c=$ccode&r=$receipt&m=$mpesav&ft=$type";
	ob_end_clean();
header("Location: $url");
}
}

if(isset($_POST['sub'])){
$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
		$number=$rew['number']+1;
		$_SESSION['SESSION']=session_id();
		$_SESSION['RECEIPT']=$number;
		$user=$_SESSION['user'];
		$i ="update socode set code='$number'";
		$sqi=mysqli_query($dbc,$i);
			

	


		$ip=get_client_ip() ;
		$tiller=teller($ip);
		$rec=$_SESSION['RECEIPT'];
$total=0;
foreach ($_SESSION["products"] as $cart_itm)
    {
	 $price= $cart_itm["price"];
	 $qty=$cart_itm["qty"];
	 $gtotal+=($qty*$price);
	}
	
if($_POST['credit1']!=''){
 $credit=$_POST['credit1'];
$r="select * from return_in where credit='$credit' and status='ACTIVE'";
$sql=mysqli_query($dbc,$r);
$row=mysqli_fetch_array($sql);
 $credit1=$row['total_p'];
$total=$credit1+$total;
$ra="UPDATE return_in set status='NOT ACTIVE' where credit='$number'";
			$ri=mysqli_query($dbc,$ra);

}
if($_POST['cashm']!=''){
if($_POST['cashm']>0){
 $cash=$_POST['cashm'];}


 $total=$total+$cash;

}
if($_POST['bank']!=''){
if($_POST['bank']>0){
$cheque=$_POST['bank'];}


$total=$total+$cheque;

}
if($total>$gtotal||$total==$gtotal){
	$D="SELECT * FROM sales where number='$receipt' and type='RECEIPT'";
		$dd=mysqli_query($dbc,$D);
		if(mysqli_num_rows($dd)==0){
		$_SESSION['RECEIPT']=$number;}
		if(mysqli_num_rows($dd)>0){
		$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
			$number=$rew['number']+1;
		$_SESSION['RECEIPT']=$number;
		}
	foreach ($_SESSION["products"] as $cart_itm)
    {
	$rec=$_SESSION['RECEIPT'];
	 $price= $cart_itm["price"];
	 $qty=$cart_itm["qty"];
$name=mysqli_real_escape_string($dbc,$cart_itm["name"]);
	$code=$cart_itm["code"];
	
	$system=$cart_itm["system"];
	$id=$cart_itm["product_id"];
	$tax=$cart_itm["vat"];
	$TOTAL=($qty*$price);
	$hh+=$TOTAL;
if($tax>0){
	$totalv=0.16*($qty*$price)/1.16;
	}
	$x=$_SESSION['SESSION'];
$y="select * from products where product_id='$id'";
	$yy=mysqli_query($dbc,$y);
	$yyy=mysqli_fetch_array($yy);
	$buying=$yyy["buying"];
	$depa=$yyy['depa'];
$session=$x;
	$sl=GetSALES();
$ch=GetCash();
	$t="insert into ledgers(credit,receipt,account_id,froms,session,date,description)values('$TOTAL','$rec','$sl','$ch','$session',NOW(),'SALES')";
$tt=mysqli_query($dbc,$t);
//$account=GetId($id);
$t="insert into ledgers(debit,account_id,froms,receipt,session,date,description)values('$TOTAL','$ch','$sl','$rec','$session',NOW(),'SALES')";
$tt=mysqli_query($dbc,$t);

$buy=$buying*$qty;
$cc=GetCostG();
$sss=GetStock();

$t="insert into ledgers(credit,receipt,account_id,froms,session,date,description)values('$buy','$rec','$sss','$cc','$session',NOW(),'SALES')";
$tt=mysqli_query($dbc,$t);
//$account=GetId($id);
$t="insert into ledgers(debit,account_id,froms,receipt,session,date,description)values('$buy','$cc','$sss','$receipt','$session',NOW(),'SALES')";
$tt=mysqli_query($dbc,$t);
$current=maximum($id);
	$t="INSERT INTO sales (p_name, qty, total_p,number, date, time,price,  p_price,user,vat,session,system,current,category,prof,name)
VALUES ('$name', '$qty', ('$TOTAL'), '$receipt', '$dates', '$vff', '$price', '$buying','$user',round('$totalv'),'$x','$system','$current','$category','$fin','$cust')";
$st=mysqli_query($dbc,$t);
$d="UPDATE products SET sold =sold + '$qty', left_p =left_p - '$qty'
WHERE product_id = '$id'";
$t=mysqli_query($dbc,$d);

$ti="select * from products where product_id='$id'";
$tt=mysqli_query($dbc,$ti);
$tu=mysqli_fetch_array($tt);
$stock=$tu['left_p'];

$f="insert into audit(product,date,value,reason,qty,number,user,stock,session,depa)values
('$id',NOW(),'Product Sales','$tiller','$qty','$rec','$user','$stock','$session','$depa')";
$ff=mysqli_query($dbc,$f);
	}
	$receipt=$_SESSION['RECEIPT'];
		$to=$gtotal-$credit1;
			$t="insert into x_report(date,till,user,amount,time,type,receipt,session,bank,number)
		values(NOW(),'$tiller','$user','$to',NOW(),'CASH','$rec','$x','','')";
		$sql=mysqli_query($dbc,$t);
		$t="insert into x_report(date,till,user,amount,time,type,receipt,session,bank,number)
		values(NOW(),'$tiller','$user','$credit1',NOW(),'CREDIT NOTES','$rec','$x','','$credit')";
		$sql=mysqli_query($dbc,$t);
			
multiple($credit1,$cheque,$to,$rec,$gtotal);
	unset($_SESSION['products']);
	unset($_SESSION['RECEIPT']);
  unset($_SESSION['SESSION']);
    session_regenerate_id();
}
}

			if(isset($_POST["submit"])&&isset($_SESSION["products"])){
   $dbc=mysqli_connect('localhost','wqvsodvt_porr','@@W!QSER765VBlkj@@@!!','wqvsodvt_point');

$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
		$number=$rew['number']+1;
		session_regenerate_id();
		$_SESSION['SESSION']=session_id();
		
		$user=$_SESSION['user'];
		$i ="update socode set code='$number'";
		$sqi=mysqli_query($dbc,$i);
			

//	$dates=$_SESSION['date'];


		$ip=get_client_ip() ;
		$tiller=teller($ip);
		$receipt=$_SESSION['RECEIPT'];
		$total=$_POST['gTotal'];
		
		$type='CASH';
		
$ip=get_client_ip() ;
		$tiller=teller($ip);
		$cash=$_POST['cash'];
			$mpesa=$_POST['mpesa'];
			$fam=$_POST['family'];
			$equity=$_POST['equity'];
			$im=$_POST['im'];
			$cheq=$_POST['cheq'];
			$ltd=$_POST['ltd'];
			$cod=$_POST['code'];
		$change=$_POST['change'];
	//	$discount=$_POST['discount'];
			$cust=$_POST['client'];
		$D="SELECT * FROM sales where number='$receipt' and type='RECEIPT'";
		$dd=mysqli_query($dbc,$D);
		if(mysqli_num_rows($dd)==0){
		$_SESSION['RECEIPT']=$number;}
		if(mysqli_num_rows($dd)>0){
		$res ="SELECT code as number FROM socode";
		$sq=mysqli_query($dbc,$res);
		$rew=mysqli_fetch_array($sq);
			$number=$rew['number']+1;
		$_SESSION['RECEIPT']=$number;
		}
		if($change==0||$change>0){
	foreach ($_SESSION["products"] as $cart_itm)
    {
	$receipt=$_SESSION['RECEIPT'];
	 $price= $cart_itm["price"];
	$name=mysqli_real_escape_string($dbc,$cart_itm["name"]);
	$code=$cart_itm["code"];
	$qty=$cart_itm["qty"];
	$id=$cart_itm["product_id"];
	$system=$cart_itm["system"];
	$tax=$cart_itm["vat"];
	
	$TOTAL=($qty*$price);
	if($tax>0){
$totalv=0.16*($qty*$price)/1.16;
}
	$ttv+=$totalv;
	$x=$_SESSION['SESSION'];
	$ip=get_client_ip() ;
$y="select * from products where product_id='$id'";
	$yy=mysqli_query($dbc,$y);
	$yyy=mysqli_fetch_array($yy);
	$buying=$yyy["buying"];
	$vat=$yyy['vat'];
	$category=$yyy['category'];
	if($vat>0){
		$totalv=0.16*($qty*$price);
		
	}else{
		$totalv=0;
		
	}
	$totall+=$TOTAL;
	$session=$x;
	$buy=$buying*$qty;

$pro=$price-$buying;
$fin=$qty*$pro;


$buyy+=$buying*$qty;

$cde=mysqli_query($dbc,("select name from accounts where id='$cust'"));
   $csq=mysqli_fetch_array($cde);
      $nmj=$csq['name'];

		$tiller=teller($ip);
		$current=maximum($id);
		$user=$_SESSION['user'];
$t="INSERT INTO sales (p_name, qty, total_p,number, date, time,price,  p_price,user,vat,session,syste,curren,category,prof,name)
VALUES ('$name', '$qty', ('$TOTAL'), '$receipt', '$dates', '$vff', '$price', '$buying','$user',round('$totalv'),'$x','$system','$current','$category','$fin','$cust')";
$st=mysqli_query($dbc,$t);
if(isset($_POST['client'])){
	$amount=$cash+$equity+$fam+$im;
	$gj="insert into customer_ledgers(credit,invoice,account_id,froms,session,date,description,mat_date,dat,qty,price)values
(('$TOTAL'),'$receipt','1','$cust','$x','$dates','$name','$dates',NOW(),'$qty','$price')";
$koo=mysqli_query($dbc,$gj);
$kii="insert into customer_ledgers(debit,account_id,froms,invoice,session,date,description,mat_date,dat,qty,price)
values(('$TOTAL'),'$cust','1','$receipt','$x','$dates','$name','$dates',NOW(),'$qty','$price')";
   $mi=mysqli_query($dbc,$kii);
   }
$d="UPDATE products SET sold =sold + '$qty', left_p =left_p - '$qty'
WHERE product_id = '$id'";
$t=mysqli_query($dbc,$d);
$ti="select * from products where product_id='$id'";
$tt=mysqli_query($dbc,$ti);
$tu=mysqli_fetch_array($tt);
$stock=$tu['left_p'];
$f="insert into audit(product,date,value,reason,qty,number,user,stock,session)values
('$id',NOW(),'Product Sales','$tiller','$qty','$receipt','$user','$stock','$session')";
$ff=mysqli_query($dbc,$f);
	}
	$sl=GetSALES();
$ch=GetCash();
	$cc=GetCostG();
$sss=GetStock();
$disc=GetDiscount();
	//SalesRec($totall,$receipt,$sl,$ch,$session);
	BuysRec($buyy,$receipt,$sss,$cc,$session);
//DiscRec($discount,$receipt,$ch,$disc,$session);
	TaxRecord(GetVat(), GetKra(),date("Y/m/d"),$ttv,$receipt,$session);
	$tota=$cash-$change;
		$t="insert into x_report(date,till,user,amount,time,type,receipt,session,refe)
		values('$dates','$tiller','$user','$tota','$vgx','$type','$receipt','$x','SALES')";
		$sql=mysqli_query($dbc,$t);
			$th=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat)values('$tota','$receipt','1','2','$x',NOW(),NOW())"));

$tm=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat)values('$tota','2','1','$receipt','$x',NOW(),NOW())"));
		if($mpesa>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$mpesa','$vgx','MPESA','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$th=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$mpesa','$receipt','$sl','8','$x',NOW(),NOW(),'$cod')"));

$tm=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$mpesa','8','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
		if($equity>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$equity','$vgx','EQUITY BANK','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$to=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$equity','$receipt','$sl','39','$x',NOW(),NOW(),'$cod')"));

$tl=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$equity','39','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
		if($im>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$im','$vgx','I&M','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$to=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$im','$receipt','$sl','38','$x',NOW(),NOW(),'$cod')"));

$tl=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$im','38','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
				if($fam>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$fam','$vgx','FAMILY BANK','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$to=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$fam','$receipt','$sl','37','$x',NOW(),NOW(),'$cod')"));

$tl=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$fam','37','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
					if($cheq>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$cheq','$vgx','CHEQUE','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$to=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$cheq','$receipt','$sl','135','$x',NOW(),NOW(),'$cod')"));

$tl=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$cheq','135','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
					if($ltd>0){
		$b="insert into x_report(date,till,user,amount,time,type,receipt,session,refe,cod)
		values('$dates','$tiller','$user','$ltd','$vgx','LTD','$receipt','$x','SALES','$cod')";
		$sql=mysqli_query($dbc,$b);	
			$to=mysqli_query($dbc,("insert into ledgers(credit,receipt,account_id,froms,session,date,dat,cod)values('$ltd','$receipt','$sl','136','$x',NOW(),NOW(),'$cod')"));

$tl=mysqli_query($dbc,("insert into ledgers(debit,account_id,froms,receipt,session,date,dat,cod)values('$ltd','136','$sl','$receipt','$x',NOW(),NOW(),'$cod')"));
		}
		if(isset($_POST['client'])){
			  if($cash>0){
   $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat)values('$tol','$cust','$dates','$receipt','2','$x',NOW())"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat)values('$tol','2','$dates','$receipt','$cust','$x',NOW())"));
}
if($equity>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$equity','$cust','$dates','$receipt','39','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$equity','39','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
if($cheq>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$cheq','$cust','$dates','$receipt','135','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$cheq','135','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
if($ltd>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$ltd','$cust','$dates','$receipt','136','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$ltd','136','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
if($im>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$im','$cust','$dates','$receipt','38','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$im','38','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
if($fam>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$fam','$cust','$dates','$receipt','37','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$fam','37','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
if($mpesa>0){
  // $tol=$cash-$change;
   $rvf=mysqli_query($dbc,("insert into customer_ledgers(credit,account_id,date,receipt,froms,session,dat,cod)values('$mpesa','$cust','$dates','$receipt','8','$x',NOW(),'$cod')"));

$rts=mysqli_query($dbc,("insert into customer_ledgers(debit,account_id,date,receipt,froms,session,dat,cod)values('$mpesa','8','$dates','$receipt','$cust','$x',NOW(),'$cod')"));
}
		}
		UserAudit($_SESSION['user_id'],"Sold receipt $receipt",date("Y/m/d"),$ip);
	$url="recei.php?c=$cash&r=$receipt&ch=$change&x=$x&d=$discount&m=$mpesa&bn=$equity&f=$fam&im=$im&cu=$cust";
	ob_end_clean();
header("Location: $url");
	
	}session_regenerate_id();
		unset($_SESSION['products']);
	unset($_SESSION['RECEIPT']);
}
mysqli_close($dbc);

			if(isset($_GET["removep"]) && isset($_SESSION["products"]))
{
	$product_id	= $_GET["removep"]; //get the product code to remove
	//$return_url 	= base64_decode($_GET["return_url"]); //get return url

	
	foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
	{	if($cart_itm["product_id"]==$product_id){
	$qty=$cart_itm["qty"];
	$price=$cart_itm["price"];
	$session=session_id();
	$teller=teller($ip);
	$code=$cart_itm["code"];
	$name=mysqli_real_escape_string($dbc,$cart_itm["name"]);
		$user=$_SESSION['user'];
	$h="insert into exemptions(qty,price,user,session,code,time,date,teller,product_id,name)
	values('$qty','$price','$user','$session','$code',NOW(),NOW(),'$teller','$product_id','$name')";
	$hh=mysqli_query($dbc,$h);
	}
		if($cart_itm["product_id"]!=$product_id){ //item does,t exist in the list
			$product[] = array('name'=>$cart_itm["name"], 'system'=>$cart_itm["system"],'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"],
			'price'=>$cart_itm["price"],'product_id'=>$cart_itm['product_id'],'vat'=>$cart_itm['vat'],'selling'=>$cart_itm['selling']);
		}
		
		//create a new product list for cart
		$_SESSION["products"] = $product;
	}
	//header("location: tables.php");
	//redirect back to original page
		header("location:tables.php");
}
?><head><title>SALES</title>

<script type="text/javascript" src="jquery-ui-1.8.2.custom.min.js"></script> 


<script type="text/javascript"> 


$(function() {

$("#dd_user_input").autocomplete({
source: "p_search.php?term=28",
minLength: 1,
select: function(event, ui) {
var getUrl = ui.item.id;
if(getUrl != '#') {
location.href = getUrl;
}
},

html: true, 

open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});

});
</script>
  <style>
input[type='text'] { font-size:15px;
font-family:"Courier New", Courier, monospace;
color:red;
 padding: 5px 0;}
</style>


<style>
td { font-family:"Courier New", Courier, monospace;
font-size: 16px; }
</style>


<html>
<script language="JavaScript" type="text/javascript" src="cash.js"></script>

<script language="JavaScript" type="text/javascript" src="shortcuts.js"></script>

  <script>
shortcut.add("Ctrl+Shift",function() {
window.location.href = window.location.href;
});
 shortcut.add("Ctrl+A",function() {
window.open("others.php", "MsgWindow", "width=800,height=500");
});
shortcut.add("Alt",function setFocusToBox(){
document.getElementById("disc").focus();
});
shortcut.add("End",function setFocusToBox(){
document.getElementById("cash").focus();
});

shortcut.add("Tab",function setFocusToBox(){
document.getElementById("amots").focus();
});
shortcut.add("Shift",function setFocusToBox(){
document.getElementById("2").focus();
});

shortcut.add("Home",function setFocusToBox(){
document.getElementById("customer").focus();
});


</script>
<script type="text/javascript">
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";
window.onhashchange=function(){
	window.location.hash="no-back-button";
}
</script>
	<SCRIPT LANGUAGE="JavaScript">
function checkIt(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        status = "This field accepts numbers only."
        return false
    }
    status = ""
    return true
}
</SCRIPT>
				  
<script type="text/javascript">
            function showUser(str)
            {
                
                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("txtHint").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET", "./search/gett.php?q=" + str, true);
                xmlhttp.send();
            }
           
        </script>
		 <script type="text/javascript">
            function showUsers(str)
            {
                
                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("txtHints").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET", "./search/gett.php?q=" + str, true);
                xmlhttp.send();
            }
           
        </script>


<script language="javascript" type="text/javascript">


function minus(){
	n=Number(document.cart.disc.value);

g=Number(document.cart.grand_total.value);

c=g-n;

a=Number(document.cart.cash.value);

b=Number(document.cart.result.value);

h=a-g;

document.cart.change.value=h.toFixed(2);

}


</script>

  <script type="text/javascript">
	function calculate() {
		n=Number(document.cart.disc.value);

g=Number(document.cart.grand_total.value);

h=g-n;
a=Number(document.cart.cash.value);

b=Number(document.cart.grand_total.value);

c=b-n;
v=a-c;
document.cart.result.value=c.toFixed(2);
  document.cart.change.value=v.toFixed(2);    
		
	}

</script>




<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('#inputform').on('keydown', 'input', function (event) {
    if (event.which == 35) {
        event.preventDefault();
        var $this = $(event.target);
        var index = parseFloat($this.attr('data-index'));
        $('[data-index="' + (index + 1).toString() + '"]').focus();
    }
});
});//]]>  

</script>
<script type="text/javascript">
function bml(){
	l=Number(document.cart.grand_total.value);
d=Number(document.cart.mpes.value);
r=Number(document.cart.eq.value);
f=Number(document.cart.fam.value);
s=Number(document.cart.im.value);
c=Number(document.cart.cheq.value);
k=Number(document.cart.ltd.value);
v=Number(document.cart.cash.value);
a=v+d+f+s+r+c+k;
p=a-l;
document.cart.change.value=p.toFixed(2);
}
</script>

<?//if(Rights($_SESSION['user_id'],$type,$_SESSION['department'])){?>


     <body>    
   <fieldset style="border-color:#000000; border-width:0px; background-color:#e8e8e8;" >
   <form  id="CODE" method="post" action="">
       <table width="900px" style="border:0px solid #033; color:#033;"><tr><td>
           
 			<form onsubmit="return false;"> 
<input id="dd_user_input" type="text" autofocus="autofocus" class="search_form" onblur="if(this.value=='')this.value=this.defaultValue;" 
onfocus="if(this.value==this.defaultValue)this.value='';" value="Search Here..."/> 
</form>
          
            </td></tr></table>
   
		</fieldset>
  <div align="center" style="font-family:Bell Gothic ,Verdana,Arial;"><h3><?echo $_SESSION['msg'];?></h3></div>
<table align="center" frame="BOX"  style="border-color:#000000;font-size:18px ;background-color:;" frame="BOX" border="0.2"  width="980px" 
 cellpadding="0"  >
 <tr><th style="border-color:#000000;background-color:#bbbbbb;">#</th><th style="border-color:#000000;background-color:#bbbbbb;">Product</th><th style="border-color:#000000;background-color:#bbbbbb;">Price</th><th
 style="border-color:#000000;background-color:#bbbbbb;" width="50">Quantity</th><th style="border-color:#000000;background-color:#bbbbbb;">Total</th><th
 style="border-color:#000000;background-color:#bbbbbb;">Empty</th>
 <th
 style="border-color:#000000;background-color:#bbbbbb;"></th></tr>
 <tr>
      <td><input type="hidden" name="price[]" onkeyup="calcTotals()" readonly/>
      </td><td><input type="hidden" required="required" name="quantity[]" onkeyup="calcTotals()" />
      </td><td><input type="hidden"  name="total[]" readonly/></td>
  </tr>
<?if(isset($_SESSION["products"]))
{
krsort($_SESSION["products"]);
    $total = 0;
  $i = 0;
    $s=0;
  $t='a';
    foreach ($_SESSION["products"] as $cart_itm)
    {
         $s++;
	$totalp+=$cart_itm["price"]*$cart_itm["qty"];
	echo '<form method="post" action="add_p.php">';
	if($_SESSION['new']==($cart_itm["name"])){
	$t='b';
	
	}
	?>
 
<tr><td  style="border-color:#000000;background-color:#e8e8e8;" width="10"><?echo $s;?></td><td  style="border-color:#000000;background-color:#e8e8e8;" width="500"><?echo UCWORDS($cart_itm["name"]);?></td>
      <td  style="border-color:#000000;background-color:#e8e8e8;" width="150">
	<?echo
	  "<input type='text' autocomplete='off'  size='2'  name='price[$i]' value=' {$cart_itm['price']}' />";?>
      </td><td   style="border-color:#000000;background-color:#e8e8e8;" ><?echo
	  "<input type='text' id='$t'  autocomplete='off' name='quantity[$i]' value=' {$cart_itm['qty']}' onfocus='javascript:this.value=\"\"' />";?>
	 
      </td><td style="border-color:#000000;background-color:#bbbbbb;">
	  <?echo number_format($cart_itm["price"]*$cart_itm["qty"]);?></td>
	  <td style="border-color:#000000;background-color:#e8e8e8;" width="5"><?echo '<a href=tables.php?removep=' . $cart_itm["product_id"] .'>';?>
	<img src="x.png"/></a></td>
<td width="1" style="border-color:#000000;background-color:#e8e8e8;"><input type="submit"name="type" value="Update" 
	 />
 
  <?
   echo '<input type="hidden" name="code" value="'.$cart_itm["product_id"].'" />
   <input type="hidden" name="number" value="'.$i.'" />';
           ?></td></tr></form><?
  	++$i;
  }}?>
<?php  
 $dbc=mysqli_connect('localhost','wqvsodvt_porr','@@W!QSER765VBlkj@@@!!','wqvsodvt_point');
$ty=mysqli_query($dbc,("select * from accounts
inner join group_accounts on group_accounts.account_id=accounts.id
where group_id='4'
and status='ACTIVE' and stat='CUSTOMER'
order by name"));
 ?>
   <form name="cart" id='inputform'  method="POST" action="tables.php" style="border-color:#000000; border-width:2; font-size:17px;">
  <tr>
      <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Grand Total</td>
      <td style="background-color:#e8e8e8;" width="130"><input type="text"  name="gTotal" value="<?echo round($totalp);?>" style="border-color:#000000;background-color:#bbbbbb"; id="grand_total"></td>
  </th></tr>
   
																		  <tr><td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Customer</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130">	
                                                                     <select name="client"  title="Client type">
                                                       
                                                            <option></option>
     <?                                               
													
    while ($row = mysqli_fetch_array($ty)) {
       $id=$row['account_id'];
	$name=$row['name'];
        echo "<option value=$id>$name</option>";
    }
    echo '</select>';?></tr>
    <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Equity Paybill</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text"  style="border-color:#000000;background-color:#bbbbbb"; value="0" name="equity" id="eq"   ></td>
  </th></tr>
    <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Family Bank</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text"  style="border-color:#000000;background-color:#bbbbbb"; value="0" name="family" id="fam"   ></td>
  </th></tr>
    <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">I&M Bank</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text"  style="border-color:#000000;background-color:#bbbbbb"; value="0" name="im" id="im"   ></td>
  </th></tr>
  <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Cheque</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text"  style="border-color:#000000;background-color:#bbbbbb"; value="0" name="cheq" id="cheq"   ></td>
  </th></tr>
  <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Ltd</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text"  style="border-color:#000000;background-color:#bbbbbb"; value="0" name="ltd" id="ltd"   ></td>
  </th></tr>
    <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Mpesa</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text" style="border-color:#000000;background-color:#bbbbbb"; value="0"  name="mpesa"  id="mpes"  /></td>
  </th></tr>
      <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Code</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  autocomplete="off" type="text" style="border-color:#000000;background-color:#bbbbbb"; value="0"  name="code"    /></td>
  </th></tr>
  <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;">Cash Amount</td>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  data-index="2" autocomplete="off" type="text" style="border-color:#000000;background-color:#e8e8e8"; onkeypress="return checkIt(event)"  name="cash"  required="required" onkeyup="bml()" id="cash" onfocus='javascript:this.value=""' /></td>
  </th></tr>
  <tr>
    <td colspan="3" align="right" style="border-color:#000000;background-color:#e8e8e8;"><b>Change</th>
      <td style="border-color:#000000;background-color:#e8e8e8;" width="130"><input  type="text" size="2" style="border-color:#000000;background-color:#bbbbbb";  name="change" id="change" readonly/></td>
  </th> <th style="text-align:right;" style="border-color:#000000;background-color:#e8e8e8;" colspan="4"><input class="active" name="submit" type="submit" value="COMPLETE SALE"
	 style="height: 45px;background-color#4AC948;  width: 120px;
	cursor:pointer;"  /></th></tr> 
	 <br /><br />
	 <th style="text-align:right;" style="border-color:#000000;background-color:#e8e8e8;" colspan="4"><input class="active" name="submitted" type="submit" value="HOLD SALE"
	 style="height: 45px;background-color#4AC948;  width: 130px;
	cursor:pointer;"  /></th>
	  </tr>
<tr>
    </tr>
</table></form>