<?php

namespace ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Providers;

use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Enums\Size;
use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use ThurData\Servers\KerioEmail\App\Helpers\KerioManager;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Repository\ClassOfServices;
use ThurData\Servers\KerioEmail\App\Traits\LangHandler;
use ThurData\Servers\KerioEmail\App\Traits\ServerParams;
use ThurData\Servers\KerioEmail\App\Traits\KerioApiHandler;
use ThurData\Servers\KerioEmail\Core\App\Controllers\Interfaces\AdminArea;
use ThurData\Servers\KerioEmail\Core\Traits\Lang;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use \ThurData\Servers\KerioEmail\App\Models\ProductConfiguration;
use ThurData\Servers\KerioEmail\App\Libs\Migrations\Drivers\Version1To2;
use \Illuminate\Database\Capsule\Manager as DB;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 29.08.19
 * Time: 10:27
 * Class ProductConfigurationDataProvider
 */
class ProductConfigurationDataProvider extends BaseDataProvider implements AdminArea
{

    const FORM_DATA = [
        'acc_limit',
        'acc_base',
        'alias_limit',
        'login_link',
        'acc_size',
        'domain_alias_limit',
        'dist_list_limit',
        'domainMaxSize',
        'domainBaseSize',
        'outlook_connector',
        'spf_string',
        'dmarc_string',
        'ca_emailAccountPage',
        'ca_ressourcePage',
        'ca_distributionListPage',
        'ca_goToWebmailPage',
        'ca_emailAliasesPage',
        'ca_domainAliasesPage',
        'ca_settingPage',
        'ca_logInToMailboxButton',
    ];

    const FILED_NOT_UPDATED = [
        'login_link'
    ];

    use LangHandler;

    /**
     *
     */
    public function read()
    {
        /**
         * load params from previous version
         */
        $this->checkConfigOrLoadFromPrevious($this->getRequestValue('id'));

        $this->loadDefaultData();
        $this->overrideDefaultDataByProductConfig();
    }

    /**
     *
     */
    public function update()
    {
        $this->catchFormData();
        $productId = $this->request->get('id');

        foreach ($this->formData as $key => $value)
        {
            ProductConfiguration::updateOrCreate(['product_id' => $productId, 'setting' => $key], ['value' => $value]);
        }
    }

    /**
     *
     */
    protected function loadDefaultData()
    {
        /* default data */
        $this->data['acc_limit']          = Size::DEFAULT_ACC_LIMIT;
        $this->data['acc_base']           = Size::DEFAULT_ACC_BASE;
        $this->data['acc_size']           = Size::DEFAULT_ACC_SIZE;
        $this->data['alias_limit']        = Size::DEFAULT_ALIAS_LIMIT;
        $this->data['domain_alias_limit'] = Size::DEFAULT_DOMAIN_ALIAS_LIMIT;
        $this->data['dist_list_limit']    = Size::DEFAULT_DIST_ALIAS_LIMIT;
        $this->data['outlook_connector']  = Kerio::ATTR_DISABLED;
        $this->data['login_link']         = Kerio::DEFAULT_LOGIN_LINK;
        $this->data['domainMaxSize']      = Size::UNLIMITED;
        $this->data['domainBaseSize']     = Size::UNLIMITED;
    }

    /**
     * @description load data from database
     */
    protected function overrideDefaultDataByProductConfig()
    {
        $settings = ProductConfiguration::where('product_id', $this->request->get('id'))->get();

        foreach ($settings as $setting)
        {
            $this->data[$setting->setting] = $setting->value;
        }
    }

    /**
     * @description catch params from request
     */
    protected function catchFormData()
    {
        /**
         * catch from request
         */
        $params = array_merge(Kerio::BASE_ACCOUNT_CONFIG,self::FORM_DATA);

        foreach ($params as $name)
        {
            if ($value = $this->request->get($name))
            {
                $this->formData[$name] = $value;
            }elseif(!in_array($name,self::FILED_NOT_UPDATED)){
                $this->formData[$name] = ProductParams::SWITCHER_DISABLED;
            }else{
                $this->formData[$name] = '';
            }
        }
    }


    private function checkConfigOrLoadFromPrevious($id)
    {

        if(ProductConfiguration::where('product_id', $id)->first())
        {
            return;
        }
        $migration = new Version1To2\Settings();

        $exists = DB::schema()->hasTable($migration->getFromTable());
        if(!$exists)
        {
            return;
        }

        $previous = DB::table($migration->getFromTable())->where('product_id', $id)->get();

        /**
         *
         */
        $prodManager = new ProductConfiguration();

        /**
         *
         * storage all params per product id
         */
        foreach($previous as $setting)
        {
            $settings[$setting->product_id][$setting->setting] = $setting->value;
            $products[] = $setting->product_id;
        }

        /**
         *
         * update setting data & save
         */
        foreach($settings as $prodId => $settingsArray)
        {
            $attrs = $migration->updateValues($settingsArray, $prodId);

            foreach($attrs as $key => $value)
            {
                $prodManager->updateOrCreate(['product_id' => $prodId, 'setting' => $key],['value' => $value]);
            }
        }

        /**
         *
         * new options
         */
        foreach($migration->getNewFields() as $key => $value)
        {

            $prodManager->updateOrCreate(['product_id' => $id, 'setting' => $key],['value' => $value]);
        }

    }
}