<?php

/**
 * LoginController
 * 
 * @author Luk� Havl��ek
 * @version 1.0
 */

class LostPasswordController extends Zend_Controller_Action {
	
	public function init()
	{
		$this->_helper->layout->disableLayout();
	}

	/**
	 * The default action - show the home page
	 */
	
	public function indexAction()
	{
		if ($this->_request->isPost())
		{
			$login = $this->_request->getPost('login');
			
			if ($login) {
				$table = new Users();
				
				$user = $table->fetchRow($table->select()->where('login LIKE ?', $login));
				if (!$user) $this->view->msg = 'uzivatelske-jmeno-nenalezeno-f';
				else 
				{
					$mailer = new Mailer();
					
					$data = $user->toArray();
					$data['code'] = sha1('sf7' . $user->id_user . 'aghsb' . $user->login . '78' . $user->password . 'g8h98j');
					
					if ($mailer->send('lost-password', $user->email, $data))
					{
						$this->_redirect('lost-password/sent');
					}
						
				}
				
				
			}
		}
		
	}
	
	public function sentAction()
	{
		return;
	}
	
	public function succAction()
	{
		return;
	}
	
	public function changeAction()
	{
		$id = $this->_getParam('id', 0);
		$code = $this->_getParam('code', '');
		
		if (!$id || !$code) $this->view->msg = 'neplatny-kod-pro-zmenu-hesla-f';
		
		
		$table = new Users();
		$row = $table->fetchRow($table->select()->where('id_user = ?', $id));
		
		if (!$row) $this->view->msg = 'neplatny-kod-pro-zmenu-hesla-f';
		
		if ($code == sha1('sf7' . $row->id_user . 'aghsb' . $row->login . '78' . $row->password . 'g8h98j'))
		{
			
			if ($this->_request->isPost())
			{
				$pass = $this->_request->getPost('password');
				$passCheck = $this->_request->getPost('password-check');
				
				if (!$pass) return;
				else {
					$this->view->match = true;
					if ($pass != $passCheck) 
					{
						$this->view->match = false;
					}
					else {
						$where = $table->getAdapter()->quoteInto('id_user = ?', $id);
						$table->update(array('password' => sha1($pass)), $where);
						$this->_redirect('/lost-password/succ');
					}
					
				}
				
			}
			
			
			$this->view->id = $id;
			$this->view->code = $code;
			$this->render();
		} else {
			$this->view->msg = 'neplatny-kod-pro-zmenu-hesla-f';
		}
		
		
	}
	
}
?>