<?php

require_once 'newedge/classes/LicenseDefenderRestAPI.php';
require_once 'modules/admin/models/ServerPlugin.php';
require_once 'modules/clients/models/ObjectCustomFields.php';

/**
* @package Plugins
*/
class PluginLicenseDefender extends ServerPlugin
{
    /*****************************************************************/
    // function getVariables - required function
    /*****************************************************************/
    function getVariables(){
        /* Specification
              itemkey     - used to identify variable in your other functions
              type        - text,textarea,yesno,password,hidden ( type hidden are variables used by CE and are required )
              description - description of the variable, displayed in ClientExec
              encryptable - used to indicate the variable's value must be encrypted in the database
        */
    
        $variables = array (
            /*T*/"Name"/*/T*/ => array (
                "type"=>"hidden",
                "description"=>"Used By CE to show plugin - must match how you call the action function names",
                "value"=>"License Defender"
                ),
            /*T*/"Description"/*/T*/ => array (
                "type"=>"hidden",
                "description"=>/*T*/"Description viewable by admin in server settings"/*/T*/,
                "value"=>/*T*/"ClientExec License Defender Integration"/*/T*/
                ),
            /*T*/"Username"/*/T*/ => array (
                "type"=>"text",
                "description"=>/*T*/"Username used to connect to server"/*/T*/,
                "value"=>""
                ),
            /*T*/"Password"/*/T*/ => array (
                "type"=>"password",
                "description"=>/*T*/"Password used to connect to server"/*/T*/,
                "value"=>"",
                "encryptable"=>true
                ),
            /*T*/"Domain Custom Field Name"/*/T*/ => array (
                "type"=>"text",
                "description"=>/*T*/"The name of the package custom field that will hold the domain ClientExec will be licensed for.<br><b>NOTE</b>: You must create this field manually in System Setup -> Products / Addons -> Custom Fields."/*/T*/,
                "value"=>""
                ),
            /*T*/"Actions"/*/T*/ => array (
                "type"=>"hidden",
                "description"=>/*T*/"Current actions that are active for this plugin per server"/*/T*/,
                "value"=>"Create,Delete"
                )
        );
        return $variables;
    }
      
    function doCreate($args)
    {
        $userPackage = new UserPackage($args['userPackageId']);
        $domain = $this->create($this->buildParams($userPackage));
        return 'License issued for ' . $domain . '.';
    }

    function create($args)
    {
        $userPackage = new UserPackage($args['package']['id']);
        $domain = $userPackage->getCustomField(@$args['server']['variables']['plugin_licensedefender_Domain_Custom_Field_Name'], CUSTOM_FIELDS_FOR_PACKAGE);
        if ($domain == "") {
            $errormsg = "No domain set in custom field or custom field doesn't exist, license not added.";
            $this->logger->log(4, "plugin_licensedefender::create::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        
        $lDefender = new LicenseDefenderRestAPI($args['server']['variables']['plugin_licensedefender_Username'], $args['server']['variables']['plugin_licensedefender_Password']);

        $return = json_decode($lDefender->addLicense($domain));
        
        if ($return === false) {
            $errormsg = "Error adding license: invalid JSON response.";
            $this->logger->log(4, "plugin_licensedefender::create::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        else if ( $return->error == 1 ) {
            $errormsg = 'Error adding license: ' . $return->msg;
            $this->logger->log(4, "plugin_licensedefender::create::error: ".$errormsg);
            throw new Exception ($errormsg);
        }

        return $domain;
    }
    
    function doDelete($args)
    {
        $userPackage = new UserPackage($args['userPackageId']);
        $domain = $this->delete($this->buildParams($userPackage));
        return 'License deleted for ' . $domain . '.';
    }
    
    function delete($args)
    {
        $userPackage = new UserPackage($args['package']['id']);
        $domain = $userPackage->getCustomField(@$args['server']['variables']['plugin_licensedefender_Domain_Custom_Field_Name'], CUSTOM_FIELDS_FOR_PACKAGE);
        if ($domain == "") {
            $errormsg = "No domain set in custom field or custom field doesn't exist, license not added.";
            $this->logger->log(4, "plugin_licensedefender::create::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        
        $lDefender = new LicenseDefenderRestAPI($args['server']['variables']['plugin_licensedefender_Username'], $args['server']['variables']['plugin_licensedefender_Password']);

        $return = json_decode($lDefender->deleteLicense($domain));
        
        if ($return === false) {
            $errormsg = "Error deleting license: invalid JSON response.";
            $this->logger->log(4, "plugin_licensedefender::delete::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        else if ( $return->error == 1 ) {
            $errormsg = 'Error deleting license: ' . $return->msg;
            $this->logger->log(4, "plugin_licensedefender::delete::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        return $domain;
    }
    
    function getAvailableActions($userPackage)
    {
        $args = $this->buildParams($userPackage);
        $userPackage = new UserPackage($args['package']['id']);
        $domain = $userPackage->getCustomField(@$args['server']['variables']['plugin_licensedefender_Domain_Custom_Field_Name'], CUSTOM_FIELDS_FOR_PACKAGE);
        if ($domain == "") {
            $errormsg = "No domain set in custom field or custom field doesn't exist, license not added.";
            $this->logger->log(4, "plugin_licensedefender::create::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        
        $actions = array();
        
        $lDefender = new LicenseDefenderRestAPI($args['server']['variables']['plugin_licensedefender_Username'], $args['server']['variables']['plugin_licensedefender_Password']);

        $return = json_decode($lDefender->getLicense($domain));
        $this->logger->log(2, print_r($return, true));
        if ($return === false) {
            $errormsg = "Error getting license: invalid JSON response.";
            $this->logger->log(4, "plugin_licensedefender::get::error: ".$errormsg);
            throw new Exception ($errormsg);
        }
        else if ( isset($return->domain) ) {
            $actions[] = 'Delete';
        } else if ( isset($return->error) ) {
            $actions[] = 'Create';
        }
        return $actions;
    }
}