<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity()
 */
class EmailToken
{
    /**
     * @ORM\Id()
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="emailTokens")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $user;

    /**
     * @ORM\Column(name="token", type="string", length=255)
     */
    private $token;

    /**
     * @ORM\Column(name="expired_at", type="date")
     */
    private $expiredAt;

    public function __construct()
    {
        $bytes = random_bytes(64);
        $this->token = rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
        $this->expiredAt = new \DateTime('+ 3 days');
    }

    /**
    * Get token
    * @return string
    */
    public function getToken()
    {
        return $this->token;
    }

    /**
    * Set token
    * @return $this
    */
    public function setToken($token)
    {
        $this->token = $token;
        return $this;
    }

    /**
    * Get expiredAt
    * @return \DateTime
    */
    public function getExpiredAt()
    {
        return $this->expiredAt;
    }

    /**
    * Set expiredAt
    * @return $this
    */
    public function setExpiredAt($expiredAt)
    {
        $this->expiredAt = $expiredAt;
        return $this;
    }

    /**
    * Get user
    * @return User
    */
    public function getUser()
    {
        return $this->user;
    }
    
    /**
    * Set user
    * @return $this
    */
    public function setUser(User $user)
    {
        $this->user = $user;
        return $this;
    }

    /**
     * return true if the token is not expired
     * @return boolean true if valid
     */
    public function isValid()
    {
        $now = new \DateTime();
        return ($now < $this->expiredAt);
    }
}
