<?php

namespace Mnv\Modules\Payment\Payme;

/**
 * @package Mnv\Modules\Payment\Payme
 */
class PaycomMerchant
{
    public $config;

    public function __construct($config)
    {
        $this->config = $config;

        if ($this->config['keyFile']) {
            $this->config['key'] = trim(file_get_contents($this->config['keyFile']));
        }
    }


    /**
     * Если не работает проверить существует ли $_SERVER["HTTP_AUTHORIZATION"]
     * @throws PaycomException
     */
    public function Authorize($request_id)
    {


        $headers = getallheaders();

//        print_r($_SERVER);
//        print_r($_SERVER["HTTP_AUTHORIZATION"]);

//        $headers2 = apache_request_headers();
//        if (isset($headers['Authorization'])) {
//            echo 'you are auth';
//        } else {
//            echo 'there is no Authorization';
//        }
//
//        print_r($headers);

        if (!$headers || !isset($headers['Authorization'])
            || !preg_match('/^\s*Basic\s+(\S+)\s*$/i', $headers['Authorization'], $matches)
            || base64_decode($matches[1]) != $this->config['login'] . ":" . $this->config['key']) {
            throw new PaycomException($request_id, 'Insufficient privilege to perform this method.', PaycomException::ERROR_INSUFFICIENT_PRIVILEGE);
        }

        return true;
    }
}