<?php

namespace Persian_Flatsome;

class Request
{
    public $api_url = 'guard.zhaket.com/api/';

    public function send_request($method, $params = [], $https = false)
    {
        $param_string = http_build_query($params);
        $protocol = ($https) ? 'https://' : 'http://';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,
            $protocol . $this->api_url . $method . '?' . $param_string
        );
        $content = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode === 0) {
            if ($https) {
                $message = sprintf(__('your server curl has problem, return code:%s, please ticket to host to fix curl problem for url %s', 'zhaket-guard'), $httpCode, $protocol . self::$api_url);
                return json_decode(json_encode(['status' => 'error', 'message' => $message]));
            } else {
                return $this->send_request($method, $params, true);
            }
        }

        return $this->response(json_decode($content));
    }

    public function isValid($license_token)
    {
        return $this->send_request('validation-license', [
            'token' => $license_token,
            'domain' => $this->getHost(),
        ]);
    }

    public function install($license_token, $product_token)
    {

        return $this->send_request('install-license', [
            'product_token' => $product_token,
            'token' => $license_token,
            'domain' => $this->getHost(),
        ]);
    }

    public function getHost()
    {
        $domain = get_home_url();
        $result = parse_url($domain);

        if (isset($result['host']) && !empty($result['host'])) {
            return $result['host'];
        }

        $possibleHostSources = ['HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR'];
        $sourceTransformations = [
            "HTTP_X_FORWARDED_HOST" => function ($value) {
                $elements = explode(',', $value);
                return trim(end($elements));
            },
        ];

        $host = '';

        foreach ($possibleHostSources as $source) {
            if (!empty($host)) break;
            if (empty($_SERVER[$source])) continue;
            $host = $_SERVER[$source];
            if (array_key_exists($source, $sourceTransformations)) {
                $host = $sourceTransformations[$source]($host);
            }
        }

        // Remove port number from host
        $host = preg_replace('/:\d+$/', '', $host);
        // remove www from host
        $host = str_ireplace('www.', '', $host);

        return trim($host);
    }

    private function response($result)
    {
        $response = new \stdClass();
        $response->success = false;
        $response->message = '';

        if ($result->status == 'successful') {
            $response->success = true;
        } else {
            if (!is_object($result->message)) {
                $response->message = $result->message;
            } else {
                foreach ($result->message as $message) {
                    foreach ($message as $msg) {
                        $response->message = $msg;
                    }
                }
            }
        }

        return $response;
    }
}