<?php

namespace ModulesGarden\Servers\OpenXchange\App\Http\Actions;

use Exception;
use ModulesGarden\Servers\OpenXchange\App\Libs\OXContext;
use ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use ModulesGarden\Servers\OpenXchange\App\Models\ProductConfiguration;
use ModulesGarden\Servers\OpenXchange\App\Helpers\Repositories\CustomFieldRepository;
use ModulesGarden\Servers\OpenXchange\Core\App\Controllers\Instances\AddonController;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 09.09.19
 * Time: 15:14
 * Class CreateAccount
 */
class CreateAccount extends AddonController
{
    /**
     * create domain in zimbra
     *
     * @param null $params
     * @return string
     */
    public function execute($params = null)
    {
        try
        {
            $config = ProductConfiguration::config($params['packageid']);

            if ($config['own_domains'] == "on")
            {
                $domain = \WHMCS\Domain\Domain::where('domain', $params['domain'])
                    ->where('userid', $params['userid'])
                    ->where('status', 'Active')
                    ->first();

                if (empty($domain->id))
                {
                    throw new Exception('Cannot create context, this product allows to use only existing active domain with the same name as for the service.');
                }
            }
            
            $adminPassword             = uniqid();
            $params['OxAdminPassword'] = $adminPassword;
            $context                   = new RestApi($params);
            $result                    = $context->createContext();

            /*CustomFieldRepository::saveCustomFieldValue(
                $params['serviceid'], $params['packageid'], $result->id, CustomFieldRepository::OX_CONTEXT_CUSTOM_FIELD
            );*/

            CustomFieldRepository::saveCustomFieldValue(
                $params['serviceid'], $params['packageid'], $result->name, CustomFieldRepository::OX_CONTEXT_NAME_FIELD
            );

            $params['model']->serviceProperties->save(['Username' => 'admin-' . $params['domain'], 'Password' => $adminPassword]);

            //$params['customfields']['context_id'] = $result->id;
        }
        catch (\Exception $ex)
        {
            /**
             * return some crit error
             */
            return $ex->getMessage();
        }

        return 'success';
    }
}
