<?php

namespace AuthStack\Installer\Services;

use Buckhill\License\LicenseManager;
use Buckhill\License\Model\DecryptedLicense;
use AuthStack\Installer\Model\License as LicenseModel;

class License
{
    protected $publicKey;
    protected $manager;
    protected $errors = [];

    public function __construct($publicKey)
    {
        $this->publicKey = $publicKey;
        $this->manager = new LicenseManager();
    }

    /**
     * @param $licenseString
     * @param $domain
     * @return LicenseModel|bool
     */
    public function verify($licenseString, $domain)
    {
        $license = $this->decrypt($licenseString);

        if(!$license->domainIs($domain))
        {
            $this->errors[] = sprintf("License specified is not issued for this domain (%s)", $domain);
        }

        if($license->isExpired())
        {
            $this->errors['license'] = 'License has expired';
        }

        $result = !sizeof($this->errors);

        if($result)
        {
            return new LicenseModel([
                'id' => 1,
                'license' => $licenseString,
                'domain' => $domain,
                'endsAt' => $license->getEndsAt()->format('Y-m-d H:i:s')
            ]);
        }

        return $result;
    }

    /**
     * @return mixed
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * @return LicenseManager
     */
    public function getManager()
    {
        return $this->manager;
    }

    /**
     * @param $licenseString
     * @return DecryptedLicense
     */
    protected function decrypt($licenseString)
    {
        $manager = $this->getManager();

        $model = $manager->unseal($licenseString, $this->publicKey);

        return new DecryptedLicense($model->getModel(false));
    }
}