<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\EmailAccount\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 DeleteAccountDataProvider extends BaseDataProvider
{

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

    public function update()
    {
    }

    public function delete()
    {
        try
        {
            $params         = Helper::moduleParams($this->request->getValue('id'));
            $context        = new RestApi($params);
            $userIdPunycode = Helper::convertEmailToPunnycode(strip_tags(html_entity_decode($this->formData['id'])));

            if ($this->formData['daysToDelete'] == '')
            {
                throw new Exception('Please Provide A Numeric Value');
            }

            //check if 0 was provided in the input. If yes delete the mailbox now. If no create the delete request (soft delete)
            $daysToDelete = intval($this->formData['daysToDelete']);

            if ($daysToDelete === 0)
            {
                $result = $context->deleteUser($userIdPunycode);

                if($result == '')
                {
                    return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountHasBeenDeleted')->setStatusSuccess();
                }
                else
                {
                    return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountsDeleteError')->setStatusError();
                }
            }
            elseif ($daysToDelete > 0)
            {
                //check if delete request already exists. If yes show the proper erorr message
                $deleteRequestExists = MailboxDeleteList::where('mailbox_name', '=', $userIdPunycode)->exists();

                if ($deleteRequestExists)
                {
                    throw new Exception('Delete request for this mailbox already exists!!');
                }

                //suspend user and create a proper record in the database
                $context->suspendUser($userIdPunycode);

                MailboxDeleteList::insert([
                    'service_id'     => $this->request->getValue('id'),
                    'mailbox_name'   => $userIdPunycode,
                    'days_to_delete' => $daysToDelete
                ]);
            }
            else
            {
                throw new Exception('Incorrect value in the "Deletion in days" field!');
            }
        }
        catch(Exception $e)
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate($e->getMessage())->setStatusError();
        }
    }
}
