<?php


	
	session_start();
	
	require_once('Ultraviolet.php');
	require_once('Database.php');
	require('FormKey.php');

	$database =& DatabaseConnect::getInstance();
	$database->query("SET CHARACTER SET utf8");
	
	$formkey = new FormKey();
	$formkey_error = 'No error';
	
	$salt = Ultraviolet::get('secret_key');
	
	for($i = 0; $i < count($_POST); $i++):
		${key($_POST)} = $_POST[key($_POST)];
		next($_POST);		
	endfor;
	
	$username = $database->make_safe($username);
	$password = $database->make_safe($password);
	
	if(isset($login) && $login == 'login'):
		
		if(!isset($form_key) || !$formkey->validate()):
			header('location:../login.php?error=Form key error.');
		endif;
		
		if($username == '' or $password == ''):
			header('location:../login.php?error=Da bi ste se prijavili morate popuniti sva polja.<br/>Molimo pokušajte ponovo.');
		else:
			$database->setBareQuery("SELECT count(id) FROM admin_users WHERE user_name = '".$username."'");
			$user_exists = $database->loadResult();
			
			if($user_exists != 1):
				header('location:../login.php?error=Korisničko ime koje ste uneli ne postoji.<br/>Molimo pokušajte ponovo.');
			else:
			
				$encrypted_password = md5($salt.$password.$salt);
				
				$database->setBareQuery("SELECT user_fname, user_lname, user_type, id, user_email FROM admin_users WHERE user_name = '".$username."' AND user_pass = '".$encrypted_password."'");
				$user_fname = $database->loadResultArray(0);
				$user_lname = $database->loadResultArray(1);
				$user_type = $database->loadResultArray(2);
				$user_id = $database->loadResultArray(3);
				$user_email = $database->loadResultArray(4);
				
				if(count($user_fname) > 0):
					$_SESSION['admin_username'] = $username;
					$_SESSION['admin_fname'] = $user_fname[0];
					$_SESSION['admin_lname'] = $user_lname[0];
					$_SESSION['admin_type'] = $user_type[0];
					$_SESSION['admin_id'] = $user_id[0];
					$_SESSION['admin_email'] = $user_email[0];
					
					setcookie('username', $username, time()+60*60*24*365, '/');
            		setcookie('password', $encrypted_password, time()+60*60*24*365, '/');//, 'www.popular.rs');

					
					header('location:../admin.php');
				else:
					header('location:../login.php?error=Lozinka koju ste uneli je pogrešna.<br/>Molimo pokušajte ponovo.');
				endif;
				
			endif;
		endif;
		
	elseif($_GET['login'] == 'logout'):
		session_unset();
		session_destroy();
		header('location:../login.php');
	else:
		die('Error');
	endif;
?>