<?php
/**
 * 2018 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of Paysera
 */
namespace Paysera\Service\Provider;

if (!defined('_PS_VERSION_')) {
    exit;
}

use Evp\Component\Money\Money;

class PaymentMethodCountryProvider
{
    /**
     * @param string $projectId
     * @param string $currency
     * @param string $language
     * @param Money $price
     *
     * @return array<int,\WebToPay_PaymentMethodCountry>
     *
     * @throws \WebToPayException
     */
    public function get($projectId, $currency, $language, $price)
    {
        if (empty($projectId) || !is_numeric($projectId)) {
            return [];
        }

        return \WebToPay::getPaymentMethodList((int) $projectId, (int) $price->getAmount(), $currency)
            ->setDefaultLanguage($language)
            ->getCountries()
        ;
    }

    /**
     * @param array<int,\WebToPay_PaymentMethodCountry> $paymentMethodCountries
     * @param $whitelistedCountries
     *
     * @return array<int,\WebToPay_PaymentMethodCountry>
     */
    public function filterByCountryWhitelist(array $paymentMethodCountries, $whitelistedCountries)
    {
        $filteredCountries = [];

        if (count($whitelistedCountries) > 0) {
            $includeOther = false;

            foreach ($whitelistedCountries as $countryCode) {
                if (array_key_exists($countryCode, $paymentMethodCountries)) {
                    $filteredCountries[] = $paymentMethodCountries[$countryCode];
                } else {
                    $includeOther = true;
                }
            }

            if ($includeOther && array_key_exists('other', $paymentMethodCountries)) {
                $filteredCountries[] = $paymentMethodCountries['other'];
            }
        }

        return $filteredCountries;
    }
}
