<?php

/*
 * consume public cloudbeez API
 *
 *
 */


class cloudBeezPublicApiConsumer
{

    private $host = CLOUDBEEZ_DOMAIN;
    private $port = CLOUDBEEZ_PORT;
    private $ssl = CLOUDBEEZ_SSL;


    public function __construct()
    {

    }

    function cloudBeezPublicApiConsumer()
    {
        self::__construct();
    }

    /*
     * check connection
     *
     */

    public function getApiStatus()
    {
        // cache in request
        $cache_key = 'cache_cloudbeez_api_status';
        if (isset($GLOBALS[$cache_key])) {
            return $GLOBALS[$cache_key];
        }

        $result = false;
        // <mailbeez_protected>
        $params = array();
        $url = '/api/public/v1/ping';
        $result = $this->handleGetRequest($url, $params);
        $GLOBALS[$cache_key] = $result;

        // </mailbeez_protected>


        return $result;
    }

    /*
     * check if store is allowed to get access to cloudbeez plans
     *
     *
     */

    public function getProPermission()
    {
        // cache in request
        $cache_key = 'cache_cloudbeez_api_pro_permission';
        if (isset($GLOBALS[$cache_key])) {
            return $GLOBALS[$cache_key];
        }

        $result = false;
        // <mailbeez_protected>
        // check if API key is valid
        $params['platform'] = MH_PLATFORM;
        $params['mh_id'] = MH_ID;
        $params['domain'] = $_SERVER['SERVER_NAME'];
        $url = '/api/public/v1/check';
        $result = $this->handleGetRequest($url, $params);
        $GLOBALS[$cache_key] = $result;


        // </mailbeez_protected>
        return $result;
    }


    public function handleGetRequest($url, $params)
    {
        $json = $this->http_request_curl('GET', $this->host, $this->port, $url, $params, array());
        $json = json_decode($json, true);
        return $json;
    }


    public function handlePostRequest($url, $params)
    {
        $json = $this->http_request_curl('POST', $this->host, $this->port, $url, array(), $params);
        $json = json_decode($json, true);
        return $json;
    }

    private function http_request_curl($method, $host, $port, $path, $get, $post)
    {
        // Initialize session.
        $ch = curl_init();
        $prefix = "http://";
        if ($this->ssl) {
            $prefix = "https://";
        }

        // Set so curl_exec returns the result instead of outputting it.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


        $get_params = '';
        if ($method == 'POST') {
            // POST
            $post_data_str = '';
            foreach ($post as $k => $v) {
                $post_data_str .= urlencode($k) . '=' . urlencode($v) . '&';
            }
            $post_data_str = substr($post_data_str, 0, -1);


            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_str);
        } else {
            // GET
            $get_data_str = '';
            foreach ($get as $k => $v) {
                $get_data_str .= urlencode($k) . '=' . urlencode($v) . '&';
            }
            $get_data_str = substr($get_data_str, 0, -1);

            $get_params = '?' . $get_data_str;

        }
        // echo '***' . $prefix . $host . $path . $get_params . '***';

        curl_setopt($ch, CURLOPT_URL, $prefix . $host . $path . $get_params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);


        $version = curl_version();
        if (isset($version['features']) && defined('CURLOPT_IPRESOLVE')) {
            // http://stackoverflow.com/questions/11004624/failed-to-connect-to-2a032880101f03faceb00c026-network-is-unreachable-fr
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }

        // Get the response and close the channel.
        $json = curl_exec($ch);

        // todo
        // handle connection failure
        if (empty($json)) {
            echo $path;
            echo "#error api_cloudbeez_public: ";
            print curl_error($ch);
            // die('curl error in cloudBeezPublicApiConsumer::http_request_curl');
            echo "#curl info: ";
            $info = curl_getinfo($ch);
            print_r($info);
        } else {
//            $info = curl_getinfo($ch);
//            print_r($info);
//            die('curl info');
        }


        curl_close($ch);
        return $json;
    }

}
