<?php

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

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

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 18.09.19
 * Time: 11:28
 * Class DeleteAccountDataProvider
 */
class CancelRequestDataProvider extends BaseDataProvider
{

    public function read()
    {
        $this->data['id'] = $this->actionElementId;
    }

    public function update()
    {
    }

    public function delete()
    {
        try
        {
            //get the proper cancellation request
            $requestId   = $this->formData['id'];
            $requestData = MailboxDeleteList::where('id', '=', $requestId)->where('service_id', '=', $this->request->getValue('id'))->first();

            if (empty($requestData))
            {
                throw new Exception('Cancellation Request Not Found!');
            }

            $params         = Helper::moduleParams($this->request->getValue('id'));
            $context        = new RestApi($params);
            $userIdPunycode = Helper::convertEmailToPunnycode(strip_tags(html_entity_decode($requestData->mailbox_name)));

            $context->unsuspendUser($userIdPunycode);

            MailboxDeleteList::where('id', '=', $requestId)->where('service_id', '=', $this->request->getValue('id'))->delete();

            return (new HtmlDataJsonResponse())->setMessageAndTranslate('deleteRequestCancelled')->setStatusSuccess();
        }
        catch(Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate($e->getMessage())->setStatusError();
        }
    }
}
