<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailForwarder\Providers;

use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;
use ModulesGarden\Servers\OpenXchange\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\OpenXchange\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 18.09.19
 * Time: 09:35
 * Class EditForwarderDataProvider
 */
class EditForwarderDataProvider extends BaseDataProvider
{
    public function read()
    {
        $params = Helper::moduleParams($_REQUEST['id']);
        $api = new RestApi($params);
        $forwarder = reset($api->getForwarder($this->actionElementId));
        $exploded = explode('@', $this->actionElementId);
        $alias = $exploded[0];
        $domain = $exploded[1];
        $this->data['alias'] = $alias;
        $this->data['domain'] = $domain;
        $this->data['forwarder'] = $forwarder;
    }
    public function update()
    {
        $hid = $this->getRequestValue('id');
        $hosting = Hosting::where('id', $hid)->first();
        $this->formData['alias'] = $this->formData['alias'].'@'.$hosting->domain;
        try{
            $params = Helper::moduleParams($_REQUEST['id']);
            $api = new RestApi($params);
            $api->updateForwarder($this->formData['forwarder'], $this->formData['alias']);
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasHasBeenEdited')->setStatusSuccess();
        } catch(Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasEditedError')->setStatusError();
        }
    }

}