<?php
/**********************************************************************
 * ProxmoxVPS developed. (26.03.19)
 * *
 *
 *  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
 *  CONTACT                        ->       contact@modulesgarden.com
 *
 *
 * This software is furnished under a license and may be used and copied
 * only  in  accordance  with  the  terms  of such  license and with the
 * inclusion of the above copyright notice.  This software  or any other
 * copies thereof may not be provided or otherwise made available to any
 * other person.  No title to and  ownership of the  software is  hereby
 * transferred.
 *
 *
 **********************************************************************/

namespace ModulesGarden\Servers\ProxmoxVps\App\Http\Actions;

use MGProvision\Proxmox\v2\Api;
use ModulesGarden\Servers\ProxmoxVps\App\Helpers\ProxmoxAddonValidator;
use ModulesGarden\Servers\ProxmoxVps\Core\App\Controllers\Instances\AddonController;

class TestConnection extends AddonController
{
    public function execute($params = null)
    {
        try
        {
            if(isset($GLOBALS['disable_hook_loading']) && $GLOBALS['disable_hook_loading']){
                throw new \Exception("Enabled hooks are required by the module. Please disable \$disable_hook_loading in cofiguration.php ");
            }
            ProxmoxAddonValidator::isInstalledOrFail();
            if (!$params['serverip'] && !$params['serverhostname'])
            {
                throw new \Exception("Server Hostname or  IP Address  is empty.");
            }
            if ($params['serverip'])
            {
                if(is_numeric($params['serverport'])){
                    $params['serverip'] .=":".$params['serverport'];
                }
                $api = new Api($params['serverip'], $params['serverusername'], $params['serveraccesshash'], $params['serverpassword']);
                $api->debug();
                $api->get("/nodes");
            }
            if ($params['serverhostname'])
            {
                if (preg_match("/[\/]/", $params['serverhostname']))
                {
                    throw new \Exception(sprintf("Server Hostname '%s' is invalid", $params['serverhostname']));
                }
                if(is_numeric($params['serverport'])){
                    $params['serverhostname'] .=":".$params['serverport'];
                }
                $api = new Api($params['serverhostname'], $params['serverusername'], $params['serveraccesshash'], $params['serverpassword']);
                $api->debug();
                $api->get("/nodes");
            }
            return ['success' => true];
        }
        catch (\Exception $e)
        {
            return ['error' => $e->getMessage()];
        }
    }
}