<?php

$g_licenseTermsCache = null;

class PhonalisaLicenseManager
{

    const DEFAULT_LICENSE_KEY = 'XXXXXXXXXXXXXXX';
    const TRIMMED_VERSION_LENGTH = 3;

    /*
      Method takes a fileName and stores this as a license into the DataBase Server
      It will return TRUE in case that the license is valid and could be stored
      In Case of an error the method will return an error Code:
      485 Wrong Data
      487 Invalid Data
      486 Could not Write to File
      488 Invalid License
     */

    public static function storeLicense($fileName)
    {
        $fh = fopen($fileName, "rb");
        if ($fh == FALSE) {
            return FALSE;
        }

        $data = fread($fh, filesize($fileName));
        // unzip licence
        //$data = @zlib_decode($data);
        //save and check license through DB Server
        $result = PhonalisaDBConnector::storeLicense($data, strlen($data));
        if ($result->status == "ok") {
            return TRUE;
        } else {
            return $result->code;
        }
    }
    /*
     * Method gives back an info Array with License Informations it will return also if the
     * License is valid or not
     */

    public static function getSystemEdition()
    {

        $licInfo = PhonalisaLicenseManager::getLicenseInfo();
        $edition = @$licInfo['edition'];

        if ($edition == "") {
            $edition = "UNKNOWN OR LICENSE INVALID";
        }

        return $edition;
    }

    public static function getLicenseInfo()
    {
        $info = array();
        $result = PhonalisaDBConnector::getLicense();

        if ($result->status == "ok") {
            $info = array_merge((array) $result->licenseeInfos, (array) $result->licenseTerms);
        }

        return $info;
    }

    public static function getSystemID()
    {
        $result = PhonalisaDBConnector::getSystemID();
        if ($result->status == "ok") {
            return $result->system_id;
        }
        return '';
    }

    public static function getLicenseBrand()
    {
        $licInfo = PhonalisaLicenseManager::getLicenseInfo();
        $brand = @$licInfo['brand'];

        if ($brand == "") {
            $brand = "";
        }
        return $brand;
    }

    public static function getPhonalisaBranding()
    {
        $separator = '-';
        $edition = PhonalisaLicenseManager::getSystemEdition();
        $brand = PhonalisaLicenseManager::getLicenseBrand();
        $version = PhonalisaLicenseManager::getVersion(true);
        $editionText = "$edition $version";

        if ($brand !== 'Phonalisa') {
            $editionText = "Phonalisa $edition $version";
        }

        if ($edition === 'Tiptel' && $brand !== "" && $brand !== "Phonalisa") {
            $editionText = "Phonalisa $version";
        }

        if ($brand === "" || $brand === 'Phonalisa') {
            $separator = '';
        }

        return "$brand $separator $editionText";
    }

    public static function getVersion($trimmed = false)
    {
        $version = Yii::app()->params->phonalisaVersion;
        if (!$trimmed) {
            return $version;
        }

        $explodeBranding = explode(".", $version);
        $trimmedBranding = array_splice($explodeBranding, 0, PhonalisaLicenseManager::TRIMMED_VERSION_LENGTH);
        $trimmedBranding = implode(".", $trimmedBranding);

        return $trimmedBranding;
    }

    public static function faxGUIEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("faxGUIEnabled");
    }

    public static function analyticsDailyReportEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("analyticsDailyReportEnabled");
    }

    public static function analyticsQueueReportEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("analyticsQueueReportEnabled");
    }

    public static function phonesettingsSpeedDialMax()
    {
        return PhonalisaLicenseManager::getIntKey("phonesettingsSpeedDialMax");
    }

    public static function fax2MailEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("fax2MailEnabled");
    }

    public static function vmail2MailEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("vmail2MailEnabled");
    }

    public static function missedCall2MailEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("missedCall2MailEnabled");
    }

    public static function sipAccountOffline2MailEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("sipAccountOffline2MailEnabled");
    }

    public static function systemDateTimeProfileEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("systemDateTimeProfileEnabled");
    }

    public static function systemAudioFilesEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("systemAudioFilesEnabled");
    }

    public static function systemMusicOnHoldEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("systemMusicOnHoldEnabled");
    }

    public static function routingBlacklistEnabled()
    {
        $bool = PhonalisaLicenseManager::getBoolKey("routingBlacklistEnabled");
        if (!$bool) {
            $int = PhonalisaLicenseManager::getIntKey("routingBlacklistMax");
            if ($int === 0) {
                return false;
            } else {
                return true;
            }
        }
        return $bool;
    }

    public static function routingBlacklistMax()
    {
        $int = PhonalisaLicenseManager::getIntKey("routingBlacklistMax");
        if ($int === 0 && PhonalisaLicenseManager::routingBlacklistEnabled() === true) {
            return -1;
        }
        return $int;
    }

    public static function routingCallGroupMax()
    {
        return PhonalisaLicenseManager::getIntKey("routingCallGroupMax");
    }

    public static function routingExternalAgentEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("routingExternalAgentEnabled");
    }

    public static function routingExternalAgentsMax()
    {
        $int = PhonalisaLicenseManager::getIntKey("routingExternalAgentsMax");
        if ($int === 0 && PhonalisaLicenseManager::routingExternalAgentEnabled() === true) {
            return -1;
        }
        return $int;
    }

    public static function routingExternalHostEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("routingExternalHostEnabled");
    }

    public static function routingQueuesMax()
    {
        return PhonalisaLicenseManager::getIntKey("routingQueuesMax");
    }

    public static function routingConferenceMax()
    {
        return PhonalisaLicenseManager::getIntKey("routingConferenceMax");
    }

    public static function routingIVRMax()
    {
        return PhonalisaLicenseManager::getIntKey("routingIVRMax");
    }

    public static function routingGatewayMax()
    {

        return PhonalisaLicenseManager::getIntKey("routingGatewayMax");
    }

    public static function routingScriptExtensionMax()
    {
        return PhonalisaLicenseManager::getIntKey("routingScriptExtensionMax", -1);
    }

    public static function provisioningKeyProfileMax()
    {
        return PhonalisaLicenseManager::getIntKey("provisioningKeyProfileMax");
    }

    public static function provisioningProfileMax()
    {
        return PhonalisaLicenseManager::getIntKey("provisioningProfileMax");
    }

    public static function adminUserMax()
    {
        return PhonalisaLicenseManager::getIntKey("adminUserMax", -1);
    }

    public static function adminBillingEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("adminBillingEnabled");
    }

    public static function adminCallForwardingSetsEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("adminCallForwardingSetsEnabled");
    }

    public static function adminWebGuiPermissionsEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("adminWebGuiPermissionsEnabled");
    }

    public static function adminCalendarEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("adminCalendarEnabled");
    }

    public static function callForwardFilterPhoneStatusEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterPhoneStatusEnabled");
    }

    public static function callForwardFilterJabberStatusEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterJabberStatusEnabled");
    }

    public static function callForwardFilterTimeRuleEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterTimeRuleEnabled");
    }

    public static function callForwardFilterContactTypeEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterContactTypeEnabled");
    }

    public static function callForwardFilterNightCircutEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterNightCircutEnabled");
    }

    public static function callForwardFilterCallSourceEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardFilterCallSourceEnabled");
    }

    public static function callForwardAddFilterEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("callForwardAddFilterEnabled");
    }

    public static function privateAddressbooksMax()
    {
        return PhonalisaLicenseManager::getIntKey("privateAddressbooksMax");
    }

    public static function publicAddressbooksMax()
    {
        return PhonalisaLicenseManager::getIntKey("publicAddressbooksMax");
    }

    public static function userSipAccountsMax()
    {
        return PhonalisaLicenseManager::getIntKey("userSipAccountsMax");
    }

    public static function adminQueueMonitorEnabled()
    {
        return PhonalisaLicenseManager::getBoolKey("adminQueueMonitorEnabled");
    }

    public static function enterpriseQueuesAvailable()
    {
        return PhonalisaLicenseManager::getBoolKey("enterpriseQueuesAvailable");
    }

    private static function getBoolKey($key, $default = false)
    {
        $result = PhonalisaLicenseManager::getLicenseTerms();
        if (!isset($result[$key])) {
            return $default;
        }
        return (bool) $result[$key];
    }

    private static function getIntKey($key, $default = 0)
    {
        $result = PhonalisaLicenseManager::getLicenseTerms();
        if (!isset($result[$key])) {
            return $default;
        }
        return (int) $result[$key];
    }

    private static function getLicenseTerms()
    {
        global $g_licenseTermsCache;

        if ($g_licenseTermsCache === null) {
            $result = PhonalisaDBConnector::getLicense();

            if ($result->status == "ok") {
                $g_licenseTermsCache = (array) $result->licenseTerms;
            } else {
                // do not throw error here, because there is (may be) no license
                //  throw new CHttpException(500, "could not read License Terms!");
            }
        }
        return $g_licenseTermsCache;
    }

    public static function licenseIsValid()
    {
        $licenseCode = PhonalisaLicenseManager::getLicenseCode();
        if ($licenseCode !== PhonalisaLicenseManager::DEFAULT_LICENSE_KEY) {
            return true;
        }
        return false;
    }

    public static function getLicenseCode()
    {
        $data = PhonalisaLicenseManager::getLicenseInfo();
        if (isset($data['licenseKey'])) {
            return $data['licenseKey'];
        }
        return PhonalisaLicenseManager::DEFAULT_LICENSE_KEY;
    }
}
