<?php session_start();
			if (isset($_SESSION['logged']) && $_SESSION['logged'] == 'yes') {
			$user = $_SESSION['user'];
			include ('../scripts/classes.php'); if ($_SESSION['lang']=="EN"){include ('../lang/en.php'); }elseif ($_SESSION['lang']=="GR"){include ('../lang/gr.php');}else {include ('../lang/en.php');}

            if ($_SERVER['REQUEST_METHOD'] != 'GET') exit;
            //foreach($_POST as $key => $value) $_POST[$key] = urldecode(trim($value));
            $trans_id = mysqli_real_escape_string($mysqli, $_GET['trans_id']);
            $creds = mysqli_real_escape_string($mysqli, $_GET['creds']);
            $tot_amount = mysqli_real_escape_string($mysqli, $_GET['tot_amount']);
	
	//Transaction records Match Query
	$match = "SELECT customer_id, barcode_id, created_on FROM cls_transactions WHERE transaction_id='$trans_id' LIMIT 1";
	$result = mysqli_query($mysqli, $match) or die("Query failed : " . mysqli_error($mysqli));
	
	if (mysqli_num_rows($result) == 0){
		$errors[]= "No customer found!";
		$str = implode("\n", $errors);
		die("Search error:\n\n" . $str);
	}else {	
		$cus = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$cust_to_update = $cus['customer_id'];	
		$barcode = $cus['barcode_id'];	
		$time= $cus['created_on'];
		
		//Check if same customer has new transaction since last 
		$last_sql = "SELECT created_on, transaction_id, created_by, barcode_id FROM cls_transactions WHERE barcode_id='$barcode' AND created_on >'$time' LIMIT 1 ";				
		$last_result = mysqli_query($mysqli, $last_sql) or die("Query failed : " . mysqli_error($mysqli));
			if (mysqli_num_rows($last_result) == 0){
				$time_last = '1753-01-01 00:00:00';
			}else{
				$tim = mysqli_fetch_array($last_result, MYSQLI_ASSOC);
				$time_last = $tim['created_on'];
				$cust = $tim['barcode_id'];
				$by = $tim['created_by'];
				$trans = $tim['transaction_id'];
			}
			//echo $time_last."<br />";
			//echo $time;
			if (strtotime($time) > strtotime($time_last)){
			//echo "yes";
				mysqli_query($mysqli, "SET NAMES 'utf8'" ); 
				//check for field values
				mysqli_query ($mysqli, "DELETE FROM cls_transactions WHERE transaction_id='$trans_id'") or die(mysqli_error($mysqli));
				
				//Get last transaction date after deletion
				$sql_find_last = "SELECT IFNULL(MAX(created_on),0) AS last FROM cls_transactions a
				INNER JOIN cls_customers b on a.customer_id = b.id  
				WHERE 
				a.customer_id='$cust_to_update' AND ISNULL(is_reversed) AND ISNULL(reversal) 
				OR 
				a.customer_id='$cust_to_update' AND is_reversed='1' AND reversal='1' AND b.score>0 ";
				$result_find_last = mysqli_query($mysqli, $sql_find_last) or die(mysqli_error($mysqli));
				$det = mysqli_fetch_assoc($result_find_last);
				$last = $det['last'];		
				
				//update customer credits and amount
				if ($creds >= 0){
					mysqli_query ($mysqli, "UPDATE cls_customers SET turnover=turnover - '$tot_amount', credits= credits -'$creds', score = score - '$creds', last_transaction_date='$last' WHERE id='$cust_to_update'") or die("Failed to update cust balance ". mysqli_error($mysqli));				
				}elseif ($creds < 0){
					mysqli_query ($mysqli, "UPDATE cls_customers SET redeem_amount=redeem_amount - '$tot_amount', credits= credits -'$creds', last_transaction_date='$last' WHERE id='$cust_to_update'") or die("Failed to update cust balance ". mysqli_error($mysqli));		 
				}
				//update transactions log (user's last transaction)
					mysqli_query ($mysqli, "UPDATE users SET params='$lbl_last_trans_deleted' WHERE username='$user'") or die("Failed to update transaction log ". mysqli_error($mysqli));
				//Update roufianos.log
				$filename = "../logs/roufianos.log";
				$content = stripslashes("\r\n".date("d-m-Y H:i:s")." USER #$user# DELETED Transaction $trans_id #CUST $cust_to_update #AMOUNT:$tot_amount"); 
				$fp = fopen($filename,"a") or die ("Error opening file in write mode!");
				fputs($fp,$content);
				fclose($fp) or die ("Error closing log file!");
				//end of updating roufianos.log		
				?>
				<script type="text/javascript">window.location = "idle.php"</script>
				<?php }else{
			?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title ?></title>
<link rel="shortcut icon" href="../img/favicon.png" />
<link href="../cms1.css" rel="stylesheet" type="text/css" />

</head>
<body>
<div class="critical" style="margin-top:20px; width:97%">
	<ul>
		<li>
        <?php echo _YOU_CANNOT_DELETE_THIS_TRANSACTION_1." ".$cust." "._YOU_CANNOT_DELETE_THIS_TRANSACTION_2." ".$by.": <strong>".$time_last." </strong>(".$trans.")"; ?>
		</li>
	</ul>
</div>		
<div class="align-center">
		<input type="button" value="<?php echo $lbl_back; ?>" onclick="window.history.go(-1)" class="button" />
</div>
<?php }	
		mysqli_close($mysqli); 
}	
} else {
    header('Location: login.php');
}
?>