<?php

	date_default_timezone_set('America/Sao_Paulo');

	require('libs/db.php');
	require('libs/Session.class.php');
	require('libs/System.class.php');
	require('libs/DBQuery.class.php');

	$db = new DBQuery;
	$system = new System;
	$session = new Session; 

	if($session->get('auth') == "true") header("Location: /sistema/");

	if($_POST['entrar']) {

		$login = $_POST['login'];
		$senha = $_POST['pass'];

		$admins = $db->query("SELECT id, nomeUser AS nome, login, senha, nivelUser AS nivel FROM usuarios WHERE login = ?", $login);
		
		if($admins->rowCount() > 0) {

			$admins = $admins->fetchAll(PDO::FETCH_ASSOC);
			
			$user = null;

			foreach($admins as $admin) {
				if(sha1($senha) == $admin['senha']) {
					$user = $admin;
					break;
				}
			}

			if($user != null) {
				$session->set('idUser', $user['id']);
				$session->set('nome', $user['nome']);
				$session->set('nivel', $user['nivel']);
				$session->set('auth', "true");
				header('Location: /sistema/');
			} else {
				$error_message = 'Senha incorreta!';
			}

		} else {
			$error_message = "Usuário não encontrado";
		}
	}

	// Logo
	$image = @$system->getOption('logoEmpresa');
	if(isset($image) && $image != ''){
		$image = '/sistema/statics/admin/' . $image;
	}else{
		$image = 'http://ambcom.com.br/web/images/logo.png';
	}

?>

<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta charset="utf-8" />
		<title>Entrar</title>
		<link rel="stylesheet" type="text/css" href="css/normalize.css" />
		<link rel="stylesheet" type="text/css" href="css/login.css?v=2.0" />
	</head>
	<body>
		<?php
			if(isset($error_message)){
				echo '<p class="error-message">' . $error_message . '</p>';
			}
		?>
		<div class="login-align">
			<div class="login">
				<img src="<?php echo $image; ?>" class="logo" alt="Sistema Administrativo" />
				<form method="post" action="login.php">
					<input type="text" placeholder="Nome de Usuário" name="login" />
					<input type="password" placeholder="Senha" name="pass" />
					<input type="submit" value="Entrar" name="entrar" />
				</form>
			</div>
			<span>&copy; <?=date('Y')?> - Equipe de desenvolvimento Ambiente Comunicação.</span>
		</div>
	</body>
</html>
