<?php

/**
 * DocumentsController - app core
 * 
 * @author Lukáš Havlíček
 * @version 1.0
 */

class AccountController extends Zend_Controller_Action 
{ 	
	public function init()
	{
		$this->view->topmenu = 8;
	}
	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
    	$user = Zend_Registry::get('user');
		$users = new Users;
		
		$msg = $this->_getParam('msg', 0);
		$this->view->msg = $msg;
		
		$item = $users->fetchRow($users->select()->where('id_user = ?', $user->id_user));
		if (!$item) $this->_redirect('/');
		
		$this->view->item = $item;
		
		if ($this->_request->isPost())	{
			$values = $this->_request->getPost();			
			
			$pass = true;
			$errors = array();
				

			if ($values['user_firstname'] == "")
			{
				$pass = false;
				$errors['jmeno-f'] = 'isEmpty';	
			} else {
				$data['user_firstname'] = $item->user_firstname;
			}
			
			if ($values['user_surname'] == "")
			{
				$pass = false;
				$errors['prijmeni-f'] = 'isEmpty';	
			} else {
				$data['user_surname'] = $item->user_surname;
			}
			
			if ($values['email'] == "")
			{
				$pass = false;
				$errors['e-mail-f'] = 'isEmpty';	
			} else
			{
				if ($values['email'] != $item->email)
				{
					$row = $users->fetchRow($users->select()->where('email LIKE ?', $values['email']));
					if ($row) {
						$pass = false;
        				$errors['e-mail-f'] = 'emailUsed';
        			}
				}
				else
				{
					$data['email'] = $item->email;
				}
        		
			}
			
        	if ($values['password'] !== $values['password_check'] && $values['password'] != "") {
				$pass = false;
        		$errors['heslo-f'] = 'passwordsNotMatch';
       		} elseif ($values['password'] != "") {
       			$data['password'] = sha1($values['password']);
       		}
        	
       		
       		if (!$pass) {
       			
       			if (!isset($values['send_mail'])) $values['send_mail'] = 0;
       			
       			$this->view->item = $users->createRow($values);
       			$this->view->errors = $errors;
       			return;
       			
       			
       		} else {
        		
       			$data['week_start'] = $values['week_start'];
        		$data['send_mail'] = $values['send_mail'] ? 1 : 0;
        		$data['lang'] = ($values['lang'] == 'cs' || $values['lang'] == 'en') ? $values['lang'] : 'cs';
       			if ($users->update($data, 'id_user = ' . $user->id_user)) {
       				
       				$language = new Zend_Session_Namespace('language');
       				unset($language->lang);
       				
        			$this->_redirect('account/index/msg/1');
        		} else {
        			$this->_redirect('account/index/msg/2');
        		}
        			
				return;        			
    		}	
		}		
    }
}