<?php

namespace ModulesGarden\Servers\OpenXchange\App\Libs;

use ModulesGarden\Servers\OpenXchange\Core\ServiceLocator;

class RestCurl
{
    public $api;
    protected $result;
    protected $url;
    protected $ssl;
    protected $host;

    public function __construct(Api $api)
    {
        $this->api = $api;
    }

    public function __get($name)
    {
        return $this->api->getParams()[$name];
    }

    public function apiAdapter()
    {
        $this->changeHost();
    }

    public function changeHost()
    {
        $this->host = $this->api->getHost();
    }

    public function prepare()
    {
        $this->apiAdapter();
        $this->url = $this->api->getSSL().$this->host.$this->api->getEndpoint();
    }

    public function request()
    {
        $this->prepare();
        $ch     = curl_init($this->url); 
        $method = $this->api->getRequestMethod();

        $headers = [
            "Accept-Encoding: application/json",
            'Content-Type:application/json',
            'Authorization: Basic '. base64_encode($this->api->getUsername() . ":" . $this->api->getPassword())
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if($method == 'POST' || $method == 'PUT')
        {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->api->getRequestMethod());  
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->api->getPostfields()));   
        }

        if($method == 'DELETE')
        {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);  
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);  
        curl_setopt($ch, CURLOPT_USERPWD, $this->api->getUsername() . ":" . $this->api->getPassword());                                                                                                                                                 
        $this->result = curl_exec($ch);

        logModuleCall('openXchange', $this->api->getRequestMethod().' '.$this->url, [json_encode($this->api->getPostfields())], $this->result);

        if(!empty(curl_error($ch)))
        {
            throw new \Exception('CURL ERROR - '.curl_error($ch));
        }

        if(curl_getinfo($ch,  CURLINFO_HTTP_CODE) >= 300)
        {
            $apiResponse = $this->response();

            if ($apiResponse->error && $apiResponse->error != '')
            {
                if ($apiResponse->error == 'Alias already exsists')
                {
                    $lang    = ServiceLocator::call('lang');
                    $message = $lang->absoluteT('error', 'aliasAlreadyExists');

                    throw new \Exception($message);
                }
                else
                {
                    throw new \Exception($apiResponse->error);
                }
            }
            else
            {
                $responseCode = curl_getinfo($ch,  CURLINFO_HTTP_CODE);
                
                if ($responseCode == 405)
                {
                    $lang    = ServiceLocator::call('lang');
                    $message = $lang->absoluteT('error', 'httpcodeerror');

                    throw new \Exception($message);
                }
                
                throw new \Exception('ERROR (HTTP '.curl_getinfo($ch,  CURLINFO_HTTP_CODE).')');
            }
        }

        return $this;
    }

    public function response()
    {
        $result = json_decode($this->result);

        if (json_last_error() === JSON_ERROR_NONE)
        {
            return $result;
        }

        return $this->result;
    }
}
