<?php
session_start();
require("data\_dbconfig.php");
include('data\_functions.php');
	
		if ($_GET['action'] == 'register')
		{
			
			$_SESSION['sessionerror'] = '';
			$selected = mssql_select_db('Account', $mssqlhandle) or die ("Couldn't open database Account"); 
  
			$errors = array();
			if(preg_match("/^[0-9a-zA-Z]{3,15}$/i", $_POST[newuser])){
			$strSql="select * from tUser where sUserID='$_POST[newuser]'";
			$result = mssql_query($strSql) or die ('A error occured:');
			
			$Count = mssql_num_rows($result);
			if ($Count > 0)  $errors[] = "This Accountname already exists, please choose another one.";
			}
			if(!preg_match("/^[0-9a-zA-Z]{3,15}$/i", $_POST[newuser])) $errors[]="You are only alowed to use uppper and lower cases in English in your username.";
			if(strlen($_POST[newuser])<3) $errors[] = "The length of your username can't be less than 3 characters";
			if(strlen($_POST[newuser])>15) $errors[]= "The length of your username can't be more than 15 characters";
			if(!preg_match("/^[0-9a-zA-Z]{3,15}$/i", $_POST[newpass])) $errors[]="You can only use English Characters of Upper case and lower case in your password.";
			if($_POST[newuser]==$_POST[newpass]) $errors[]= "Accountname and password can't be the same!";
			if(strlen($_POST[newpass])<3) $errors[] = "The length of the password can't be less than 3 characters";
			if(strlen($_POST[newpass])>15) $errors[] = "The length of the password can't be more than 15 characters";
			if($_POST[newpass2]!=$_POST[newpass]) $errors[] = "Password does not match";
			if(checkmail($_POST[newmail])==0) $errors[] = "E-mail address wrong";

			if (($_SESSION["captcha_code"] !=0) AND ($_POST["captcha"] == $_SESSION["captcha_code"])) 
			{
				echo "";
			} else {
				$errors[] = "Captcha wrong.";
			}

			// Session löschen
			unset($_SESSION['captcha_code']);
			
			if(sizeof($errors)>0){
				$errorStr .= "<b>You have the following error(s):</b>";
					foreach($errors as $error)
						$errorStr .= "<li>$error</li>";
					} else {
						$errorStr = "<center><strong>Successfully registered</strong></center>";
						$userid= mysql_real_escape_string($_POST[newuser]);
						$passwd_user=mysql_real_escape_string($_POST[newpass]);
						$usermail = mysql_real_escape_string($_POST[newmail]);
						$regquerymysql = "INSERT INTO global_users (id, gameuser, gamepassword, gamemail, gamecash, banned) VALUES ('', '$userid', '$passwd_user', '$usermail', '0', '0')";
						$regquery = "INSERT INTO tUser (sUserID, sUserPW, sUserName) VALUES ('$userid', '$passwd_user', '$userid')";
						mssql_query($regquery);
						mysql_query($regquerymysql);
					}
			
			$_SESSION['sessionerror'] = "<table width='80%' border='0' align='center' cellpadding='0' cellspacing='0'>
											<tr>
												<td>".$errorStr."</td>
											</tr>
										</table>";
					
			
			header ("Location: index.php?show=register");
			
			
		}
		
		if ($_GET['action'] == 'login')
		{
			$selected = mssql_select_db('Account', $mssqlhandle) or die ("Couldn't open database Account"); 
			$loginusername = mysql_real_escape_string($_POST['loginname']);
			$loginpassword = mysql_real_escape_string($_POST['loginpass']);
			$get_user = mssql_query("SELECT * FROM tUser WHERE (sUserID = '".$loginusername."') AND (sUserPW = '".$loginpassword."')");
			
			$row_user = mssql_fetch_array($get_user);
				if (mssql_num_rows($get_user) > 0)
					{
						
  						$datenrichtig = true;
						$_SESSION['username'] = $row_user["sUserID"];
  						$_SESSION['userpass'] = $row_user["sUserPW"];
      					$_SESSION['last_besuch'] = time();
  						$_SESSION['user_eingeloggt'] = true;
						$_SESSION['level'] = $row_user['nAuthID'];
						$_SESSION['since'] = $row_user["dDate"];
						$_SESSION['userno'] = $row_user["nUserNo"];
						
					}
                    else
                    {
						$datenrichtig = false;
  						$_SESSION['user_eingeloggt'] = false;
					}

				if ($datenrichtig == true)
					{	
						setcookie("username", "".$_SESSION['username']."", time()+(3600*24*365));
						setcookie("userpass", "".$_SESSION['userpass']."", time()+(3600*24*365));
						header ("Location: index.php?show=".$_GET['site']."");
						
					}
        			else
       				{
						$_SESSION['sessionerror'] = "User not Found!!!";
						header ("Location: index.php?show=error");
					}

		}
		
		if ($_GET['action'] == 'logout')
		{
			$_SESSION = array();
			setcookie("username","",0);
			setcookie("userpass","",0);
			setcookie("last_besuch","",0);
			setcookie("level","",0);
			header ("Location: index.php?show=".$_GET['site']."");
		}
		if ($_GET['action'] == 'getitem')
		{
			$get_money = mysql_query("SELECT gamecash, banned FROM global_users WHERE gameuser = '".$_SESSION['username']."' LIMIT 1");
			$row_money = mysql_fetch_array($get_money);
			$aktmoney = $row_money['gamecash'];
			$newcash = $aktmoney-$_POST['needcash'];
			if ($row_money['banned'] > 0)
				{
					$_SESSION['sessionerror'] = "You are banned from Cashshop!!!";
					header ("Location: index.php?show=error");
				} else {
			
				
				$how_often= mysql_query("SELECT price, isSell, howoften FROM global_shop WHERE itemid = '".$_POST['buyitemid']."' LIMIT 1");
				$buycount = mysql_fetch_array($how_often);
				$newbuycount = $buycount['howoften']+1;
	
				/*
				echo "itemid ".$_POST['buyitemid']."<br>";
				echo "cost ".$_POST['needcash']."<br>";
				echo "have money ".$aktmoney."<br>";
				echo "User ".$_SESSION['username']."<br>";
				echo "userNo ".$_SESSION['userno']."<br>";
				echo "new cash ".$newcash."<br>";
				echo "oldcount ".$buycount['howoften']."<br>";
				echo "newcount ".$newbuycount."<br>";
				echo "userNo ".$_POST['returnid']."<br>";
				*/
				
				if ($aktmoney < $buycount['price'])
				{
						$_SESSION['sessionerror'] = "Not enough cash available!!!";
						header ("Location: index.php?show=error");
				} else {
				
				if ($buycount['isSell'] == 0)
				{
						$_SESSION['sessionerror'] = "Item not available!!!";
						header ("Location: index.php?show=error");
				} else {
				
				$selected = mssql_select_db('Account', $mssqlhandle) or die ("Couldn't open database Account"); 
				$itemquery = "INSERT INTO tChargeItem (userNo, orderNo, goodsNo) VALUES ('".$_SESSION['userno']."', '".$newbuycount."', '".$_POST['buyitemid']."')";
				$writeindb = mysql_query("UPDATE global_shop SET howoften = '".$newbuycount."' WHERE itemid = '".$_POST['buyitemid']."'");
				$insertItem = mssql_query($itemquery);
				$writecash = mysql_query("UPDATE global_users SET gamecash = '".$newcash."' WHERE gameuser = '".$_SESSION['username']."' LIMIT 1");
				
				if ($insertItem && $writecash)
					{
						header ("Location: index.php?show=cashshop&catID=".$_POST['returnid']."&action=success");
					} else {
						$_SESSION['sessionerror'] = "Database Error!!!";
						header ("Location: index.php?show=error");
					}
				}
			}
				
			}	
				
		}
		if($_GET['action'] == 'editpassword')
 		{
			$selected = mssql_select_db('Account', $mssqlhandle) or die ("Couldn't open database Account"); 

  
			$errors = array();
			
			$strSql="select * from tUser where sUserID='$_POST[edituser]' AND sUserPW='$_POST[oldpass]'";
			$result = mssql_query($strSql) or die ('A error occured:');
			$Count = mssql_num_rows($result);
			if ($Count < 1)  $errors[] = "Old Password is wrong or Account not Found.";
			if ($_POST['newpass1'] == '') $errors[]= "no Password given.";
			if ($_POST['newpass1'] <> $_POST['newpass2']) $errors[]= "Passwords do not match.";
			
			if(sizeof($errors)>0){
				$errorStr .= "<b>You have the following error(s):</b>";
					foreach($errors as $error)
						$errorStr .= "<li>$error</li>";
					} else {
						$errorStr = "<center><strong>Password Successfully changed. pls Relog!!!</strong></center>";
						
						$writeindb = mysql_query("UPDATE global_users SET gamepassword = '".$_POST['newpass1']."' WHERE gameuser = '".$_SESSION["username"]."'");
						$writeindb2 = mssql_query("UPDATE tUser SET sUserPW = '".$_POST['newpass1']."' WHERE sUserID = '".$_SESSION["username"]."'");	
					}
			
			$_SESSION['sessionerror'] = "<table width='80%' border='0' align='center' cellpadding='0' cellspacing='0'>
											<tr>
												<td>".$errorStr."</td>
											</tr>
										</table>";
					

			header ("Location: index.php?show=error");
			
 		}
		if($_GET['action'] == 'editmail')
 		{
			$strSql="select * from global_users where gameuser='$_POST[edituser]' AND gamemail='$_POST[oldmail]'";
			$result = mysql_query($strSql) or die ('A error occured:');
			$Count = mysql_num_rows($result);
			if ($Count < 1)  $errors[] = "Old E-Mail not found.";
			if ($_POST['newmail'] == '') $errors[]= "no New E-Mail given.";
			
			if(sizeof($errors)>0){
				$errorStr .= "<b>You have the following error(s):</b>";
					foreach($errors as $error)
						$errorStr .= "<li>$error</li>";
					} else {
						$errorStr = "<center><strong>E-Mai Successfully changed.</strong></center>";
						
						$writeindb = mysql_query("UPDATE global_users SET gamemail= '".$_POST['newmail']."' WHERE gameuser = '".$_SESSION["username"]."'");
					}
			
			$_SESSION['sessionerror'] = "<table width='80%' border='0' align='center' cellpadding='0' cellspacing='0'>
											<tr>
												<td>".$errorStr."</td>
											</tr>
										</table>";
					

			header ("Location: index.php?show=editprofile");			
		}
		
		if($_GET['action'] == 'requestpassword')
 		{
				
				$strSql="select * from global_users where gamemail='$_POST[requestmail]'";
				$result = mysql_query($strSql) or die ('A error occured:');
				$Count = mysql_num_rows($result);
				if ($Count < 1)  $errors[] = "E-Mail not found!!";
				if ($_POST['requestmail'] == '') $errors[]= "E-Mail not found!!";
				$mailcount = mysql_fetch_array($result);
				if(sizeof($errors)>0){
				$errorStr .= "<b>You have the following error(s):</b>";
					foreach($errors as $error)
						$errorStr .= "<li>$error</li>";
					} else {
						$errorStr = "<center><strong>Password successfully requested. Please Check your E-Mails!!!</strong></center>";
						
						$sender = "request@isya-online.de";
						$empfaenger = $mailcount['gamemail'];
						$betreff = "Password Request from Isya Online";
						$mailtext = "Hi !\nYour requested Password is: ".$mailcount['gamepassword']."";
						mail($empfaenger, $betreff, $mailtext, "From: $sender "); 
					}
				
				$_SESSION['sessionerror'] = "<table width='80%' border='0' align='center' cellpadding='0' cellspacing='0'>
											<tr>
												<td>".$errorStr."</td>
											</tr>
										</table>";
				header ("Location: index.php?show=forgotPW");
				
		}		
				
				
?>		