<?php

/* * ********************************************************************
 * ProxmoxAddon product developed. (Sep 10, 2018)
 * *
 *
 *  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\ProxmoxAddon\App\UI\Templates\Fields;

use MGProvision\Proxmox\v2 as proxmox;
use ModulesGarden\ProxmoxAddon as main;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\AjaxFields\Select;

/**
 * Description of NodeSelect
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class NodeSelect extends Select implements AdminArea
{
    private $formData;

    public function returnAjaxData()
    {
        $this->formData = $this->getRequestValue('formData', []);
        $options        = [];
        foreach ($this->getOptions() as $id => $option)
        {
            $options[$id] = [
                'title'    => $option,
                'selected' => $this->formData['id'] && main\App\Models\IpAddress::where('id', $this->formData['id'])->where("node", $option)->count()
            ];
        }
        return (new main\Core\UI\ResponseTemplates\RawDataJsonResponse($options));
    }

    private function getOptions()
    {
        $options = ['0' => main\Core\ServiceLocator::call('lang')->absoluteT('Any')];
        if ($this->formData['sid'] > 0)
        {
            $servers = main\Core\Models\Whmcs\Server::where('id', $this->formData['sid']);
        }
        else
        {
            $servers = main\Core\Models\Whmcs\Server::whereIn("type", ["proxmoxVPS", "ProxmoxCloudVps"])->where('disabled', '0');
        }
        $nodeRepository = new proxmox\repository\NodeRepository();
        foreach ($servers->get() as $server)
        {
            /* @var $server main\Core\Models\Whmcs\Server */
            try
            {
                $host = $server->ipaddress ? $server->ipaddres : $server->hostname;
                $api  = new proxmox\Api($host, $server->username, $server->accesshash, decrypt($server->password));
                $nodeRepository->setApi($api);
                foreach ($nodeRepository->fetch() as $node)
                {
                    $options[$node->getNode()] = $node->getNode();
                }
            }
            catch (\Exception $ex)
            {//login to proxmox host failed
            }
        }
        return $options;
    }
}
