<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\UI\Admin\ProductConfiguration\Pages\Sections;


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

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * 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 ZimbraApiHandler;

    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->setType($productManager->get(ProductParams::CLASS_OF_SERVICE_NAME));
        $options->setProductId($productId);
        $options->load();
        ;

        /**
         * config option model
         */
        $configurableOptions = new \ModulesGarden\Servers\ZimbraEmail\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;
    }
}