<?php

class Newsletter2Go
{

    private $host = "www.newsletter2go.de";
//    private $host = "dev.newsletter2go.com";
    private $port = 443;
    private $ssl = true;


    private $api_key;

    public function __construct($api_key)
    {

        if (!isset($api_key) || empty($api_key))
            throw new Exception("missing auth info.");
        $this->api_key = $api_key;
    }

    public function Newsletter2Go($api_key)
    {
        self::__construct($api_key);
    }

    public function sendSMS($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/send/sms/';
        return $this->handleRequest($url, $params);

    }

    public function getGroupSize($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/get/groupsize/';
        return $this->handleRequest($url, $params);

    }


    public function sendEmail($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/send/email/';
        return $this->handleRequest($url, $params);
    }

    public function createNL($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/create/newsletter/';
        return $this->handleRequest($url, $params);

    }

    public function createUser($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/affiliate/createaccount/';
        return $this->handleRequest($url, $params);

    }

    public function createIntegration($params = array())
    {

        $data = array('apikey' => $this->api_key,
            'url' => HTTPS_CATALOG_SERVER . MH_DIR_WS_CATALOG);

        $params['key'] = $this->api_key;
        $params['authentication'] = json_encode($data);
        $params['integration'] = 'mb';
        $url = '/de/api/create/integration/';
        return $this->handleRequest($url, $params);
    }

    public function getStatus()
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/get/status/';
        return $this->handleRequest($url, $params);

    }

    public function sendNL($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/send/newsletter/';
        return $this->handleRequest($url, $params);

    }

    public function getNewsletter($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/get/newsletter/';
        return $this->handleRequest($url, $params);

    }

    public function getStatistics($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/get/statistics/';
        return $this->handleRequest($url, $params);

    }

    public function getCredits()
    {

        $params = array();
        $params['key'] = $this->api_key;
        $url = '/de/api/get/credits/';
        return $this->handleRequest($url, $params);

    }

    public function getUnsubscribes($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/get/unsubscribes/';
        return $this->handleRequest($url, $params);

    }

    public function getHardbounces()
    {

        $params['key'] = $this->api_key;
        $params['apibounces'] = 1;
        $url = '/de/api/get/hardbounces/';
        return $this->handleRequest($url, $params);

    }

    public function createRecipient($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/create/recipient/';
        return $this->handleRequest($url, $params);

    }

    public function createGroup($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/create/group/';
        return $this->handleRequest($url, $params);

    }

    public function createRecipients($params)
    {

        $params['key'] = $this->api_key;
        $url = '/de/api/create/recipients/';
        return $this->handleRequest($url, $params);

    }

    public function getGroups()
    {

        $params = array();
        $params['key'] = $this->api_key;
        $url = '/de/api/get/groups/';
        return $this->handleRequest($url, $params);

    }

    public function getAllNewsletter()
    {

        $params = array();
        $params['key'] = $this->api_key;
        $url = '/de/api/get/newsletters/';
        return $this->handleRequest($url, $params);

    }

    public function deleteRecipient($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/recipient/';
        return $this->handleRequest($url, $params);
    }

    public function deleteGroup($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/group/';
        return $this->handleRequest($url, $params);
    }

    public function addRecipientToNewsletter($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/set/recipient/';
        return $this->handleRequest($url, $params);
    }

    public function addGroupToNewsletter($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/set/grouptonewsletter/';
        return $this->handleRequest($url, $params);
    }

    public function deleteGroupFromNewsletter($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/groupfromnewsletter/';
        return $this->handleRequest($url, $params);
    }

    public function deleteAllGroupsFromNewsletter($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/allgroupsfromnewsletter/';
        return $this->handleRequest($url, $params);
    }

    public function deleteAllRecipientsFromGroup($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/allrecipientsfromgroup/';
        return $this->handleRequest($url, $params);
    }

    public function getGroupsByNewsletter($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/get/groupsbynewsletter/';
        return $this->handleRequest($url, $params);
    }

    public function getRecipient($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/get/recipient/';
        return $this->handleRequest($url, $params);
    }

    public function getRecipients($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/get/recipients/';
        return $this->handleRequest($url, $params);
    }


    public function addRecipientToGroup($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/set/recipienttogroup/';
        return $this->handleRequest($url, $params);
    }

    public function deleteRecipientFromGroup($params)
    {
        $params['key'] = $this->api_key;
        $url = '/de/api/delete/recipientfromgroup/';
        return $this->handleRequest($url, $params);
    }

    /*
     * API to trigger Migration Process
     *
     */

    /*
     * replaced by link to upgrade page MAILBEEZ_CONFIG_EMAIL_ENGINE_N2G_UPGRADE_URL
     *
    public function setMigrationProcess() {
        $params['key'] = $this->api_key;
        $url = '/de/api/set/migration/';

        return array(
            'status' => 200,
            'value' => 'true' // true - migration process is started
        );

        return $this->handleRequest($url, $params);
    }
    */

    /*
     * API to get status of Migration Process
     *
     */

    public function getMigrationStatus() {
        $params['key'] = $this->api_key;
        $url = '/de/api/get/migrationstatus/';
        return $this->handleRequest($url, $params);

        // dummy result
        /*
         * 'not_available' - account is not yet triggered for migration
         * {"success":1,"value":{"date":null,"status":"not_available"},"status":200,"reason":"OK"}
         *
         * 'waiting' - account is waiting for getting migrated
         * {"success":1,"value":{"date":"2016-05-09","status":"waiting"},"status":200,"reason":"OK"}
         *
         * 'available' - account is migrated: API V2 is available
         * {"success":1,"value":{"date":"2016-05-09","status":"available"},"status":200,"reason":"OK"}
         */

        return array(
            'success' => 1,
            'status' => 200,
            'reason' => 'OK',
            'value' => array(
                'date' => '2017-05-09',
                'status' => 'waiting' // 'not_available', 'waiting', 'available'
            )
        );

    }



    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_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 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)) {
            print curl_error($ch);
            // die('curl error');
        } else {
            $info = curl_getinfo($ch);
            // print_r($info);
            // die('curl info');
        }

        curl_close($ch);
        return $json;
    }


}
