<?php

namespace Eater\Glim\Handler\Panel\Servers\Edit;

use Eater\Glim\Handler\Session;
use Eater\Glim\Model\ServerQuery;
use Eater\Glim\Service\Server;

class Action extends Session
{
    protected $shouldHaveSuperuser = true;

    public function handle()
    {
        $server = ServerQuery::create()->findOneByFingerprint($this->attr('fingerprint'));

        $server->setFqdn($this->post('fqdn'));
        $server->setExternalIp($this->post('external-ip'));

        # Details
        $server->setLocation($this->post('location'));
        $server->setSpeed($this->post('speed'));

        # Config
        $server->setInternalIp($this->post('internal-ip'));
        $server->setNetmask($this->post('netmask'));
        $server->setPort($this->post('port'));
        $server->setProtocol($this->post('protocol'));
        $server->setFirstDns($this->post('first-dns'));
        $server->setSecondDns($this->post('second-dns'));

        $server->save();

        /** @var Server $serverService */
        $serverService = $this->get('server');
        try {
            $serverService->deliverOpenVPNConfig($server);
        } catch (\Exception $e) {
            return $this->json([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }

        return $this->json([ 'success'=> true ]);
    }
}