<?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: 10.09.19
 * Time: 13:06
 * Class ForwarderDataProvider
 */
class ForwarderDataProvider extends BaseDataProvider
{
    public function read()
    {
        $hid = $this->getRequestValue('id');
        $hosting = Hosting::where('id', $hid)->first();
        $this->data['domain'] = $hosting->domain;
    }

    public function create()
    {
        $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']);
            $limit = Helper::forwardingAliasesLimit($params);
            $api = new RestApi($params);
            $forwarders = json_decode(json_encode([$api->getForwarders()]), true);
            $countForwarders = count($forwarders[0]);

            if($countForwarders >= $limit)
            {
                return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasesLimit')->setStatusError();
            }
            $api = new RestApi($params);
            $api->createForwarder(Helper::convertEmailToPunnycode($this->formData['forwarder']), $this->formData['alias']);
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasHasBeenCreated')->setStatusSuccess();
        } catch(Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('forwardingAliasCreatedError')->setStatusError();
        }
    }

    public function update()
    {
    
    }

    public function delete()
    {
    
    }
}
