<?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
 */

declare(strict_types=1);

namespace Paysera\Delivery\Model;

use Paysera\Delivery\PayseraDeliveryCarriers;

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

use Carrier;
use Configuration;

class PayseraShippingGatewayModel implements PayseraShippingGatewayModelInterface
{
    /**
     * @var PayseraDeliveryCarriers
     */
    private $deliveryCarriers;

    public function __construct(PayseraDeliveryCarriers $deliveryCarriers)
    {
        $this->deliveryCarriers = $deliveryCarriers;
    }

    public function findIdByGatewayCode(string $deliveryGatewayCode): ?int
    {
        $activeCarriers = Carrier::getCarriers(
            (int) Configuration::get('PS_LANG_DEFAULT'),
            true,
            false,
            false,
            null,
            PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
        );

        foreach ($activeCarriers as $activeCarrier) {
            $activeCarrierCode = $this->getGatewayCodeFromCarrierInfo((int)$activeCarrier['id_carrier']);
            if ($activeCarrierCode !== null && $activeCarrierCode === $deliveryGatewayCode) {
                return (int)$activeCarrier['id_carrier'];
            }
        }

        return null;
    }

    private function getGatewayCodeFromCarrierInfo(int $carrierId): ?string
    {
        $carrierInfo = $this->deliveryCarriers->getCarrierById($carrierId);

        return $carrierInfo !== null
            ?  sprintf('%s_%s', $carrierInfo['code'], $carrierInfo['type'])
            : null;
    }
}
