<?php
namespace Autogedal\Retur\Block\Customer;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Customer\Model\Session;
use Autogedal\Retur\Model\ReturRepository;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Psr\Log\LoggerInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Autogedal\Retur\Ui\Component\Listing\Column\Status\Options as StatusOptions;

class View extends Template
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $coreRegistry = null;

    /**
     * @var Session
     */
    protected $customerSession;

    /**
     * @var ReturRepository
     */
    protected $returRepository;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var OrderCollectionFactory
     */
    protected $orderCollectionFactory;

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

    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resource;

    /**
     * @var StatusOptions
     */
    protected $statusOptions;

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param ReturRepository $returRepository
     * @param RequestInterface $request
     * @param Registry $registry
     * @param OrderCollectionFactory $orderCollectionFactory
     * @param LoggerInterface $logger
     * @param \Magento\Framework\App\ResourceConnection $resource
     * @param StatusOptions $statusOptions
     * @param array $data
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        ReturRepository $returRepository,
        RequestInterface $request,
        Registry $registry,
        OrderCollectionFactory $orderCollectionFactory,
        LoggerInterface $logger,
        \Magento\Framework\App\ResourceConnection $resource,
        StatusOptions $statusOptions,
        array $data = []
    ) {
        $this->customerSession = $customerSession;
        $this->returRepository = $returRepository;
        $this->request = $request;
        $this->coreRegistry = $registry;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->logger = $logger;
        $this->resource = $resource;
        $this->statusOptions = $statusOptions;
        parent::__construct($context, $data);
    }

    /**
     * Get current return
     *
     * @return \Autogedal\Retur\Api\Data\ReturInterface|null
     */
    public function getReturn()
    {
        if ($this->coreRegistry->registry('current_retur')) {
            return $this->coreRegistry->registry('current_retur');
        }

        $returId = $this->request->getParam('id');
        if (!$returId) {
            return null;
        }

        try {
            $retur = $this->returRepository->getById($returId);

            if (!$this->isReturBelongsToCustomer($retur)) {
                return null;
            }

            $this->coreRegistry->register('current_retur', $retur);
            return $retur;
        } catch (NoSuchEntityException $e) {
            return null;
        } catch (\Exception $e) {
            $this->logger->critical($e);
            return null;
        }
    }

    /**
     * Check if return belongs to customer
     *
     * @param \Autogedal\Retur\Api\Data\ReturInterface $retur
     * @return bool
     */
    private function isReturBelongsToCustomer($retur)
    {
        try {
            $connection = $this->resource->getConnection();
            $select = $connection->select()
                ->from(
                    ['so' => $this->resource->getTableName('sales_order')],
                    ['customer_id']
                )
                ->where('so.user_increment_id = ?', $retur->getUserIncrementId());

            $result = $connection->fetchOne($select);

            return $result == $this->customerSession->getCustomerId();
        } catch (\Exception $e) {
            $this->logger->critical($e);
            return false;
        }
    }

    /**
     * Get related order
     *
     * @return \Magento\Sales\Model\Order|null
     */
    public function getOrder()
    {
        $retur = $this->getReturn();
        if (!$retur) {
            return null;
        }

        try {
            $orderCollection = $this->orderCollectionFactory->create();
            $orderCollection->addFieldToFilter('user_increment_id', $retur->getUserIncrementId());
            $orderCollection->setPageSize(1);

            if ($orderCollection->getSize() > 0) {
                return $orderCollection->getFirstItem();
            }

            return null;
        } catch (\Exception $e) {
            $this->logger->critical($e);
            return null;
        }
    }

    /**
     * Get order view URL
     *
     * @return string
     */
    public function getOrderViewUrl()
    {
        $order = $this->getOrder();
        if ($order && $order->getId()) {
            return $this->getUrl('sales/order/view', ['order_id' => $order->getId()]);
        }
        return '#';
    }

    /**
     * Get status label
     *
     * @param int $statusId
     * @return string
     */
    public function getStatusLabel($statusId)
    {
        $options = $this->statusOptions->toOptionArray();
        foreach ($options as $option) {
            if ($option['value'] == $statusId) {
                return $option['label'];
            }
        }
        return '';
    }

    /**
     * Get return history items
     *
     * @return \Autogedal\Retur\Api\Data\ReturStatusHistoryInterface[]|null
     */
    public function getHistoryItems()
    {
        $retur = $this->getReturn();
        if (!$retur) {
            return null;
        }

        return $retur->getStatusHistories();
    }

    /**
     * Return back url
     *
     * @return string
     */
    public function getBackUrl()
    {
        return $this->getUrl('retur/customer/returns');
    }
}
