<?php

namespace MGModule\DNSManager2\models\whmcs\service;
use \MGModule\DNSManager2 as main;
use \MGModule\DNSManager2\mgLibs\custom\dns\utils\IP;
/**
 * Description of account
 * @Table(name=tblhosting,preventUpdate,prefixed=false)
 * @author Michal Czech <michael@modulesgarden.com>
 */
class service extends main\mgLibs\models\orm{
    /**
     * @Column()
     * @var type 
     */
    public $id;
    
    /**
     * @Column(name=userid,as=userid)
     * @var int 
     */
    public $clientID = 0;

    public $userid;
    /**
     *
     * @var client
     */
    private $_client;

    /**
     * @Column(name=dedicatedip,as=dedicatedip)
     * @var string 
     */
    public $dedicatedIP = null;
    
    /**
     * @Column(name=assignedips,as=assingedips)
     * @var array 
     */
    public $IPList = array();
    
    /**
     *
     * @Column(name=server,as=serverid)
     * @var int 
     */
    public $serverID;
    
    /**
     *
     * @var server
     */
    private $_server;
    
    /**
     * 
     * @Column(name=packageid,as=pid)
     * @var int 
     */
    public $productID;
    
    /**
     *
     * @var main\models\whmcs\product\product
     */
    private $_product;
    
    /**
     * 
     * @Column()
     * @var string 
     */
    public $domain;
    
    /**
     *
     * @Column()
     * @var string
     */
    public $username;
    
    /**
     * 
     * @Column(as=passwordEncrypted)
     * @var string
     */
    public $password;
    
    /**
     *
     * @Column(name=orderid)
     * @var int 
     */
    protected $_orderid;
    
    /**
     *
     * @Column(name=domainstatus,as=_domainstatus)
     * @var string
     */
    protected $_status;
    
    /**
     *
     * @Column(name=billingcycle,as=_billingcycle)
     * @var string 
     */
    protected $_billingcycle;
    
    /**
     *
     * @var main\models\whmcs\service\customFields\repository
     */
    private $_customFields;
    
    /**
     *
     * @var main\models\whmcs\service\configOption\repository 
     */
    private $_configOptions;
            
    /**
     * Load Account
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @param int $id
     * @param array $data
     * @throws main\mgLibs\exceptions\systemLoad
     */
    function __construct($id = null, $data = array()) {
        $this->id = $id;
        $this->load($data);
    }
    
    /**
     * Load Account Server
     * Function allows to easy overwrite server object
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @param int $id
     * @param array $data
     * @return main\models\whmcs\servers\server
     */
    protected function loadServer($id,$data = array()){
        return new main\models\whmcs\servers\server($id,$data);
    }
    
    /**
     * Load Product
     * Function allows to easy overwrite product object
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @param array $data
     * @return main\models\whmcs\product\product
     */
    protected function loadProduct($data = array()){
        return new main\models\whmcs\product\product($this->productID,$data);
    }
                
    /**
     * Load Client
     * Function allows to easy overwrite product object
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @param type $data
     * @return main\models\whmcs\service\client
     */
    protected function loadClient($data = array()){
        return new main\models\whmcs\client\client($this->clientID,$data);
    }
     
    /**
     * Get Server Connected With Service
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return main\models\whmcs\servers\server
     */
    public function server(){
       if(empty($this->_server))
       {
           $this->_server = $this->loadServer($this->serverID);
       }
       return $this->_server;
    }
    
    /**
     * Get Client Connected with Service
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return main\models\whmcs\client\client
     */
    function client(){
       if(empty($this->_client))
       {
           $this->_client = $this->loadClient();
       }
       
       return $this->_client;
    }
    
    function clientID(){
        return $this->clientID;
    }
    
    /**
     * Get Product Service
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return main\models\whmcs\product\product
     */
    public function product(){        
       if(empty($this->_product))
       {
           $this->_product = $this->loadProduct();
       }
       return $this->_product;
    }
    
    /**
     * Get Custom Fields
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return customFields
     */
    function customFields(){
        if(empty($this->_customFields))
        {
            $this->_customFields = new main\models\whmcs\service\customFields\repository($this->id);
        }
        
        return $this->_customFields;
    }
                 
    /**
     * Get Config Options
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return configOptions
     */
    function configOptions(){
       if(empty($this->_configOptions))
       {
           $this->_configOptions = new main\models\whmcs\service\configOptions\repository($this->id);
       }
       
       return $this->_configOptions;
    }
    
    /**
     * Get Merged Configs from product configuration & custom fields & confi optins
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @return \stdClass
     */
    function mergedConfig(){
                
        $obj = new \stdClass(); 
        
        foreach ($this->product()->configuration as $name => $value)
        {
            if(!empty($value))
            {
                $obj->$name = $value;
            }
        }
        
        foreach ($this->customFields()->toArray(false) as $name => $value)
        {
            if(!empty($value))
            {
                $obj->$name = $value;
            }
        }
        
        foreach ($this->configOptions()->toArray(false) as $name => $value)
        {
            if(!empty($value))
            {
                $obj->$name = $value;
            }
        }
        
        return $obj;
    }

    /**
     * Save Account Settings
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     */
    function save($cols = array()){         
        $cols['password']  = encrypt($this->password);
                
        if(($key = array_search($this->dedicatedIP, $this->IPList)) !== false) {
            unset($this->IPList[$key]);
        }
        
        $cols['assignedips'] = implode("\n",  $this->IPList);
        
        parent::save($cols);
    }
    
    /**
     * Set Object Properties
     * 
     * @author Michal Czech <michael@modulesgarden.com>
     * @param array $data
     * @throws main\mgLibs\exceptions\system
     */
    function load(array $data = array()){
        if(empty($this->id) && !empty($data['serviceid']))
        {
            $this->id = $data['serviceid'];
        }
        
        if($this->id !== null && empty($data))
        {
            $data = main\mgLibs\MySQL\query::select(
                    static::fieldDeclaration()
                    , static::tableName()
                    , array(
                        'id'    => $this->id
                    )
            )->fetch();
            
            if(empty($data))
            {
                throw new main\mgLibs\exceptions\system('Unable to find Item with ID:'.$this->id);
            }
        }
        
        if(isset($data['passwordEncrypted']))
        {
            $data['password'] = decrypt($data['passwordEncrypted']);
        }
        
        if(!empty($data['dedicatedip']))
        {
            $ipo = new IP(trim($data['dedicatedip']));
            $this->dedicatedIP =  $this->IPList[] = (string) $ipo;
        }
        
        if(!empty($data['assingedips']))
        {
            foreach(explode("\n",$data['assingedips']) as $ip)
            {
                if($ip) {
                    $ipo = new IP(trim($ip));
                    $ip = (string) $ipo;
                    
                    if(!in_array($ip, $this->IPList))
                    {
                        $this->IPList[] = trim($ip);
                    }
                }
                
            }
        }
        
        if(!empty($data['_domainstatus']))
        {
            $this->_status           = $data['_domainstatus'];
            $this->_billingcycle     = $data['_billingcycle'];
        }
        
        if(!empty($data['userid']))
        {
            $this->userid           = $data['userid'];
            $this->clientID         = $data['userid'];
            $this->serverID         = $data['serverid'];
            $this->domain           = $data['domain'];
            $this->productID        = $data['pid'];
            $this->username         = $data['username'];
            $this->password         = $data['password'];
        }

        if(!empty($data['server']))
        {
            $this->_server = $this->loadServer($data['serverid'], array(
                'hostname'      => $data['serverhostname']
                ,'username'     => $data['serverusername']
                ,'password'     => $data['serverpassword']
                ,'accesshash'   => $data['serveraccesshash']
                ,'secure'       => $data['serversecure']
                ,'ip'           => $data['serverip']    
            ));
        }
        
        if(!empty($data['customfields']))
        {
            $this->_customFields = new main\models\whmcs\service\customFields\repository($this->id,$data['customfields']);
        }
        
        if(!empty($data['configoptions']))
        {
            $this->_configOptions = new configOptions\repository($this->id);
        }
        
        if(!empty($data['_orderid']))
        {
            $this->_orderid = $data['_orderid'];
        }
    }
    
    
    function billingcycle(){
        if(empty($this->_billingcycle)){
            $this->load();
        }

        return $this->_billingcycle;
    }
    
    function getBillingCycleNumMonth(){
        switch ($this->billingcycle())
        {
            case 'Monthly':
                return 1;
            case 'Quarterly':
                return 3;
            case 'Semi-Annually':
                return 6; 
            case 'Annually':
                return 12;
            case 'Biennially':
                return 24;
            case 'Triennially':
                return 36;
        }
        
        return 0;
    }
    
    public function status(){
        if(empty($this->_status)){
            $this->load();
        }
        return $this->_status;
    }
    
    function orderId(){
        if(empty($this->_orderid)){
            $this->load();
        }
        return $this->_orderid;
    }
    
    public function getIPs() {        
        return $this->IPList;
    }
}
