<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Client\EmailAccount\Providers;


use ModulesGarden\Servers\ZimbraEmail\App\Enums\Zimbra;
use ModulesGarden\Servers\ZimbraEmail\App\Helpers\ZimbraManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Product\ProductManager;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\Account;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Models\ClassOfService;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Repository\ClassOfServices;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Response;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Services\Update\UpdateAccount;
use ModulesGarden\Servers\ZimbraEmail\App\Services\ConfigurableOptions\Strategy\Types\ClassOfServicesOptions;
use function ModulesGarden\Servers\ZimbraEmail\Core\Helper\di;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 18.09.19
 * Time: 09:35
 * Class EditAccountDataProvider
 */
class EditAccountDataProvider extends BaseDataProvider
{

    /**
     *
     */
    public function read()
    {
        /**
         * hosting id
         */
        $hid = $this->getRequestValue('id');
        /**
         * load hosting
         */
        $hosting = Hosting::where('id', $hid)->first();

        /**
         * load api
         */
        $api = (new ZimbraManager())->getApiByServer($hosting->server);

        $repository = new Repository($api->soap);

        $result = $repository->accounts->getAccountOptionsById($this->actionElementId);

        if($result instanceof Response && $result->getLastError())
        {
            throw new \Exception($result->getLastError());
        }

        $mailBoxParams              = explode('@', $result->getName());
        $this->data['id']           = $result->getId();
        $this->data['username']     = $mailBoxParams[0];
        $this->data['domain']       = $mailBoxParams[1];
        $this->data['firstname']    = $result->getDataResourceA(Account::ATTR_FIRSTNAME);
        $this->data['lastname']     = $result->getDataResourceA(Account::ATTR_LASTNAME);
        $this->data['display_name'] = $result->getDataResourceA(Account::ATTR_DISPLAY_NAME);
        $this->data['status']       = $result->getDataResourceA(Account::ATTR_ACCOUNT_STATUS);
        $this->data['company']      = $result->getDataResourceA(Account::ATTR_COMPANY);
        $this->data['title']        = $result->getDataResourceA(Account::ATTR_PROF_TITLE);
        $this->data['phone']        = $result->getDataResourceA(Account::ATTR_PHONE);
        $this->data['home_phone']   = $result->getDataResourceA(Account::ATTR_HOME_PHONE);
        $this->data['mobile_phone'] = $result->getDataResourceA(Account::ATTR_MOBILE_PHONE);
        $this->data['fax']          = $result->getDataResourceA(Account::ATTR_FAX);
        $this->data['pager']        = $result->getDataResourceA(Account::ATTR_PAGER);
        $this->data['country']      = $result->getDataResourceA(Account::ATTR_COUNTRY);
        $this->data['city']         = $result->getDataResourceA(Account::ATTR_CITY);
        $this->data['street']       = $result->getDataResourceA(Account::ATTR_STREET);
        $this->data['post_code']    = $result->getDataResourceA(Account::ATTR_POSTAL_CODE);
        $this->data['currentCosId'] = $result->getDataResourceA(Account::ATTR_CLASS_OF_SERVICE_ID);
        $this->data['cosId']        = $result->getDataResourceA(Account::ATTR_CLASS_OF_SERVICE_ID);
        $this->data['state']        = $result->getDataResourceA(Account::ATTR_STATE);

        $lang = di('lang');
        $this->availableValues['status'] = [
            Zimbra::ACC_STATUS_ACTIVE        => $lang->absoluteT('zimbra','account','status','active'),
            Zimbra::ACC_STATUS_LOCKED        => $lang->absoluteT('zimbra','account','status','locked'),
            Zimbra::ACC_STATUS_MAINTENANCE   => $lang->absoluteT('zimbra','account','status','maintenance'),
            Zimbra::ACC_STATUS_CLOSED        => $lang->absoluteT('zimbra','account','status','closed'),
            Zimbra::ACC_STATUS_LOCKOUT       => $lang->absoluteT('zimbra','account','status','lockout'),
            Zimbra::ACC_STATUS_PENDING       => $lang->absoluteT('zimbra','account','status','pending')
        ];

        $this->readCosParams();

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function update()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');


        $fieldToProtection = ['firstname', 'lastname', 'display_name', 'company', 'title', 'country', 'state', 'city', 'street', 'post_code' ];

        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->updateAccount($productManager->get('cos_name'));
        /**
         *
         * set product manager & form data to service
         */
        $service
            ->setProductManager($productManager)
            ->setFormData($this->formData);


        /**
         * run service
         */
        $result = $service->run();

        /**
         * return success or error response
         */
        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessage($service->getError())->setStatusError();
        }

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountHasBeenUpdated')->setStatusSuccess();
    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function updateStatus()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->updateAccountStatus()
            ->setProductManager($productManager)
        ;
        /**
         *
         * set product manager & form data to service
         */

        /**
         * run service for each id
         */
        $service->setFormData($this->formData);
        $result = $service->run();

        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessage($service->getError())->setStatusError();
        }

        /**
         * return success
         */
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('emailAccountStatusHasBeenUpdated')->setStatusSuccess();

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function changePassword()
    {
        /**
         * hosting id
         */
        $hid = $this->request->get('id');

        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);

        /**
         *
         * get soap create domain  service
         */
        $service =(new ZimbraManager())
            ->getApiByHosting($hid)
            ->soap
            ->service()
            ->updateAccountPassword()
            ->setProductManager($productManager)
        ;
        /**
         *
         * set product manager & form data to service
         */

        /**
         * run service for each id
         */
        $service->setFormData($this->formData);
        $result = $service->run();

        if(!$result)
        {
            return (new HtmlDataJsonResponse())->setMessage($service->getError())->setStatusError();
        }

        return (new HtmlDataJsonResponse())->setMessageAndTranslate('passwordChangedSuccessfully')->setStatusSuccess();
    }

    /**
     *
     */
    public function readCosParams()
    {
        $hid = $this->getRequestValue('id');
        /**
         * product manager allow to check product settings
         */
        $productManager = new ProductManager();
        $productManager->loadByHostingId($hid);
        if($productManager->get('cos_name') === ClassOfServices::CLASS_OF_SERVICE_QUOTA)
        {
            /**
             *
             * get soap create domain  service
             */
            $api =(new ZimbraManager())
                ->getApiByHosting($hid)
                ->soap;

            /**
             *
             * get cos from API
             */
            $classOfServices = $api->repository()->cos->all();

            /**
             *
             * load configurable options coses
             */
            $supportedCos = $productManager->getSettingCos();

            /**
             *
             * add COS to array
             */
            $configoptions = $this->getFilteredCosConfigurableOptions();
            foreach($classOfServices as $cos)
            {
                /**
                 *
                 *
                 * skip COS which is not used in configurable options
                 */
                if(!($supportedCos && array_key_exists($cos->getId(), $supportedCos)))
                {
                    continue;
                }

                /**
                 *
                 * skip if class of services doesnt exists in config option list
                 */
                if($configoptions && !array_key_exists('cosQuota_'.$cos->getId(), $configoptions))
                {
                    continue;
                }

                /**
                 * skip not purchased as CO
                 */
                if ($configoptions && $configoptions['cosQuota_'.$cos->getId()] == 0)
                {
                    continue;
                }

                /**
                 * 1. check if config opts are not available
                 * 2. skip if quantity === 0
                 */
                if(!$configoptions && $supportedCos[$cos->getId()] == 0)
                {
                    continue;
                }


                /* @var $cos ClassOfService*/
                $this->availableValues['cosId'][$cos->getId()] = $cos->getMbMailQuote().' MB';
            }
        }

    }

    /**
     * @return bool|mixed
     */
    protected function getFilteredCosConfigurableOptions()
    {
        $configoptions = $this->getWhmcsParamByKey('configoptions');

        foreach($configoptions as $key => $value)
        {
            if(strpos($key, ClassOfServicesOptions::COS_CONFIG_OPT_PREFIX) === false)
            {
                unset($configoptions[$key]);
            }

        }

        return $configoptions;
    }

}