<?php
/**
 * Class ConfigurableOptionManager
 * User: ThurData
 * Date: 2019-09-29
 * Time: 15:33
 * @package ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Providers
 */

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


use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Services\ConfigurableOptions\ConfigurableOptions;
use ThurData\Servers\KerioEmail\App\Services\ConfigurableOptions\Strategy\ConfigOptionsType;
use ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Helper\ConfigurableOptionsBuilder;
use ThurData\Servers\KerioEmail\Core\UI\Interfaces\AdminArea;
use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

class ConfigurableOptionManager extends BaseDataProvider implements AdminArea
{
    public function read()
    {
        $productId = $this->getRequestValue('id');

        $productManager = new ProductManager();
        $productManager
            ->loadById($productId);

        $options = new ConfigOptionsType();
        $options->setProductId($productId);
        $options->load();

        $configurableOption = new ConfigurableOptions($productId);
        ConfigurableOptionsBuilder::buildAll($configurableOption, $options->getConfigurableOptions());

        $this->data         = [
            'fields' => $configurableOption->show()
        ];
    }

    /**
     * @return HtmlDataJsonResponse|void
     */
    public function create()
    {
        $productId = $this->getRequestValue('id');

        try
        {
            $productManager = new ProductManager();
            $productManager
                ->loadById($productId);

            $options = new ConfigOptionsType();
            $options->setProductId($productId);
            $options->load();

            $configurableOption = new ConfigurableOptions($productId);

            ConfigurableOptionsBuilder::build($configurableOption, $this->formData, $options->getConfigurableOptions());
            $status             = $configurableOption->createOrUpdate();

            $msg                = ($status) ? 'configurableOptionsCreate' : 'configurableOptionsUpdate';
            return (new HtmlDataJsonResponse())
                ->setStatusSuccess()
                ->setCallBackFunction('redirectToConfigurableOptionsTab')
                ->setMessageAndTranslate($msg);
        }
        catch (\Exception $ex)
        {
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessage($ex->getMessage());
        }
    }

    public function delete()
    {

    }

    public function update()
    {

    }
}