<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Traits;


use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Server;
use WHMCS\Database\Capsule as DB;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 09.09.19
 * Time: 13:53
 * Class ServerParams
 */
trait ServerParams
{

    /**
     * @param $id
     * @return array
     */
    public function getServerParamsByProductId($id)
    {
        $serverId = DB::table('tblproducts')
            ->join('tblservergroups', 'tblproducts.servergroup', '=', 'tblservergroups.id')
            ->join('tblservergroupsrel', 'tblservergroups.id', '=', 'tblservergroupsrel.groupid')
            ->join('tblservers', 'tblservergroupsrel.serverid', '=', 'tblservers.id')
            ->where('tblproducts.id', '=', $id)
            ->first(['tblservers.id'])
            ->id;

        if($serverId)
        {
            return $this->getServerParamsById($serverId);
        }

    }

    /**
     * @param $id
     * @return array
     */
    public function getServerParamsByHostingId($id)
    {
        $hosting = Hosting::where('id', $id)->first();
        if($hosting)
        {
            return $this->getServerParamsById($hosting->server);
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function getServerParamsById($id)
    {
        $server = Server::where('id', $id)->first();
        if ($server)
        {
            return [
                'serverid'         => $server->id,
                'serverip'         => $server->ipaddress,
                'serverhostname'   => $server->hostname,
                'serversecure'     => $server->secure,
                'serverusername'   => $server->username,
                'serverpassword'   => decrypt($server->password) ? decrypt($server->password) : $server->password,
                'serveraccesshash' => $server->accesshash,
                'serverport'       => $server->port,
            ];
        }

    }

}