<?php

namespace Extension\CbUtilityPackage;

use Application\Config;
use Application\Session;

class SwitchConfig extends Common
{
    public function __construct()
    {
        parent::__construct();
        $this->preserveConfigUpsells = Config::extensionsConfig('CbUtilityPackage.preserve_config_upsells');
        $this->configurationMapping  = Config::extensionsConfig('CbUtilityPackage.configuration_mapping');
        $this->PageType              = Session::get('steps.current.pageType');
    }

    public function switchConfig()
    {        
        if($this->PageType == 'leadPage' || $this->PageType == 'checkoutPage' || empty($this->preserveConfigUpsells))        {
            return;
        }
        
        $currentStepId    = (int) Session::get('steps.current.id');
        $previousConfigId = (int) Session::get('steps.previous.configId');

        foreach ($this->configurationMapping as $configurationMapping) {
            if (
                !empty($configurationMapping[0]) &&
                (int) $configurationMapping[0] == $previousConfigId
            ) {
                Session::set(
                    'steps.current.configId', (int) $configurationMapping[1]
                );
                Session::set(
                    sprintf('steps.%d.configId', $currentStepId),
                    (int) $configurationMapping[1]
                );
                return;
            }
        }        
    }
}