<?php

namespace buckhill\encrypter;

abstract class AbstractEncrypter
{
    protected $method;
    protected $secret;
    protected $iv;

    public function __construct($method = null, $secret = null, $iv = null)
    {
        $this->method = $method;
        $this->secret = hash('sha256', $secret);

        if(is_null($iv))
        {
            $this->autoIV();
        }
        else
        {
            $this->iv = $iv;
        }
    }


    /**
     * @param bool|false $decode
     *
     * @return null|string
     */
    public function getIV($decode = false)
    {
        if($decode)
        {
            return base64_encode($this->iv);
        }
        else
        {
            return $this->iv;
        }
    }


    /**
     * @param string     $iv
     * @param bool|false $decode
     */
    public function setIV($iv = '', $decode = false)
    {
        if($decode)
        {
            $this->iv = base64_decode($iv);
        }
        else
        {
            $this->iv = base64_encode($iv);
        }
    }


    /**
     * @return $this
     * @throws \Exception
     */
    public function autoIV()
    {
        $iv_length = openssl_cipher_iv_length($this->method);

        if(false === $iv_length)
        {
            throw new \Exception(sprintf("Unable to get cipher iv length for the specified cipher: %s", $this->method));
        }

        $iv = openssl_random_pseudo_bytes($iv_length);

        $this->iv = $iv;

        return $this;
    }
}