<?php 

$_POST = help::sanitize($_POST, true);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
 
	if(empty($_POST["email"]) || empty($_POST['password']))
		
		$msg = "Account or Password fields cannot be empty!";
		
	else {
   
		$_POST['email'] = strtolower($_POST['email']);
		$_POST['password'] = md5($_POST['password']);
		
		$sql = "
			SELECT * FROM tbl_users 
			WHERE pwd = '{$_POST['password']}' AND (email = '{$_POST['email']}' OR acctno = '{$_POST['email']}')
		";

        $result = mysqli_query($link, $sql);
		
        if(mysqli_num_rows($result)) {
			
			$row = mysqli_fetch_assoc($result);
			$TOKEN = $link->real_escape_string(help::keygen());
			
			$sql = sQuery::update('tbl_users', array('token' => $TOKEN), "email = '{$row['email']}'");
			$update = $link->query( $sql );
			
			if( $update ) {
				
				$_SESSION['uid'] = $row['id'];
				$_SESSION['token'] = $TOKEN; // Token will cause login from 2 different devices at the same time;
				
				$user_url = help::url( PANEL_DIR );
				
				header("location: {$user_url}/home.php");

			} else $msg = "Login Failed! Please try again";
			
		} else $msg = "Email or Password incorrect!";
	
	}
	
}
