<?php

	//Security
	if( ! defined( 'IS_INIT' ) )
	{
		die( 'Unauthorized Access');
	}
	
class User
{
	private $Handler;
	public $UserOptions;
	
	public function __construct()
	{
		global $Handler;
		
		$this->Handler = $Handler;
	}
	
	public function Authenticate( $user , $pass )
	{
		//0 = Not found
		//1 = Ok
		//2 = Banned
		$pass = md5( $pass . SALT );
		$do = sqlsrv_prepare( $this->Handler->database->conn , "Select bIsBlock from Account.dbo.tUser where sUserID = ? and sUserPW = ? and bIsDelete = 'false'" , array( &$user , &$pass ) );
		sqlsrv_execute( $do );
		if( sqlsrv_has_rows( $do ) == true )
		{
			$ret = sqlsrv_fetch_array( $do , SQLSRV_FETCH_ASSOC );
			if( $ret['bIsBlock'] == 0 )
			{
				sqlsrv_free_stmt( $do );
				return 1;
			}
			elseif( $ret['bIsBlock'] == 1)
			{
				sqlsrv_free_stmt( $do );
				return 2;
			}
		}
		else
		{
			return 0;
		}
	}
	
	public function FetchInfo( $user , $pass )
	{
		$check = sqlsrv_prepare( $this->Handler->database->conn , "Select nUserNo from Account.dbo.tUser where sUserID = ? and sUserPW = ?" , array( &$user , &$pass) );
		sqlsrv_execute( $check );
		if( sqlsrv_has_rows( $check ) == false )
		{
			session_destroy();
			header( 'Location:' . MAIN_URL );
		}
		else
		{
			$sql = 'SELECT *
			FROM Account.dbo.tUser 
			INNER JOIN Account.dbo.tUserOption
			ON Account.dbo.tUser.sUserID = ? and Account.dbo.tUserOption.nUserNo=Account.dbo.tUser.nUserNo
			';
			$do = sqlsrv_prepare( $this->Handler->database->conn,  $sql , array( &$user ) );
			sqlsrv_execute( $do );
			if( sqlsrv_has_rows( $do ) == true )
			{
				$this->UserOptions = sqlsrv_fetch_array( $do , SQLSRV_FETCH_ASSOC );
				$cash = sqlsrv_prepare( $this->Handler->database->conn , "Select cash from Account.dbo.tCash where userNo = ? and cashtype = 1 and status = 'true' " , array( &$this->UserOptions['nUserNo'] ) );
				sqlsrv_execute( $cash );
				$this->UserOptions = array_merge( sqlsrv_fetch_array( $cash , SQLSRV_FETCH_ASSOC ) , $this->UserOptions );
			}
			else
			{
				die( 'Failed to get account information. Please contact a staff member.');
			}
		}
	}
	
	public function BuyItem( $id )
	{
		if( preg_match( '/[^0-9]/' , $id ) == 0 )
		{
			$checkExists = sqlsrv_prepare( $this->Handler->database->conn , "Select * from Account.dbo.tMallItems where itemid = ?" , array( &$id ) );
			sqlsrv_execute( $checkExists );
			if( sqlsrv_has_rows( $checkExists ) == true )
			{
				$row = sqlsrv_fetch_array( $checkExists , SQLSRV_FETCH_ASSOC );
				if( $row['price'] <= $this->UserOptions['cash'] )
				{
					$this->AddItem( $row['itemid'] , $row['price'] , $row['pieces'] );
					$this->SubPoints( $row['price'] );
                                        $this->Handler->WriteLog( 'Buy Item' , 'Success' , " Item - {$row['itemid']}" , "Points - {$row['price']}" );
					$this->Handler->theme->SetValue( 'MESSAGE' , $this->Handler->theme->GetValue( 'SUCCESS_BUY' ) );
					$this->Handler->theme->SetValue( 'GO_BACK' , $this->Handler->theme->GetValue( 'GO_REFRESH' ) );
					$this->Handler->theme->SetValue( 'RED_URL' , MAIN_URL . "?view=cp&do=mall" );
					$this->Handler->theme->Parse( 'success.html' );
				}
				else
				{
                                    $this->Handler->WriteLog( 'Buy Item' , 'Failed' , " Item - {$row['itemid']}" , "Points - {$row['price']}" , "Not Enough Coins" );
					$this->Handler->theme->SetValue( 'ERROR' , $this->Handler->theme->GetValue( 'ERR_MONEY' ) );
					$this->Handler->theme->SetValue( 'GO_BACK' , $this->Handler->theme->GetValue( 'GO_REFRESH' ) );
					$this->Handler->theme->SetValue( 'RED_URL' , MAIN_URL . "?view=cp&do=mall" );
					$this->Handler->theme->Parse( 'error.html' );
					exit;
				}
			}
			else
			{
                            $this->Handler->WriteLog( 'Buy Item' , 'Failed' ,  "Invalid Item" , "$id" );
				$this->Handler->theme->SetValue( 'ERROR' , $this->Handler->theme->GetValue( 'ERR_INVALID_ITEM' ) );
				$this->Handler->theme->SetValue( 'GO_BACK' , $this->Handler->theme->GetValue( 'GO_REFRESH' ) );
				$this->Handler->theme->SetValue( 'RED_URL' , MAIN_URL . "?view=cp&do=mall" );
				$this->Handler->theme->Parse( 'error.html' );
			}
		}
		else
		{
                    $this->Handler->WriteLog( 'Buy Item' , 'Failed' , "Hack Attempt - Regex Failed" , "$id" );
			$this->Handler->theme->SetValue( 'ERROR' , $this->Handler->theme->GetValue( 'ERR_INVALID_ITEM' ) );
			$this->Handler->theme->SetValue( 'GO_BACK' , $this->Handler->theme->GetValue( 'GO_REFRESH' ) );
			$this->Handler->theme->SetValue( 'RED_URL' , MAIN_URL . "?view=cp&do=mall" );
			$this->Handler->theme->Parse( 'error.html' );
		}
	}
	
	public function SubPoints( $amount , $user = null )
	{
		if( $user == null)
		{
			$user =  $this->UserOptions['nUserNo'];
		}
		$do = sqlsrv_prepare( $this->Handler->database->conn , "UPDATE Account.dbo.tCash set cash = cash - ? where userno = ?", array( &$amount , &$user ) );
		sqlsrv_execute( $do );
		
		$log = sqlsrv_prepare( $this->Handler->database->conn , "Insert into Account.dbo.tCashLog ([userNo] , [logType] , [cashType] , [cash] , [reference] ) VALUES ( ? , 1 , 1 , ? , 'subtract' );" , array( &$user , &$amount ) );
		sqlsrv_execute( $log );
	}
	
	public function AddItem( $item , $price , $amount , $user = null )
	{
		if( $user == null )
		{
			$user = $this->UserOptions['nUserNo'];
		}
		
		$uniqid = md5( time() . rand( 9156156156 , 9156498415 ) );
		$uniqid .= rand( 92302321 , 9315361561 );
		$uniqid .= time();
		
		$stmt = "INSERT INTO [Account].[dbo].[tOrder]
           ([orderDate]
           ,[orderType]
           ,[userNo]
           ,[toUserNo]
           ,[goodsNo]
           ,[goodsPrice]
           ,[amount]
           ,[discount]
           ,[orderPrice]
           ,[cashType]
           ,[isPay]
           ,[userIP]
           ,[uniqID])
     VALUES
           (CURRENT_TIMESTAMP
           ,1
           ,?
           ,0
           ,?
           ,?
           ,1
           ,0
           ,0
           ,1
           ,'true'
           ,?
		   ,?);";
		
		$do = sqlsrv_prepare( $this->Handler->database->conn , $stmt , array( &$user , &$item ,  &$price , &$_SERVER['REMOTE_ADDR'] , &$uniqid ) );
		sqlsrv_execute( $do );
		
		$getorder = sqlsrv_prepare( $this->Handler->database->conn , "Select * from Account.dbo.tOrder where uniqid = ? " , array( &$uniqid ) );
		sqlsrv_execute( $getorder );
		$ret = sqlsrv_fetch_array( $getorder , SQLSRV_FETCH_ASSOC );
		
		$insertitem = sqlsrv_prepare( $this->Handler->database->conn , "Insert into Account.dbo.tChargeItem ([userNo] , [orderNo] , [goodsNo] ) values ( ? , ? ,  ? )" , array( &$user , &$ret['orderNo'] , &$ret['goodsNo'] ) );
		sqlsrv_execute( $insertitem );
	}
	
	public function CheckPWCorrect( $user , $pass )
	{
		$pass = md5( $pass . 'f1we564w56' );
		$do = sqlsrv_prepare( $this->Handler->database->conn , "Select bIsBlock from Account.dbo.tUser where sUserID = ? and sUserPW = ? and bIsDelete = 'false'" , array( &$user , &$pass ) );
		sqlsrv_execute( $do );
		if( sqlsrv_has_rows( $do ) == true )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function UpdatePass( $pass , $user = null )
	{
		if( $user == null )
		{
			$do = sqlsrv_prepare( $this->Handler->database->conn , "Update Account.dbo.tUser SET sUserPW = ? where nUserNo = ?" , array( &$pass , &$this->UserOptions['nUserNo'] ) );
			sqlsrv_execute( $do );
			$_SESSION['PassWord'] = $pass;
		}
		else
		{
			
		}
	}
        
        public function HasEnoughCoins( $amount )
        {
            if( $this->UserOptions['cash'] >= $amount )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
}

?>