<?php

namespace ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Pages\Sections;


use ThurData\Servers\KerioEmail\App\Enums\ProductParams;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\Services\ConfigurableOptions\Strategy\ConfigOptionsType;
use ThurData\Servers\KerioEmail\App\UI\Admin\Custom\Sections\BoxSectionExtended;
use ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Buttons\CreateConfigurableOptionsBaseModalButton;
use ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Helper\ConfigurableOptionsBuilder;
use ThurData\Servers\KerioEmail\App\Traits\KerioApiHandler;
use ThurData\Servers\KerioEmail\App\UI\Admin\ProductConfiguration\Providers\ConfigurableOptionManager;
use ThurData\Servers\KerioEmail\Core\UI\Interfaces\AdminArea;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\Sections\BoxSection;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 29.08.19
 * Time: 08:32
 * Class ConfigurableOptionsSection
 */
class ConfigurableOptions extends BoxSectionExtended implements AdminArea
{
    protected $id       = 'configurableOptions';
    protected $name     = 'configurableOptions';
    protected $title    = 'configurableOptions';

    use KerioApiHandler;

    public function initContent()
    {

        $this->addButton(new CreateConfigurableOptionsBaseModalButton());
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function getOptions()
    {
        /**
         * product id
         */
        $productId = $this->getRequestValue('id');

        /**
         * product manager
         */
        $productManager = new ProductManager();
        $productManager
            ->loadById($productId);

        /**
         * config options strategy
         */
        $options = new ConfigOptionsType();
        $options->setProductId($productId);
        $options->load();

        /**
         * config option model
         */
        $configurableOptions = new \ThurData\Servers\KerioEmail\App\Services\ConfigurableOptions\ConfigurableOptions($productId);

        /**
         * build co to show
         */
        ConfigurableOptionsBuilder::buildAll($configurableOptions, $options->getConfigurableOptions());

        /**
         *
         */
        $fields = $configurableOptions->show();

        /**
         *
         * add additional elements,
         * resolve none full line issue (#156)
         */
        $limit = count($fields) % 3;

        if($limit > 0)
        {
            while($limit < 3)
            {
                $fields['emptyFields'.$limit] = '-1';
                $limit++;
            }
        }


        return $fields;
    }
}