<?php

/*
 * This file is part of the AuthStack project.
 *
 * (c) Buckhill Ltd <development@buckhill.co.uk>
 *
 * This source file is subject to the Buckhill license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Buckhill\License\Model;

use Buckhill\License\Exceptions\EncryptionException;

class EncryptedLicense
{
    /**
     * @var null
     */
    protected $encrypted = null;

    /**
     * @var array
     */
    protected $metadata = [
        'alg' => '',
        'key' => '',
        'iv' => ''
    ];

    public function __construct($encrypted, array $metadata)
    {
        $this->encrypted = $encrypted;
        $this->metadata = $metadata;
    }

    /**
     * @return License
     * @throws EncryptionException
     */
    public function decrypt()
    {
        $result = @openssl_decrypt($this->encrypted, $this->getAlg(), $this->getKey(), false, $this->getIV());

        if(false === $result)
        {
            throw new EncryptionException(openssl_error_string());
        }

        $license = json_decode($result, true);

        return License::load(array_merge($license, $this->metadata));
    }

    /**
     * @return null
     */
    public function getEncryptedPayload()
    {
        return $this->encrypted;
    }

    /**
     * @param bool $json
     * @return array|string
     */
    public function getEncryptionMetadata($json = false)
    {
        if($json)
        {
            return json_encode($this->metadata);
        }

        return $this->metadata;
    }

    /**
     * @return string
     */
    public function getAlg()
    {
        return $this->metadata['alg'];
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return $this->metadata['key'];
    }

    /**
     * @return string
     */
    public function getIV()
    {
        return $this->metadata['iv'];
    }
}