<?php

namespace Entity;

class User extends ModelBase
{
    public function install()
    {
        $dbPrefix = $this->getDbPrefix();
        $result = self::$dbo->exec("CREATE TABLE IF NOT EXISTS `{$dbPrefix}user` (
            `id` INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            `email` VARCHAR(128) NOT NULL UNIQUE,
            `password` VARCHAR(64),
            `sexe` ENUM('MALE', 'FEMALE') NULL,
            `optin` BOOLEAN DEFAULT FALSE,
            `register` DATETIME NOT NULL,
            `lastConnect` DATETIME NOT NULL,
            `lastVisit` DATETIME NOT NULL,
            `registerIp` VARCHAR(42) NOT NULL,
            `lastConnectIp` VARCHAR(42) NOT NULL,
            `lastVisitIp` VARCHAR(42) NOT NULL
        )");
        if ($result === false)
            throw new \Exception(get_class().": ".self::$dbo->errorInfo()[2]);
        return true;
    }

    public function __construct($id = null)
    {
        $this->register = $this->lastVisit = $this->lastConnect = new \DateTime();
        $this->registerIp = $this->lastVisitIp = $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);
    }
}

