<?php


mh_define('APPZ_CLOUDBEEZ_SSL', true);


class newsletter2go_register
{
    private $host = "appz.cloudbeez.com";
    private $port = 443;
    private $ssl;

    private $api_key;


    public function __construct($lang = 'DE')
    {
        $this->lang = $lang;
        $this->ssl = mh_cfg('APPZ_CLOUDBEEZ_SSL');

    }

    public function newsletter2go_register($lang = 'DE')
    {
        self::__construct($lang);
    }

    public function createUser($params)
    {
        if ($this->lang == 'DE') {
            $url = '/api_n2g/de/v1/createaccount/';
        } else {
            $url = '/api_n2g/en/v1/createaccount/';
        }
        return $this->handleRequest($url, $params);
    }


    public function handleRequest($url, $params)
    {
        //Newsletter2Go API returns json format:
        $json = $this->http_request_curl('POST', $this->host, $this->port, $url, array(), $params);
        #var_dump($params);
        #var_dump($url);
        //convert json to php array:
        #echo($json);
        $json = json_decode($json, true);

        //return it to caller:
        return $json;
    }

    /* http request with curl , faster as http_request */
    /* need to install curl */
    private function http_request_curl($method, $host, $port, $path, $get, $post)
    {
        // Initialize session.
        $ch = curl_init();
        $prefix = "http://";
        if ($this->ssl) {
            $prefix = "https://";
        }

        curl_setopt($ch, CURLOPT_URL, $prefix . $host . $path);

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

        $postdata_str = '';
        foreach ($post as $k => $v) {
            $postdata_str .= urlencode($k) . '=' . urlencode($v) . '&';
        }
        $postdata_str = substr($postdata_str, 0, -1);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata_str);
        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, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

        $info = curl_getinfo($ch);
        //print_r($info);

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

        // todo: error handling
        if (empty($json)) {
            echo $path;
            print curl_error($ch);
            // die('curl error');
        } else {
            $info = curl_getinfo($ch);
            // print_r($info);
            // die('curl info');
        }


        curl_close($ch);
        return $json;
    }

}
