<?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 = $api->getForwarder($this->actionElementId);
        $exploded  = explode('@', $this->actionElementId);
        $alias     = $exploded[0];
        $domain    = $exploded[1];

        $this->data['alias']         = $alias;
        $this->data['domain']        = \WHMCS\Domains\Idna::fromPunycode($domain);
        $this->data['forwarderEdit'] = implode(',' . PHP_EOL, $forwarder->forwardTo);
    }
    public function update()
    {
        $hid                     = $this->getRequestValue('id');
        $hosting                 = Hosting::where('id', $hid)->first();
        $domainPunycode          = \WHMCS\Domains\Idna::toPunycode($hosting->domain);
        $this->formData['alias'] = $this->formData['alias'].'@'.$domainPunycode;

        try
        {
            $params = Helper::moduleParams($_REQUEST['id']);
            $api    = new RestApi($params);
            //$api->updateForwarder(Helper::convertEmailToPunnycode($this->formData['forwarderEdit']), $this->formData['alias']);
            $api->deleteForwarder(Helper::convertEmailToPunnycode($this->formData['alias']));
            $api->createForwarder(Helper::convertEmailToPunnycode($this->formData['forwarderEdit']), $this->formData['alias']);
            
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasHasBeenEdited')->setStatusSuccess();
        }
        catch(Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasEditedError')->setStatusError();
        }
    }

}