<?php
class Managers extends Buyers
{
    public $manager;
    public $permissions_list = array(
        'pages'      => 'Разделы',
        'banners'    => 'Баннеры',
        'comments'   => 'Комментарии',
        'feedbacks'  => 'Заявки',
        'design'     => 'Дизайн',
        'backup'     => 'Бекап',
        'blog'       => 'Блог',
        'settings'   => 'Настройки',
        'managers'   => 'Администраторы',
        'license'    =>'Лицензия'
    );

    //функция для генерации нового пароля
    //функция для генерации нового пароля
	public function generate_password()
	{
        $length = 12;
        $chars = '1234567890ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz!-~*()_=';
        $max = strlen($chars) - 1;
        $password = '';

        for($i = 0; $i < $length; $i++)
            $password .= $chars[random_int(0, $max)];

        return $password;
	}

    public function get_managers($filter = array())
    {
        $query = $this->db->placehold("SELECT * FROM managers");
        $this->db->query($query);
        $tmp = $this->db->results();
        foreach($tmp as $m)
        {
            $manager = new stdClass();
            $manager->login = $m->login;
            $permissions = empty($m->permissions) ? array_flip($this->permissions_list) : explode(",", $m->permissions);
            //пишем название в массив
            foreach($permissions AS $permission){
                $permission_name = $this->permissions_list[$permission];
                $manager->permissions[$permission_name] = $permission;
            }
            $managers[] = $manager;
        }
        return $managers;
    }

    public function count_managers($filter = array())
    {
        return count($this->get_managers());
    }

    public function get_manager($login)
    {
        if(!empty($login))
        {
            $this->db->query("SELECT * FROM managers WHERE login = ?", $login);
            if($manager = $this->db->result())
            {
                $manager->permissions = empty($manager->permissions) ? array_keys($this->permissions_list) : explode(",", $manager->permissions);
                return $manager;
            }
        }
        return false;
    }

    public function add_manager($manager)
    {
        $manager->permissions = implode(",", $manager->permissions);
        $query = $this->db->placehold("INSERT INTO managers SET ?%", $manager);
        $this->db->query($query);
        return $this->db->insert_id() > 0 ? $manager->login : false;
    }

    public function update_manager($login, $manager)
    {
        if(!empty($manager->password))
            $manager->passhash = password_hash($manager->password, PASSWORD_BCRYPT);

        if(!empty($manager->permissions))
            $manager->permissions = implode(",", $manager->permissions);

        $this->db->query("UPDATE managers SET ?% WHERE login = ? LIMIT 1", $manager, $login);
    }

    public function delete_manager($login)
    {
        $query = $this->db->placehold("DELETE FROM managers WHERE login = ? LIMIT 1", $login);
        $this->db->query($query);
        return $this->db->affected_rows();
    }

    public function access($module)
    {
        if(!$this->manager)
            $this->manager = $this->auto_login();

        if(is_array($this->manager->permissions))
            return in_array($module, $this->manager->permissions);

        return false;
    }

    public function auto_login()
    {
        if($this->sessions->admin)
        {
            $this->db->query("SELECT login FROM managers WHERE passhash = ?", $this->sessions->admin);
            if($login = $this->db->result('login'))
            {
                /*
                //если ип сессии не совпадает с текущим, кикнем пользователя
                if($this->request->ip() !== $this->sessions->ip)
                {
                    unset($this->sessions->admin);
                    return;
                }
                */
                return $this->manager = $this->get_manager($login);
            }
        }
        return false;
    }
}
