<?php

namespace FiloBlu\Flow\Model\Actions\From;

use Exception;
use Magento\Store\Model\StoreRepository;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Customer\Model\ResourceModel\Group\Collection;
use Magento\Customer\Api\CustomerRepositoryInterface;

/**
 * Class Addtocustomergroup
 * @package FiloBlu\Flow\Model\Actions\From
 */
class Addtocustomergroup
{
    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;
    /**
     * @var Collection
     */
    protected $customerGroupColl;
    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepositoryInterface;


    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param Collection $customerGroupColl
     * @param CustomerRepositoryInterface $customerRepositoryInterface
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Collection $customerGroupColl,
        CustomerRepositoryInterface $customerRepositoryInterface
    )
    {
        $this->scopeConfig = $scopeConfig;
        $this->customerGroupColl = $customerGroupColl;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
    }


    /**
     * @param $customer
     * @param $value
     * @param $storeId
     * @param $channelConfig
     * @return void
     * @throws Exception
     */
    public function process($customer, $value, $storeId, $channelConfig)
    {
        if(!$value || !$customer->getId()) {
            throw new Exception('Empty customer group');
        }

        foreach($value as $arrayIndex => $actionData) {
            $groupValue = trim($actionData['value'] ?? '');
        }

        $groupId = $groupValue;
        if(!is_numeric($groupId)) {
            $groupId = $this->getCustomerGroupId($groupId);
        }

        if(!$groupId) {
            throw new Exception('customer group not found');
        }

        $customer->setGroupId($groupId);
        $customer->save();
    }

    /**
     * @param $group
     * @return false|int|mixed|string
     */
    protected function getCustomerGroupId($group) {
        $customerGroups = $this->customerGroupColl->toOptionArray();
        foreach ($customerGroups as $groupId => $groupName) {
            if(!is_numeric($group)) {
                if(strtolower($group) == strtolower($groupName['label'])) {
                    return $groupName['value'];
                }
            }
            else {
                if($group == $groupId) {
                    return $groupId;
                }
            }
        }
        return false;
    }
}
