<?php

namespace Opencart\Extension\Alsendo\Handlers;

use Opencart\Extension\Alsendo\Repositories\ConfigRepository;

class ConfigHandler
{
    private ConfigRepository $repository;
    private array $allowedRegions = ['poland', 'czechia', 'romania'];

    public function __construct(ConfigRepository $repository)
    {
        $this->repository = $repository;
    }

    public function saveRegion(string $region): array
    {
        if (empty($region)) {
            return ['error' => 'No region provided'];
        }

        if (!in_array($region, $this->allowedRegions)) {
            return ['error' => 'Invalid region selected'];
        }

        try {
            $this->repository->saveRegion($region);
            return ['success' => 'Region saved successfully'];
        } catch (\Exception $e) {
            return ['error' => 'Failed to save region: ' . $e->getMessage()];
        }
    }

    public function saveApiConfig(array $apiConfig): array
    {
        $config = $this->repository->getConfig();
        $requiredFields = $config->getRequiredFields();

        foreach ($requiredFields as $field) {
            if (!isset($apiConfig[$field]) || $apiConfig[$field] === '') {
                return ['error' => ucfirst(str_replace('_', ' ', $field)) . ' is required'];
            }
        }

        try {
            $this->repository->saveApiConfig($apiConfig);
            return ['success' => 'API configuration saved successfully'];
        } catch (\Exception $e) {
            return ['error' => 'Failed to save API configuration: ' . $e->getMessage()];
        }
    }

    public function saveApiKeys(string $appId, string $appSecret): array
    {
        return $this->saveApiConfig(['app_id' => $appId, 'app_secret' => $appSecret]);
    }
} 