<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 19/04/19
 * Time: 8.13
 */

namespace FiloBlu\Rma\Handlers;

use Exception;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 *
 */
class CustomCarrierHandler
{
    /** @var string */
    const RMA_CUSTOM_CARRIER = 'filoblu_disablerma_section/rma_group/rma_option_carrier';

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * AddCustomCarrier constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param LoggerInterface $logger
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        LoggerInterface $logger
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->logger = $logger;
    }

    /**
     * @param $result
     * @return array
     */
    public function getShippingCarriers($result)
    {
        try {
            if ($this->scopeConfig->getValue(self::RMA_CUSTOM_CARRIER) ?? false) {
                if (isset($_POST['carrier']) && $_POST['carrier'] === 'custom') {
                    $result = array_merge($result, ['custom' => $_POST['carrier']]);
                } else {
                    $result['custom'] = 'Custom';
                }
            }
            return $result;
        } catch (Exception $exception) {
            $this->logger->critical($exception->getMessage(), ['exception' => $exception]);
            return $result;
        } catch (Throwable $throwable) {
            $this->logger->critical($throwable->getMessage(), ['exception' => $throwable]);
            return $result;
        }
    }
}
