<?php

namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VirtualInterface\Fields;

use ModulesGarden\ProxmoxAddon\App\Models\VirtualNetwork;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Services\Ip\Ipv4Range;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\AjaxFields\Select;

class IpSelect extends Select implements ClientArea
{


    protected $id   = 'ipSelect';
    protected $name = 'ip';

    public function prepareAjaxData()
    {
        session_write_close();
        $vnId = $this->getRequestValue('formData')['vn_id'];
        if(!$vnId || $vnId=='public'){
            foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))->ofVmIdNull()->get() as $ip)
            {
                if(!$this->getValue()){
                    $this->setSelectedValue($ip->ip);
                }
                $this->availableValues[]=['key' =>  $ip->ip, 'value' => $ip->ip];
            }
            return;
        }
        /**
         * @var VirtualNetwork $virtualNetwork
         */
        $virtualNetwork = VirtualNetwork::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                                       ->ofId($vnId)
                                       ->firstOrFail();
        $ipRange = new Ipv4Range($virtualNetwork->pool, $virtualNetwork->cidr);
        $ipRange->setLimit(200);
        $ipRange->disableIpAddresses( $virtualNetwork ->virtualInterfaces->pluck('ip')->toArray());
        foreach (  $ipRange->get() as $ip ){
            if(!$this->getValue()){
                $this->setSelectedValue($ip);
            }
            $this->availableValues[]=['key' =>  $ip, 'value' => $ip];
        }
  ;
    }
}