<?php
    
    namespace frontend\widgets;
    
    use artbox\catalog\models\Variant;
    use artbox\catalog\models\VariantOptionExcl;
    use artbox\catalog\models\VariantOptionGroupExcl;
    
    class VariantGroupHelper
    {
        protected $groups = [];
        
        public function addGroup(VariantOptionGroupExcl $group)
        {
            if (!array_key_exists($group->id, $this->groups)) {
                $this->groups[ $group->id ][ 'group' ] = $group;
                $this->groups[ $group->id ][ 'options' ] = new VariantOptionHelper();
            }
        }
        
        public function addOption(VariantOptionExcl $option)
        {
            if (empty($this->groups[ $option->groupId ])) {
                $this->addGroup($option->variantOptionGroupExcl);
            }
            /**
             * @var \frontend\widgets\VariantOptionHelper $variantOptionHelper
             */
            $variantOptionHelper = $this->groups[ $option->groupId ][ 'options' ];
            $variantOptionHelper->addOption($option);
        }
        
        public function addVariant(Variant $variant)
        {
            $options = $variant->variantOptionExcls;
            foreach ($options as $option) {
                $this->addOption($option);
                $variantContainer = $this->getVariantContainer($option);
                $variantContainer->addVariant($variant);
            }
        }
        
        public function getVariantContainer(VariantOptionExcl $option)
        {
            /**
             * @var \frontend\widgets\VariantOptionHelper $variantOptionHelper
             */
            $variantOptionHelper = $this->groups[ $option->groupId ][ 'options' ];
            return $variantOptionHelper->getVariantContainer($option);
        }
        
        public function getGroups()
        {
            return $this->groups;
        }
    }