<?php
namespace Opencart\Extension\Alsendo\Handlers\Region;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/Entity/AlsendoRegionEntity.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/ConfigRepository.php');

use Opencart\Extension\Alsendo\DTO\Entity\AlsendoRegionEntity;
use Opencart\Extension\Alsendo\Repositories\ConfigRepository;
use Opencart\System\Engine\Registry;

class RegionHandler
{
    private Registry $registry;
    private ConfigRepository $configRepository;

    public function __construct(Registry $registry, ConfigRepository $configRepository)
    {
        $this->registry = $registry;
        $this->configRepository = $configRepository;
    }

    public function syncRegion(string $region): void
    {
        $this->configRepository->saveRegion($region);


        $this->registry->load->model('extension/alsendo/module/alsendo_region');
        $this->registry->load->model('localisation/currency');

        /** @var AlsendoRegionEntity $currentRegion */
        $selectedRegion = $this->registry->model_extension_alsendo_module_alsendo_region->getRegionByCode($region);

        if (!$selectedRegion) {
            throw new \Exception('Invalid region or region not supported');
        }

        $this->registry->model_extension_alsendo_module_alsendo_region->setRegionByCode($region);

        /** @var AlsendoRegionEntity $currentRegion */
        $currentRegion = $this->registry->model_extension_alsendo_module_alsendo_region->getCurrentRegion();
        $newRegionCurrency = $this->registry->model_localisation_currency->getCurrency($currentRegion->currencyId);

        $this->configRepository->upsert('config', 'config_currency', $newRegionCurrency['code']);
    }
} 