<?php

namespace inpost_shipping\Model\Expander;

use inpost_shipping\InpostConfig;

class InpostShippingMethodExpander
{
    /**
     * @param array $deliveryServices
     *
     * @return array
     */
    public function expandDeliveryServices(array $deliveryServices): array
    {
        $keysToUnset = [];
        foreach ($deliveryServices as $serviceKey => $service) {
            if (!isset(InpostConfig::SENDING_METHOD_SERVICES[$service['id']])) {
                $keysToUnset[] = $serviceKey;
                continue;
            }
            $deliveryServices[$serviceKey]['shippingMethods'] = InpostConfig::SENDING_METHOD_SERVICES[$service['id']];
        }

        foreach ($keysToUnset as $key) {
            unset($deliveryServices[$key]);
        }

        return $this->translateDeliveryServices($deliveryServices);
    }

    /**
     * @param array $deliveryServices
     *
     * @return array
     */
    protected function translateDeliveryServices(array $deliveryServices): array
    {
        foreach ($deliveryServices as $serviceKey => $service) {
            if (isset(InpostConfig::DELIVERY_SERVICES_TRANSLATION[$serviceKey])) {
                $deliveryServices[$serviceKey]['name'] = InpostConfig::DELIVERY_SERVICES_TRANSLATION[$serviceKey];
                $deliveryServices[$serviceKey]['description'] = InpostConfig::DELIVERY_SERVICES_TRANSLATION[$serviceKey];
            }
        }

        return $deliveryServices;
    }

    /**
     * @param array $request
     *
     * @return array
     */
    public function transformRequest(array $request): array
    {
        if (!isset($request['handling_costs'])) {
            $request['handling_costs'] = 0;
        }

        if (!isset($request['free_shipping'])) {
            $request['free_shipping'] = 0;
        }

        foreach ($request['ranges'] as $k => $range) {
            if (!isset($range['status'])) {
                $request['ranges'][$k]['status'] = "0";
            }
        }

        return $request;
    }
}