<?php

namespace Entity;

class Admin extends ModelBase
{
    /**
     * Role -> 0 : no access
     *      -> 1 : read access
     *      -> 2 : +write access
     *      -> 3 : +delete /disable access
     *
     * [0] -> admin (add user, change site configuration)
     * [1] -> cms (add / modify / delete pages)
     * [2] -> products
     * [3] -> orders
     * [4] -> translations
     *
     * '*' Is the site admin, have all rights and no one can change this role
    **/
    public function install()
    {
        $dbPrefix = $this->getDbPrefix();
        $result = self::$dbo->exec("CREATE TABLE IF NOT EXISTS `{$dbPrefix}admin` (
            `id` INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            `email` VARCHAR(128) NOT NULL UNIQUE,
            `password` VARCHAR(64),
            `role` VARCHAR(8) NOT NULL DEFAULT '00000',
            `lastConnect` DATETIME NOT NULL,
            `lastConnectIp` VARCHAR(42) NOT NULL
        )");
        if ($result === false)
            throw new \Exception(get_class().": ".self::$dbo->errorInfo()[2]);
        return true;
    }

    public function __construct($id = null)
    {
        $this->lastConnect = new \DateTime();
        $this->lastConnectIp = \Tools\Context::getContext()->ip;
        parent::__construct($id);
    }

    public function checkPassword($value)
    {
        return password_verify($value, $this->password);
    }

    public function setPassword($value)
    {
        parent::__set("password", password_hash($value, PASSWORD_BCRYPT));
    }

    public function __set($key, $value)
    {
        if ($key == "password")
            return $this->setPassword($value);
        return parent::__set($key, $value);
    }
}

