<?php

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_system.php');

// <mailbeez_protected>

//mh_define('CLOUDBEEZ_DOMAIN', 'apps.mailbeez.com');  // SSL only - issue: can get blocked on some servers
mh_define('CLOUDBEEZ_DOMAIN', 'cloudbeez.com');
mh_define('CLOUDBEEZ_SSL', false);
mh_define('CLOUDBEEZ_PORT', 443);

//$prefix = (CLOUDBEEZ_SSL) ? "https://" : "http://";

// simple solution
$prefix = '//';

// MH_PLATFORM
// MH_ID - platform or affiliate

// &inline=true
// removed as there are some security issues with iframes

$params = '&clb=' . base64_encode(mh_href_link(FILENAME_MAILBEEZ, 'cloudbeez_purchase=ok')) . '&clu=' . base64_encode(MAILBEEZ_MAILHIVE_URL_DIRECT) . '&clp=' . base64_encode(mh_cfg('CLOUDLOADER_PRIVATE_API_KEY')) . '&clt=' . ((defined('CLOUDBEEZ_CLT') ? mh_cfg('CLOUDBEEZ_CLT') : '0')) . '&a=' . MH_ID;

// add cnt to pre-select plan
$params .= '&c_cnt=' . mailbeez_system::getUniqueCustomerCnt();

// todo:
// add language info

switch ($_SESSION['language']) {
    case "german":
        define('CLOUDBEEZ_DOMAIN_LANG', str_replace('.com', '.de', CLOUDBEEZ_DOMAIN));
        break;
    default:
        define('CLOUDBEEZ_DOMAIN_LANG', CLOUDBEEZ_DOMAIN);
        break;
}

define('CLOUDBEEZ_REGISTER_URL', $prefix . CLOUDBEEZ_DOMAIN_LANG . '/user/login?cla=register' . $params);
define('CLOUDBEEZ_SELECT_PLAN_URL', $prefix . CLOUDBEEZ_DOMAIN_LANG . '/plans?cla=buy' . $params);

// </mailbeez_protected>

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/classes/mailbeez_cache.php');

if (!class_exists('cloudbeez_status_cache')) {
    class cloudbeez_status_cache extends mailbeez_cache
    {
        function __construct()
        {
            parent::__construct();
            $this->app_cache_time = 60 * 10; // cache time in sec
        }

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


class cloudbeez_status_handler
{

    public static function getStatus($cache = true, $redirect = true, $refresh = false)
    {
        // caching
        // <mailbeez_protected>

        $cloudbeez_connection_cache = new cloudbeez_status_cache();
        $cloudbeez_connection_cache->set_cache_id('cloudbeez', 'cloudbeez');

        if (stristr($_SERVER['QUERY_STRING'], 'config_cloudbeez&refresh=ok')) {
            // todo
            // make common call to unset session data
            unset($_SESSION['cache_cloudbeez_status_handler_time']);
            unset($_SESSION['cache_cloudbeez_status_handler']);

            mh_storage_destroy('subscription_check_result');
            mh_storage_destroy('subscription_check_result_subscription_info');

            $cloudbeez_connection_cache->purge_cache('app');
            $back_url = mh_href_link(FILENAME_MAILBEEZ, 'module=config_cloudbeez');
            if ($redirect) {
                mh_redirect($back_url);
            }
        }

        // todo
        // refactoring
        if ($refresh || (isset($_SESSION['cloudloader_refresh_connection']) && $_SESSION['cloudloader_refresh_connection']))  {
            unset($_SESSION['cloudloader_refresh_connection']);
            unset($_SESSION['cloudbeez_purchase']);

            unset($_SESSION['cache_cloudbeez_status_handler_time']);
            unset($_SESSION['cache_cloudbeez_status_handler']);

            mh_storage_destroy('subscription_check_result');
            mh_storage_destroy('subscription_check_result_subscription_info');

            $cloudbeez_connection_cache->purge_cache('app');
            if ($redirect) {
                mh_redirect(mh_href_link(FILENAME_MAILBEEZ, ''));
            }
            if ($refresh) {
                return true;
            }
        }


        if ($cache && $cloudbeez_connection_cache->read_cache('app')) {
            // load from appcache if set

            // restore session
            $content = $cloudbeez_connection_cache->read_cache('app');
            list($c1, $c2) = explode('|', $content['value']);

            $_SESSION['cache_cloudbeez_status_handler'] = $c1;
            $_SESSION['cache_cloudbeez_status_handler_time'] = $c2;
        }


        $timestamp_cachetime = 60 * 5;

        if (isset($_SESSION['cache_cloudbeez_status_handler']) && !(isset($_SESSION['cloudbeez_purchase']) && $_SESSION['cloudbeez_purchase'])) {
            if (time() - $timestamp_cachetime < $_SESSION['cache_cloudbeez_status_handler_time']) {
                return unserialize($_SESSION['cache_cloudbeez_status_handler']);
            }
        }

        $show_select_package = false;
        $show_waiting_info = false;
        $show_install_package = false;
        $show_update_package = false;
        $show_invalid_license = false;
        $show_update_package_ok = false;
        $show_api_error = false;
        if (mh_cfg('CLOUDLOADER_API_KEY') != '') {
            // api key set
            $cloud_api = new cloudBeezApiConsumer(mh_cfg('CLOUDLOADER_API_KEY'));
            $is_installed = $cloud_api->checkIsInstalled();

            $status_result = $cloud_api->getApiStatus();
            if (!$is_installed) {
                // not yet installed
                // check api and license status
                if (isset($status_result['result'])) {
                    // API connection established
                    if (isset($status_result['license']) && $status_result['license']) {
                        // valid license
                        $show_install_package = true;
                    } else {
                        // no license yet
                        if (isset($_SESSION['cloudbeez_purchase'])) {
                            // but purchase was performed, so lets wait for IPN to get processed
                            $show_waiting_info = true;
                        } else {
                            // no purchase
                            $show_select_package = true;
                        }
                    }
                } else {
                    // no api connection - wrong key?
                    $show_api_error = true;
                    $show_select_package = true;
                }
            } else {

                // installed
                // check for updates

                if (isset($status_result['result']) && $status_result['result']) {
                    // API connection established
                    if (isset($status_result['license']) && $status_result['license']) {
                        // valid license
                        // todo: check for version

                        $uptodate = $cloud_api->checkLicenseVersion();
                        if ($uptodate === -1) {
                            $show_invalid_license = true;
                            $show_select_package = true;
                        } else {
                            $show_update_package = !$uptodate;
                            $show_update_package_ok = $uptodate;
                        }
                    } else {
                        // invalid license
                        $show_select_package = true;
                        $show_invalid_license = true;
                    }
                } else {
                    // no api connection - wrong key?
                    // todo: message api connection failed
                    $show_api_error = true;
                }
            }
        } else {
            // check if subscriptions are allowed
            $cloud_public_api = new cloudBeezPublicApiConsumer();

            $status_result = $cloud_public_api->getApiStatus();
            if (isset($status_result['result']) && $status_result['result']) {
                $result = $cloud_public_api->getProPermission();
                $show_select_package = $result['result'];
            } else {
                // no api connection - server down?
                $show_select_package = false;
            }
        }

        $result = array($show_select_package, $show_waiting_info, $show_install_package, $show_update_package, $show_update_package_ok, $show_invalid_license, $show_api_error);

        // set cache
        $_SESSION['cache_cloudbeez_status_handler'] = serialize($result);
        $_SESSION['cache_cloudbeez_status_handler_time'] = time();
        // </mailbeez_protected>


        $cache_code = implode('|', array($_SESSION['cache_cloudbeez_status_handler'], $_SESSION['cache_cloudbeez_status_handler_time']));

        $cloudbeez_connection_cache->set_cache($cache_code, 'app');
//        echo "set cache";

        return $result;
    }

    public static function getActionUrls()
    {
        $select_package = CLOUDBEEZ_SELECT_PLAN_URL;
        $install_package = mh_href_link(FILENAME_MAILBEEZ, 'cloudloader_mode=install_package');
        $update_package = mh_href_link(FILENAME_MAILBEEZ, 'cloudloader_mode=update_package');

        if (MH_REQUEST_TYPE == 'SSL') {
            // force https
            $select_package = str_replace('http://', 'https://', $select_package);
            $install_package = str_replace('http://', 'https://', $install_package);
            $update_package = str_replace('http://', 'https://', $update_package);
        }

        return array($select_package, $install_package, $update_package);
    }

}