<?php

namespace App\Service\Moz;

final class Request
{
    private $accessId;
    private $secretKey;
    private $expires;
    private $domain;
    private $method = 'GET';
    private $cols = '103079215104';

    public function __construct($accessId, $secret, $expires, $domain)
    {
        $this->expires = time() + $expires;
        $this->accessId = $accessId;
        $this->secretKey = $secret;
        $this->domain = $domain;
    }

    /**
     * @return string
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    public function getUri()
    {
        return 'http://lsapi.seomoz.com/linkscape/url-metrics/'.
            urlencode($this->domain).
            '?Cols='.
            $this->cols.
            '&AccessID='.
            $this->accessId.
            '&Expires='.
            $this->expires.
            '&Signature='.
            $this->getSignature();
    }

    private function getSignature()
    {
        // Put each parameter on a new line.
        $stringToSign = $this->accessId."\n".$this->expires;

        // Get the "raw" or binary output of the hmac hash.
        $binarySignature = hash_hmac('sha1', $stringToSign, $this->secretKey, true);

        // Base64-encode it and then url-encode that.
        return urlencode(base64_encode($binarySignature));
    }
}
