<?php

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

use function ModulesGarden\Servers\OpenXchange\Core\Helper\di;
use ModulesGarden\Servers\OpenXchange\Core\Traits\OutputBuffer;
use ModulesGarden\Servers\OpenXchange\Core\Models\Whmcs\Product;
use ModulesGarden\Servers\OpenXchange\Core\App\Installer\ModuleInstaller;
use ModulesGarden\Servers\OpenXchange\App\Http\Admin\ProductConfiguration;
use ModulesGarden\Servers\OpenXchange\App\Service\CustomFields\CustomFields;
use ModulesGarden\Servers\OpenXchange\Core\App\Controllers\Instances\AddonController;
use ModulesGarden\Servers\OpenXchange\App\UI\Admin\ProductConfiguration\Pages\ConfigForm;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 28.08.19
 * Time: 09:07
 * Class ConfigOptions
 */
class ConfigOptions extends AddonController
{
    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') && $this->getRequestValue('ajax') == '1'))) {
                try {
                    //run installer
                    $installer = new ModuleInstaller();
                    $installer->makeInstall();
                    //CustomFields::create($_REQUEST['id'], 'context_id|Context ID');
                    CustomFields::create($_REQUEST['id'], 'context_name|Context Name');
                } catch (\Exception $e) {
                    throw new \Exception($e->getMessage());
                }
            }
            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('ajax') == '1')
            {
                return [ProductConfiguration::class, 'index'];
            }

        } catch (\Exception $e)
        {
            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>";


    }

}
