<?php

/*
 * Logowanie się użytkownika
 *
 */

class Main_Core_Controller_Admin_AuthController extends Eppe_Backend_Controller_Action {

	protected $_url = '/Core/admin_index';

	public function init() {
		parent::init();
	}

	protected function _login($username, $pass) {
		$storage = new Eppe_Auth_Storage_Backend();
		Eppe_Auth_Backend::_()->setStorage($storage);

		$auth_adapter = Rtn_RB_Auth_Adapter_Backend::factory()
			->setUsername($username)
			->setPassword($pass);

		$result = Eppe_Auth_Backend::_()->authenticate($auth_adapter);

		if ($result->isValid()) {
			$bean = $result->getIdentity();
			$storage->write($bean);
			return true;
		}
	}

	public function indexAction() {
		if (Eppe_Auth_Backend::_()->hasIdentity())
			$this->_redirect($this->_url);

		$this->_changeLayout('admin/layout_homepage');

		$form = new Core_Form_Admin_Login();
		$this->view->form = $form;
	}

	public function ajaxLoginAction() {

		$this->_disableView();

		$form = new Core_Form_Admin_Login();
		$post = $this->_getPost();

		if (!$form->isValid($post)) {
			$form->populate($post);
			$this->ajaxResponse->data = $form->render();
			$this->ajaxResponse->evalJS = 'new Error("Podaj login i hasło")';
		} else {
			$data = $form->getValues();
			$result = $this->_login($data['email'], $data['password']);

			if ($result) {
				$this->ajaxResponse->evalJS = 'new Success("Logowanie powiodło się. Trwa przekierowanie...");window.location.reload();';
			} else {
				$form->populate($post);
				$this->ajaxResponse->data = $form->render();
				$this->ajaxResponse->evalJS = 'new Error("Podano błędny login lub hasło")';
			}
		}
	}

	public function logoutAction() {
		$this->_logout();
		$this->_addMessage(__('Zostałeś poprawnie wylogowany'));
		$this->_redirect('/Core/admin_auth');
	}

	protected function _logout() {
		$auth = Eppe_Auth_Backend::getInstance();
		$auth->clearIdentity();

		$storage = new Zend_Auth_Storage_Session();
		$storage->clear();
	}

}
