<?php

/*
 * consume private cloudbeez API
 * API Key required
 *
 *
 */


class cloudBeezApiConsumer
{

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


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

        $this->timestamp_cachetime = 60 * 5;
    }

    function cloudBeezApiConsumer($api_key)
    {
        self::__construct($api_key);
    }

    public function getApiStatus()
    {
        $result = false;
        // <mailbeez_protected>
        // check if API key is valid
        if (!defined('CLOUDLOADER_DISABLE_DEPLOY') && file_exists(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'cloudbeez/dev_environment.php')) {
            include(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'cloudbeez/dev_environment.php');
        }

        $params['apikey'] = $this->api_key;
        $params['p'] = urlencode(base64_encode(serialize(array('domain' => $_SERVER['SERVER_NAME']))));
        $url = '/api/private/v1/ping';
        $result = $this->handleGetRequest($url, $params);
        // </mailbeez_protected>
        return $result;

    }

    public static function getSubscriptionInfo()
    {
        $result = false;
        // <mailbeez_protected>

        $result = mh_storage_get('subscription_check_result_subscription_info');

        // </mailbeez_protected>
        return $result;

    }


    public static function getSubscriptionInfoHtml()
    {
        $result = false;
        // <mailbeez_protected>

        $subscriptions = cloudBeezApiConsumer::getSubscriptionInfo();

        if (is_array($subscriptions)) {
            ob_start();
            ?>
            <style type="text/css">
                div.mh_sub_info {

                }

                .mh_sub_info h2 {
                    margin: 0px;
                    font-size: 14px;
                }

                .mh_sub_info.valid h2 {
                    color: #abd37f;
                }

                .mh_sub_info.invalid h2 {
                    color: red;
                }

                .mh_sub_msg {
                    color: #ff0000;
                    font-weight: bold;
                }

            </style>

            <?php
            $result = ob_get_contents();
            ob_end_clean();


            foreach ($subscriptions as $subscr) {

//                $subscr['status']; // ACTIVE / PASTDUE
//                $subscr['expires_in']; // number of days
//                $subscr['expiration_date']; // 2014-09-30
//                $subscr['valid_license']; // true / false
//                $subscr['error_license'];
                $msg = '';

                $expired = false;
                if ($subscr['error_license']) {
                    switch ($subscr['error_license']) {
                        case 'exceeded cnt_customers':
                            $msg = mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_CUSTOMER_CNT_EXCEED');
                            break;
                        default;
                            $msg = '';
                        // ok
                    }
                } elseif ($subscr['expires_in'] == -1) {
                    $expired = true;
                    $msg = mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_EXPIRED');
                } else {
                    $msg = '';
                }

                $subscription_info = implode("\n", array_keys($subscr['modules']));

                ob_start();
                ?>
                <div
                        style="border: 1px solid #c0c0c0; padding: 10px; margin: 10px; text-align: center; background-color: #fff">

                    <div
                            class="mh_sub_info <?php echo ($subscr['valid_license'] && !$expired) ? 'valid' : 'invalid'; ?>">
                        <h2 title="<?php echo $subscription_info; ?>"><?php echo
                            (mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_' . strtoupper($subscr['data']['title'])) ?
                                mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_' . strtoupper($subscr['data']['title'])) : $subscr['data']['title']
                            );

                            ?></h2>

                        <div><sup><?php echo $subscr['status']; ?></sup></div>

                        <?php if ($msg) { ?>
                            <div class="mh_sub_msg"><?php echo $msg ?></div>
                        <?php } ?>

                        <?php if ($subscr['expires_in'] > 0) { ?>
                            <div>

                                <?php echo mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_MAX_CUSTOMER_CNT'); ?>
                                <?php echo $subscr['data']['max_customers']; ?>
                                <br/>
                                <?php echo mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_VALID_UNTIL'); ?>
                                <?php echo $subscr['expiration_date']; ?>
                                (<?php echo $subscr['expires_in']; ?>
                                <?php echo mh_lng('MAILBEEZ_CONFIG_CLOUDBEEZ_VALID_UNTIL_DAYS_LEFT'); ?>)
                            </div>
                        <?php } ?>
                    </div>

                </div>
                <?php
                $result .= ob_get_contents();
                ob_end_clean();


            }
        } else {

        }
        // </mailbeez_protected>
        return $result;
    }

    // not used
    /*
    public function getApiLicenseInfo()
    {
        // check for license for current API key
        $params['apikey'] = $this->api_key;
        $url = '/api/private/v1/license';
        return $this->handleGetRequest($url, $params);
    }
    */

    public function checkIsInstalled()
    {
        $hash = $this->getInstalledPackageHash();
        return ($hash) ? true : false;
    }


    public function checkLicenseVersion()
    {
        $hash_installed = $this->getInstalledPackageHash();
        $hash = $this->getPackageHash();

        if ($hash_installed) {
            // 1: up to date
            // 0: new version

            return (int)($hash_installed == $hash);
        } else {
            // not yet installed
            return -1;
        }

    }


    private function getPackageHash()
    {
        $hash = false;
        // <mailbeez_protected>
        // check if API key is valid
        $params['apikey'] = $this->api_key;
        $url = '/api/private/v1/package/install';
        $result = $this->handleGetRequest($url, $params);

        if (isset($result['error'])) {
            return false;
        } else {
            $hash = $result['package']['id'];
            return $hash;
        }
        // </mailbeez_protected>
    }

    private function getInstalledPackageHash()
    {
        $f = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'cloudbeez/package.hash';
        if (file_exists($f)) {
            return file_get_contents($f);
        } else {
            return false;
        }
    }


    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 = ($this->ssl) ? "https://" : "http://";

        // Set so curl_exec returns the result instead of outputting it.
        $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, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        //curl_setopt($ch, CURLOPT_VERBOSE, true);

        $headers = array(
            "Content-Type: application/json",
            "Accept: application/json",
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $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);
        }

        $json = curl_exec($ch);
        if (empty($json)) {
            //echo $path;
            //print curl_error($ch);
            // die('curl error');
            $json = json_encode(array('curl_error' => curl_error($ch)));

        } else {
            $info = curl_getinfo($ch);
            // print_r($info);
            // die('curl info');
        }


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


        // Get the response and close the channel.
        if (PHP_VERSION_ID < 80000) {
            curl_close($ch);
        }
        return $json;
    }

}
