<?php

namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Sections;

use ModulesGarden\ProxmoxAddon\App\Models\VirtualNetwork;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Ip\Ipv4Range;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Buttons\ButtonBase;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\Fields\Select;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\Sections\BaseSection;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\Sections\BoxSection;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\Sections\HalfPageSection;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class VirtualNetworkSection extends BaseSection implements ClientArea
{
    use ProductService;

    public function initContent()
    {
        $this->initIds('virtualNetworkSection');
        $this->initFields();
    }

    public function initFields()
    {
        //virtualNetwork
        $this->customTplVars['virtualNetwork'] = ["public" => sl('lang')->abtr('Public')];
        //ips
        $this->customTplVars['ips']=[];
        //Public
        $this->customTplVars['ipSelected'] =null;
        foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))->ofVmIdNull()->get() as $ip)
        {
            if(!$this->customTplVars['ipSelected'] ){
                $this->customTplVars['ipSelected']  = $ip->ip;
            }
            $this->customTplVars['ips'][] =[
                "networkId" => "public",
                "ip" => $ip->ip,
                "id" => $ip->id
            ];
        }
        if(empty($this->customTplVars['ips'])){
            unset($this->customTplVars['virtualNetwork']['public']);
        }
        //private
        foreach (VirtualNetwork::ofHostingId($this->getWhmcsParamByKey('serviceid'))->get() as $vn)
        {
            $this->customTplVars['virtualNetwork'][$vn->id] = $vn->name;
            $ipRange = new Ipv4Range($vn->pool, $vn->cidr);
            $ipRange->setLimit(255);
            $ipRange->disableIpAddresses( $vn->virtualInterfaces->pluck('ip')->toArray());
            foreach (  $ipRange->get() as $ip ){
                $this->customTplVars['ips'][]=[
                    "networkId" => $vn->id,
                    "ip" => $ip,
                ];
            }
        }


    }
}