<?php

namespace AuthStack\EncryptedLicense;

use mageekguy\atoum\tests\functionals\mock\timeTravel;

class License implements \JsonSerializable
{
    protected $license = [];

    public function __construct(array $license)
    {
        $this->license = $license;
    }

    /**
     * @return bool
     */
    public function isValid(): bool
    {
        if(!$this->isExpired())
        {
            return true;
        }

        return $this->isInGracePeriod();
    }

    /**
     * @return bool
     */
    public function isExpired(): bool
    {
        return time() > $this->getEndsAt();
    }

    /**
     * @return bool
     */
    public function isStarted(): bool
    {
        return time() > $this->getStartsAt();
    }

    /**
     * @return bool
     */
    public function isInGracePeriod(): bool
    {
        $grace = new \DateTime("now", new \DateTimeZone('UTC'));

        $grace->setTimestamp($this->getEndsAt());

        $grace->modify($this->getGracePeriod());

        return $grace->getTimestamp() > time();
    }

    /**
     * @param string $domain
     * @return bool
     */
    public function validateDomain(string $domain): bool
    {
        return in_array($domain, $this->getDomains());
    }

    /**
     * @return array|mixed
     */
    public function jsonSerialize()
    {
        return $this->license;
    }

    /**
     * @return array
     */
    public function getDomains(): array
    {
        return isset($this->license['domain']) ? $this->license['domain'] : [];
    }

    /**
     * @return int
     */
    public function getStartsAt(): int
    {
        return isset($this->license['startsAt']) ? $this->license['startsAt'] : 0;
    }

    /**
     * @return int
     */
    public function getEndsAt(): int
    {
        return isset($this->license['endsAt']) ? $this->license['endsAt'] : 0;
    }

    /**
     * @return string
     */
    public function getGracePeriod(): string
    {
        return isset($this->license['gracePeriod']) ? $this->license['gracePeriod'] : '+1 day';
    }
}