<?PHP

class ManagerAdmin extends Buyers
{
	public function fetch()
	{
		//передаём все существующие классы в шаблон
		$this->design->assign('perms', $this->managers->permissions_list);

		if($this->request->method('post'))
		{
			$status = "updated";
			$manager = new stdClass();
			$old_login = $this->request->post('old_login');
			$manager->login = $this->request->post('login');

			if(empty($manager->login))
			{
				$this->design->assign('message_error', 'empty_login');
			}
			elseif($this->managers->get_manager($manager->login) && $manager->login != $old_login)
			{
	  			$manager->login = $old_login;
	  			$manager->permissions = (array)$this->request->post('permissions');
	  			$this->design->assign('message_error', 'login_exists');
			}
			else
			{
				$password = $this->request->post('password');
				if(!empty($password))
					$manager->passhash = password_hash($password, PASSWORD_BCRYPT);

				// Обновляем права только другим менеджерам
				$current_manager = $this->managers->manager;

				if($old_login != $current_manager->login)
					$manager->permissions = (array)$this->request->post('permissions');

				if(empty($old_login))
				{
					$manager->login = $this->managers->add_manager($manager);
	  				$status = "added";
	  			}
		    	else
				{
					$this->managers->update_manager($old_login, $manager);
					$status = "updated";
				}
				$manager = $this->managers->get_manager($manager->login);
                $this->request->redirect(array('login'=>$manager->login,'module'=>'ManagerAdmin','message_success'=>$status,'return'=>$this->request->get('return')));
	    	}
		}
		else
		{
			$login = $this->request->get('login');
			if(!empty($login))
				$manager = $this->managers->get_manager($login);
		}

		if(!empty($manager))
			$this->design->assign('m', $manager);

 	  	return $this->design->fetch('manager.tpl');
	}

}
