<?php

$email = $password= "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 
	$_POST = help::sanitize($_POST, true);
	
	## Check Email
	if (!empty($_POST["email"])) {
		$email = $_POST["email"];
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $email_err = "Invalid email format"; 
	}
  
	## Check Password
	if (!empty($_POST["password"])) $password = md5($_POST["password"]);
	
	## Then:
	if(empty($email) || empty($password))
		
		$msg = "Email or Password fields cannot be empty!";
		
	else {
				
		$sql = "SELECT * FROM admin WHERE email='$email'  AND password='$password'";
		$result = $link->query($sql);
		
		if(mysqli_num_rows($result)) {
			
			$row = mysqli_fetch_assoc($result);
			$TOKEN = $link->real_escape_string(help::keygen());
			
			$SQL = sQuery::update( "admin", array( "token" => $TOKEN ), "email='{$email}'" );
			$updated = $link->query( $SQL );
			
			if( $updated ) {
				
				$_SESSION['_admin'] = array(
					'email' => $row['email'],
					'token' => $TOKEN,
					'uid' => $row['id']
				);

				header("location: " . help::url( PANEL_DIR ) . "/home.php"); 
			
			} else $msg = 'The login process failed';

		} else $msg = "Email or Password incorrect!";
		
	}
	
}
	

