<?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\ResourceModel\Retur\CollectionFactory;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Autogedal\Retur\Ui\Component\Listing\Column\Status\Options as StatusOptions;

class Returns extends Template
{
    /**
     * @var Session
     */
    protected $customerSession;

    /**
     * @var CollectionFactory
     */
    protected $returCollectionFactory;

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

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

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

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param CollectionFactory $returCollectionFactory
     * @param LoggerInterface $logger
     * @param OrderCollectionFactory $orderCollectionFactory
     * @param StatusOptions $statusOptions
     * @param array $data
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        CollectionFactory $returCollectionFactory,
        LoggerInterface $logger,
        OrderCollectionFactory $orderCollectionFactory,
        StatusOptions $statusOptions,
        array $data = []
    ) {
        $this->customerSession = $customerSession;
        $this->returCollectionFactory = $returCollectionFactory;
        $this->logger = $logger;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->statusOptions = $statusOptions;
        parent::__construct($context, $data);
    }

    /**
     * Get customer returns collection
     *
     * @return \Autogedal\Retur\Model\ResourceModel\Retur\Collection|null
     */
    public function getReturns()
    {
        try {
            $customerId = $this->customerSession->getCustomerId();
            $collection = $this->returCollectionFactory->create();

            $collection->getSelect()->join(
                ['so' => $collection->getTable('sales_order')],
                'main_table.order_user_increment_id = so.user_increment_id',
                []
            )->where('so.customer_id = ?', $customerId);

            $collection->setOrder('main_table.entity_id', 'DESC');

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

    /**
     * Get order by user_increment_id
     *
     * @param string $userIncrementId
     * @return \Magento\Sales\Model\Order|null
     */
    public function getOrderByUserIncrementId($userIncrementId)
    {
        try {
            $orderCollection = $this->orderCollectionFactory->create();
            $orderCollection->addFieldToFilter('user_increment_id', $userIncrementId);
            $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
     *
     * @param string $userIncrementId
     * @return string
     */
    public function getOrderViewUrl($userIncrementId)
    {
        $order = $this->getOrderByUserIncrementId($userIncrementId);
        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 view URL for a return
     *
     * @param int $returId
     * @return string
     */
    public function getViewUrl($returId)
    {
        return $this->getUrl('retur/customer/view', ['id' => $returId]);
    }
}
