<?php

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


use ModulesGarden\Servers\ZimbraEmail\App\Http\Admin\ProductConfiguration;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Restrictions\Restriction;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Api;
use ModulesGarden\Servers\ZimbraEmail\App\Traits\ExtensionsCheckerTrait;
use ModulesGarden\Servers\ZimbraEmail\App\UI\Admin\ProductConfiguration\Pages\ConfigForm;
use ModulesGarden\Servers\ZimbraEmail\Core\App\Controllers\Instances\AddonController;
use ModulesGarden\Servers\ZimbraEmail\Core\Traits\OutputBuffer;
use function ModulesGarden\Servers\ZimbraEmail\Core\Helper\di;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Product;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 28.08.19
 * Time: 09:07
 * Class ConfigOptions
 */
class ConfigOptions extends AddonController
{
    use ExtensionsCheckerTrait;
    use OutputBuffer;

    /**
     * @param null $params
     * @return array
     * @throws \Exception
     */
    public function execute($params = null)
    {
        try{

            $this->throwErrorIfServerInvalid();
            $this->throwErrorIfExtensionsInvalid();

            if ($this->getRequestValue('action') === 'module-settings' && !$this->getRequestValue('loadData') )
            {
                if(empty($this->getRequestValue('magic')))
                {
                    return [
                        "configoption" => [
                            "Type" => "",
                            "Description" => $this->getJsCode(),
                        ],
                    ];
                }

                if (isset($_REQUEST['magic']))
                {
                    $this->cleanOutputBuffer();

                    return [ProductConfiguration::class, 'index'];
                }

                return [ProductConfiguration::class, 'index'];

            }
            elseif ($this->getRequestValue('action') === 'save')
            {
                $form = new ConfigForm();
                $form->runInitContentProcess();
                $form->returnAjaxData();
            }
            elseif (($this->getRequestValue('loadData') && $this->getRequestValue('ajax') == '1'))
            {
                return [ProductConfiguration::class, 'index'];
            }

        }catch (\Exception $e)
        {
            //todo log
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * check if server is configured properly
     * @throws \Exception
     */
    protected function throwErrorIfServerInvalid()
    {
        $productId = di('request')->get('id');
        $product = Product::where('id', $productId)->first();
        if(!$product->servergroup)
        {
            throw new \Exception(di('lang')->absoluteT('error', 'invalidServer'));
        }
    }

    /**
     * check if extension is instlled
     * @throws \Exception
     */
    protected function throwErrorIfExtensionsInvalid()
    {
        $extensions = [
            \SoapClient::class => 'soap'
        ];

        foreach($extensions as $class => $extension)
        {
            if(!class_exists($class))
            {
                throw new \Exception(di('lang')->addReplacementConstant('extension', $extension)->absoluteT('error', 'extensionRequired'));
            }
        }

    }
    private function getJsCode()
    {
        $params = array_merge($this->request->request->all(), $this->request->query->all());
        $dataQuery = http_build_query($params);

        return "
                <script>
                    $('#layers').remove();
                    $('.lu-alert').remove();
                    $('#tblModuleSettings').addClass('hidden');
                    $('#tblMetricSettings').before('<img style=\"margin-left: 50%; margin-top: 15px; margin-bottom: 15px; height: 20px\" id=\"mg-configoptionLoader\" src=\"images/loading.gif\">');
                    $.post({
                        url: '{$_SERVER['HTTP_ORIGIN']}{$_SERVER['PHP_SELF']}?$dataQuery&magic=1'
                    })
                    .done(function( data ){
                        
                        var json = JSON.parse(data);
                       
                        $('#mg-configoptionLoader').remove();
                        if ({$this->getRequestValue('servergroup')} == 0)
                        {
                              $('#tblModuleSettings').html(json.content).removeClass('hidden');
                        }
                        else
                        {
                            $('#tblModuleSettings').html(json.content).removeClass('hidden');
                        }
//                        
                    });
                </script>";


    }

}