<?php

class Licence extends PhonalisaRecord
{

    public $id;
    public $data;
    //for activate Licens :
    //NOTE : //* == aditional attribute

    public $license_code;
    public $customer_adr_street;
    public $customer_adr_street2;                    //*
    public $customer_adr_street_number;
    public $customer_adr_zip;
    public $customer_adr_region;
    public $customer_adr_country;
    public $customer_email;
    public $customer_firstname;
    public $customer_lastname;
    public $customer_company;
    public $customer_branch;                //*
    public $system_id;
    public $upgrade_code;
    public $agree_privacy;

    const UPGRADED_LICENSE_BOOLS = array(
        'adminWebGuiPermissionsEnabled',
        'adminCallForwardingSetsEnabled',
        'adminCalendarEnabled',
        'adminBillingEnabled',
        'routingBlacklistEnabled',
        'routingExternalAgentEnabled',
        'routingExternalHostEnabled',
        'routingPhonalisaConnectEnabled',
        'systemDateTimeProfileEnabled',
        'systemAudioFilesEnabled',
        'systemMusicOnHoldEnabled',
        'adminQueueMonitorEnabled',
        'enterpriseQueuesAvailable',
        'faxGUIEnabled',
        'fax2MailEnabled',
        'analyticsDailyReportEnabled',
        'analyticsQueueReportEnabled',
        'vmail2MailEnabled',
        'missedCall2MailEnabled',
        'sipAccountOffline2MailEnabled',
        'callForwardFilterPhoneStatusEnabled',
        'callForwardAddFilterEnabled',
        'callForwardFilterCallSourceEnabled',
        'callForwardFilterContactTypeEnabled',
        'callForwardFilterJabberStatusEnabled',
        'callForwardFilterTimeRuleEnabled',
        'callForwardFilterNightCircutEnabled'
    );
    const UPGRADED_LICENSE_INTS = array(
        'adminUserMax',
        'phonesettingsSpeedDialMax',
        'privateAddressbooksMax',
        'publicAddressbooksMax',
        'userSipAccountsMax',
        'provisioningProfileMax',
        'provisioningKeyProfileMax',
        'routingGatewayMax',
        'routingIVRMax',
        'routingConferenceMax',
        'routingQueuesMax',
        'routingBlacklistMax',
        'routingCallGroupMax',
        'tapiDriverConcurrentUser',
        'routingExternalAgentsMax'
    );
    const UPGRADED_LICENSE_DATES = array(
        'tapiDriverValidUntil'
    );

    public static function myAttributes()
    {
        return array(
            'id' => 'id',
            'data' => 'data',
            'license_code' => 'license_code',
            'customer_firstname' => 'customer_firstname',
            'customer_lastname' => 'customer_lastname',
            'customer_company' => 'customer_company',
            'customer_adr_street' => 'customer_adr_street',
            'customer_adr_street2' => 'customer_adr_street2',
            'customer_adr_street_number' => 'customer_adr_street_number',
            'customer_adr_zip' => 'customer_adr_zip',
            'customer_adr_region' => 'customer_region',
            'customer_adr_country' => 'customer_country',
            'customer_email' => 'customer_email',
            'customer_branch' => 'customer_branch',
            'system_id' => 'system_id',
            'upgrade_code' => 'upgrade_code',
            'agree_privacy' => 'agree_privacy'
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Gateway the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'licence';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('agree_privacy', 'required', 'except' => array('ajaxValidation')),
            array('agree_privacy', 'boolean'),
            array('license_code, customer_firstname, customer_lastname, customer_company, customer_adr_street, 
                customer_adr_street_number, customer_adr_zip, customer_adr_region, customer_adr_country, customer_email',
                'required', 'on' => array('activate', 'update', "ajaxValidation")
            ),
            array('upgrade_code', 'required', 'on' => array('upgradeLicense', 'update')),
            array('system_id', 'safe'),
            array('customer_company, customer_adr_street2, customer_branch, license_code', 'safe', 'on' => array('activate', "ajaxValidation")),
            array('customer_email', 'email', 'on' => 'activate'),
            array('customer_adr_zip', 'length', 'max' => 10, 'on' => array('activate', "ajaxValidation")),
            array('data', 'required', 'message' => __('LICENCE_MODEL_REQUIRED_ERROR_MESSAGE'), "except" => "ajaxValidation"),
            //array('data', 'file', 'allowEmpty'=>false),
            array('id, data', 'safe', 'on' => 'search'),
            array(
                'customer_adr_street_number',
                'match',
                'pattern' => '/^[0-9]/',
                'message' => __('LICENCE_MODEL_SHOULD_START_WITH_NUMBER_ERROR_MESSAGE'),
                'on' => array('activate', 'update', "ajaxValidation")
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated be$licenseInfolow.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('LICENCE_MODEL_ID'),
            'data' => __('LICENCE_MODEL_DATA'),
            'license_code' => __('LICENCE_MODEL_LICENSE_CODE'),
            'customer_adr_street' => __('LICENCE_MODEL_CUSTOMER_ADR_STREET'),
            'customer_adr_street2' => __('LICENCE_MODEL_CUSTOMER_ADR_STREET2'),
            'customer_adr_street_number' => __('LICENCE_MODEL_CUSTOMER_ADR_STREET_NUMBER'),
            'customer_adr_zip' => __('LICENCE_MODEL_CUSTOMER_ADR_ZIP'),
            'customer_adr_region' => __('LICENCE_MODEL_CUSTOMER_ADR_REGION'),
            'customer_adr_country' => __('LICENCE_MODEL_CUSTOMER_ADR_COUNTRY'),
            'customer_email' => __('LICENCE_MODEL_CUSTOMER_EMAIL'),
            'customer_company' => __('LICENCE_MODEL_CUSTOMER_COMPANY'),
            'customer_branch' => __('LICENCE_MODEL_CUSTOMER_BRANCH'),
            'customer_firstname' => __('LICENCE_MODEL_CUSTOMER_FIRSTNAME'),
            'customer_lastname' => __('LICENCE_MODEL_CUSTOMER_LASTNAME'),
            'upgrade_code' => __('LICENCE_MODEL_UPGRADE_CODE'),
            'agree_privacy' => __('WIZARD_AGREE_PRIVACY')
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($order = 'id')
    {
        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);
        if ($filter != null) {
            return new CPhonalisaDataProvider($this, array(
                'criteria' => $criteria,
            ));
        }
    }

    public function getData()
    {
        $licenseInfo = PhonalisaLicenseManager::getLicenseInfo();
        $licenseData = array();
        $id = 0;

        $sortedLicenseInfo = self::sortLicenseInfo($licenseInfo);
        foreach ($sortedLicenseInfo as $key => $value) {

            $licenseData[$id]['id'] = $id;
            $licenseData[$id]['name'] = $key;
            $licenseData[$id]['value'] = $value;

            $id++;
        }
        $dataProvider = new CArrayDataProvider($licenseData, array(
            'pagination' => false
        ));
        return $dataProvider;
    }

    public function getUpgradedData()
    {
        $licenseInfo = PhonalisaLicenseManager::getLicenseInfo();
        $licenseData = array();

        $id = 0;

        $notUsedKey = array_merge(array('system_id', 'brand'), array_keys(self::getLicenseInfoPrototype()));
        foreach ($licenseInfo as $key => $value) {
            if (in_array($key, $notUsedKey)) {
                continue;
            }

            $licenseData[$id]['id'] = $id;
            $licenseData[$id]['name'] = $key;
            $licenseData[$id]['value'] = $value;

            $id++;
        }
        $dataProvider = new CArrayDataProvider($licenseData, array(
            'pagination' => false
        ));
        return $dataProvider;
    }

    private static function getLicenseInfoPrototype()
    {
        return array(
            'company' => null,
            'person' => null,
            'street' => null,
            'postcode' => null,
            'city' => null,
            'country' => null,
            'email' => null,
            'activated' => null,
            'channels' => null,
            'edition' => null,
            'sku' => null,
            'licenseKey' => null,
            'valid' => null,
        );
    }

    public static function sortLicenseInfo($data)
    {
        $sortedLicenseInfo = array();
        foreach (self::getLicenseInfoPrototype() as $key => $value) {

            if (isset($data[$key])) {
                $sortedLicenseInfo[$key] = $data[$key];
            } else {
                Log::d("Key: \"$key\" does not exist in License file", "phonalisa-webinterface");
                if (isset($value)) {
                    Log::d("set default value to \"$value\"", "phonalisa-webinterface");
                    $sortedLicenseInfo[$key] = $value;
                } else {
                    
                }
            }
        }
        return $sortedLicenseInfo;
    }

    public function activateLicense()
    {
        $result = LicenseServer::activateLicense($this);
        if ($result === true) {
            return true;
        }
        Log::d("License API returned : " . $result['errorMessage'], "phonalisa-webinterface");
        return $result;
    }

    public function actionBeforeSave()
    {
        $this->agree_privacy = 0;
        return parent::beforeSave();
    }
}
