<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\ChoiceProvider;

use Gls\GlsPoland\DataProvider\ServiceInformationProvider;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CountryRepository;
use PrestaShop\PrestaShop\Core\Form\FormChoiceProviderInterface;

final class ShopDeliveryCountryChoiceProvider implements FormChoiceProviderInterface
{
    private $repository;
    private $infoProvider;
    private $language;

    public function __construct(CountryRepository $repository, ServiceInformationProvider $informationProvider, \Language $language)
    {
        $this->repository = $repository;
        $this->infoProvider = $informationProvider;
        $this->language = $language;
    }

    public function getChoices(): array
    {
        if ([] === $isoCodes = $this->infoProvider->getShopDeliveryAvailableCountries()) {
            return [];
        }

        $choices = [];
        $countries = $this->repository->findBy(['iso_code' => $isoCodes, 'id_lang' => $this->language->id], ['active' => 'DESC', 'id_country' => 'ASC']);

        foreach ($countries as $country) {
            if (isset($choices[$country->iso_code])) {
                continue;
            }

            $choices[$country->iso_code] = $country->name;
        }

        return array_flip($choices);
    }
}
