<?php

/* * ********************************************************************
 * ProxmoxAddon product developed. (Aug 23, 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\Servers\Providers;

use ModulesGarden\ProxmoxAddon as main;
use ModulesGarden\ProxmoxAddon\App\Models\RangeVm;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Server;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;

/**
 *
 * Description of RangeVmProvider
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class RangeVmProvider extends BaseModelDataProvider implements AdminArea
{

    public function __construct()
    {
        parent::__construct(RangeVm::class);
    }

    public function read()
    {
        if (!$this->actionElementId)
        {
            return false;
        }
        $dbData = $this->model->where('server_id', $this->actionElementId)->first();
        if ($dbData !== null)
        {
            $this->data = $dbData->toArray();
        }
        $this->data['server_id'] = $this->actionElementId;
    }

    public function update()
    {

        //update & create
        if ($this->formData['vmid_from'] && $this->formData['vmid_to'])
        {
            $dbData = $this->model->where('server_id', $this->formData['server_id'])->first();
            if ($dbData === null)
            {
                $dbData = new RangeVm();
            }
            $dbData->fill($this->formData)->save();
        }
        else
        {//delete
            $this->model->where('server_id', $this->formData['server_id'])->delete();
        }
        $server = Server::find($this->formData['server_id']);
        main\Core\ServiceLocator::call('lang')->addReplacementConstant('name', $server->name);
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('The VM range for the server :name: has been edited successfully')
            ->setStatusSuccess()
            ->setCallBackFunction($this->callBackFunction);
    }
}
