<?php
class User_LoginController extends Zend_Controller_Action {
	/**
	 * reprezetance tabulky uzivatelu
	 * @var Application_Model_Users
	 */
	protected $_tableUsers;
	
	public function init() {
		$this->_tableUsers = new Application_Model_Users();
	}
	
	public function signinHtmlAction() {
		$response = $this->_signIn();
		Zend_Registry::set("response", $response);
		
		//kontrola jeslti prihlaseni bylo uspesne
		if (!$response->success) {
			$this->_forward("index", "index", "default");
			return;
		}
		
		$this->view->response = $response;
	}
	
	public function signinAction() {
		$this->_forward("signin.json");
	}
	
	public function signinJsonAction() {
        	$this->_helper->layout()->disableLayout();
        
		$response = $this->_signIn();
		
		$this->view->response = $response;
	}
	
	/**
	 * pokusi se prihlasit uzivatele
	 * @throws Zend_Exception
	 * @return Library_Response
	 */
	protected function _signIn() {
		$response = new Library_Response();
		
		//kontrola dat
		try {
			//kontrola odeslani prihlasovacich udaju
			if (!isset($_REQUEST["user"]["username"], $_REQUEST["user"]["password"])) {
				//prihlasovaci udaje nejsou kompletni
				$response->setStatus("DATA_NOT_SEND", 400);
				throw new Zend_Exception("Login data is not complete");
			}
			
			$data = $_REQUEST["user"];
			
			//kontrola jeslti jsou data zadana
			if (empty($data["username"]) || empty($data["password"])) {
				//prihlasovaci udaje jsou prazdne
				$response->setStatus("DATA_IS_EMPTY", 400);
				throw new Zend_Exception("Login data is empty");
			}
		} catch (Zend_Exception $e) {
			return $response;
		}
		
		//pokus o prihlaseni
		try {
			/* @var $user Application_Model_Row_User */
			$user = $this->_tableUsers->fetchRow($this->_tableUsers->select(false)
				->where("username like ?", $data["username"]));
			
			//kontorla nalezeni uzivatele
			if (!$user) {
				//uzivatel nebyl nalezen
				$response->setStatus("USER_NOT_FOUND", 404);
				throw new Zend_Exception("User " . $data["username"] . " not found");
			}
			
			//kontrola hesla
			$passwordSHA1 = $user->hashPassword($data["password"]);
			
			if ($passwordSHA1 != $user->password) {
				//hesla nesouhlasi
				$response->setStatus("PASSWORD_INVALID", 403);
				throw new Zend_Exception("User " . $data["username"] . " input invalid password");
			}
		} catch (Zend_Exception $e) {
			return $response;
		}
		
		//vygenerovani cookie a ulozeni zmen
		$user->setCookie()->save();
		
		//zapsani uzivatele do session
		$session = new Zend_Session_Namespace("system");
		$session->user = $user;
		
		//nastaveni odpovedi
		$response->setOk();
		$response["user"] = $user;
		
		//nastavnei cookie
		setcookie("_mlc", $user->cookie, 0, "/");
		
		return $response;
	}
}
?>
