<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Esb\Helper;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Url;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Exception\CouldNotInvoiceException;
use Magento\Sales\Model\OrderRepository;
use Psr\Log\LoggerInterface;

/**
 * Generic Helper
 */
class Data extends AbstractHelper
{
    /**
     * @var ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * @var LoggerInterface $logger
     */
    protected $_logger;

    /**
     * @var OrderRepositoryInterface $orderRepository
     */
    protected $_orderRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    protected $_searchCriteriaBuilder;

    /**
     * @var Url
     */
    protected $_urlHelper;

    /**
     * Constructor
     *
     * @param ScopeConfigInterface $scopeConfig
     * @param LoggerInterface $logger
     * @param OrderRepository $orderRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param Url $urlHelper
     */
    public function __construct(
        ScopeConfigInterface      $scopeConfig,
        LoggerInterface           $logger,
        OrderRepository           $orderRepository,
        SearchCriteriaBuilder     $searchCriteriaBuilder,
        Url                       $urlHelper
    )
    {
        $this->_scopeConfig = $scopeConfig;
        $this->_logger = $logger;
        $this->_searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_orderRepository = $orderRepository;
        $this->_urlHelper = $urlHelper;
    }

    /**
     * Format endpoint url by replacing base_url tokens.
     *
     * @param string $url
     * @return string
     */
    public function getEndpointUrl($url)
    {
        $endpoint_base_url = $this->_scopeConfig->getValue(
            'esb/endpoints/endpoint_base_url'
        );
        return preg_replace('/\{\{endpoint_base_url\}\}/', $endpoint_base_url, $url);
    }

    /**
     * Format endpoint url by replacing base_url tokens.
     *
     * @param OrderInterface $order
     * @return bool
     */
    public function isTestOrder(
        OrderInterface $order
    )
    {
        if (preg_match("/.*filoblu.com\$/", $order->getCustomerEmail())) {
            $this->_logger->addInfo(
                'TEST ORDER FOUND: ' . $order->getIncrementId() . '. Email: ' . $order->getCustomerEmail());
            return true;
        }

        return false;
    }

    /**
     * @param string|null $orderIncrementId
     * @return \Magento\Framework\DataObject
     * @throws \Magento\Sales\Exception\CouldNotInvoiceException
     */
    public function loadOrderByOrderId($orderIncrementId)
    {
        $searchCriteria = $this->_searchCriteriaBuilder
            ->addFilter('increment_id', $orderIncrementId)->create();
        $orderList = $this->_orderRepository->getList($searchCriteria);

        if (count($orderList) !== 1) {
            $message = __('Cannot find order %1', $orderIncrementId);
            $this->_logger->critical($message);
            throw new CouldNotInvoiceException($message);
        }

        return $orderList->getFirstItem();

    }

    /**
     * @param $document
     * @return string
     */
    public function getPrintUrl($document)
    {
        return $this->_urlHelper->getUrl('esb/invoice/print', ['document' => $document]);
    }

}
