<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Autogedal\Retur\Controller\Index;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Autogedal\Retur\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Autogedal\Retur\Api\Data\ReturInterfaceFactory;
use Magento\SalesSequence\Model\Manager;
use Autogedal\Retur\Model\Provider\StatusProvider;
use Autogedal\Retur\Api\ReturRepositoryInterface;
use Magento\Customer\Model\Session as CustomerSession;
use Leadlion\AutogedalWarehouses\Model\WarehouseFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class Post extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
{
    protected $ibanValidator;
    protected $customerSession;
    protected $warehouseFactory;
    protected $orderCollectionFactory;

    /**
     * @var ReturRepositoryInterface
     */
    private $returRepository;

    /**
     * @var Manager
     */
    protected $sequenceManager;

    /**
     * @var ReturInterfaceFactory
     */
    private $returFactory;

    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var MailInterface
     */
    private $mail;

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

    /**
     * @param Context $context
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        ReturInterfaceFactory $returFactory,
        Manager $sequenceManager,
        ReturRepositoryInterface $returRepository,
        CustomerSession $customerSession,
        \Zend_Validate_Iban $ibanValidator,
        WarehouseFactory $warehouseFactory,
        CollectionFactory $orderCollectionFactory,
        LoggerInterface $logger = null
    ) {
        parent::__construct($context);
        $this->warehouseFactory = $warehouseFactory;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->ibanValidator = $ibanValidator;
        $this->returFactory = $returFactory;
        $this->returRepository = $returRepository;
        $this->sequenceManager = $sequenceManager;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->customerSession = $customerSession;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
    }

    /**
     * Post user question
     *
     * @return Redirect
     */
    public function execute()
    {
        if (!$this->getRequest()->isPost()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $data = $this->getRequest()->getParams();
            
            if (isset($data['iban']) && $data['iban'] && !$this->ibanValidator->isValid(preg_replace('/\s+/', '', $data['iban']))) {
                $this->messageManager->addErrorMessage(__('IBAN-ul nu este valid. Verificati si incercati din nou.'));
                $this->dataPersistor->set('formular_retur', $this->getRequest()->getParams());
                return $this->resultRedirectFactory->create()->setPath('retur');
            }

            if (!isset($data['add-retur'])) {
                $this->messageManager->addErrorMessage(__('Comanda nu are produse eligibile pentru retur'));
                $this->dataPersistor->set('formular_retur', $this->getRequest()->getParams());
                return $this->resultRedirectFactory->create()->setPath('retur');
            }

            $returModel = $this->returFactory->create();

            $returModel->setData($data);

            if ($returModel->getEntityId() == null && $returModel->getIncrementId() == null) {
                $storeId = $returModel->getStoreId();
                if ($storeId === null) {
                    $storeId = 0;
                }
                $returModel->setIncrementId(
                    $this->sequenceManager->getSequence(
                        'retur',
                        $storeId
                    )->getNextValue()
                );
                $returModel->setStatus(StatusProvider::NOU);
            }
            
            if (isset($data['add-retur'])) {
                $returItems = [];
                foreach ($data['add-retur'] as $key => $value) {
                    $returItems[] = $value;
                }
                $returModel->setReturItems($returItems);
            }
            
            $this->returRepository->save($returModel);

            $orderCollection = $this->orderCollectionFactory->create()
                ->addAttributeToSelect("*")
                ->addFieldToFilter('user_increment_id', ['in' => $returModel->getUserIncrementId()]);
            foreach ($orderCollection as $order) {
                $warehouse = $this->warehouseFactory->create()->load($order->getAutogedalAllocatedWarehouse());
            }
            $warehouseAddress = $warehouse->getAddress();
            if ($warehouse->getCity()) {
                $warehouseAddress = $warehouse->getAddress(). ', '.$warehouse->getCity();
            }

            $mailParams = [
                'store_id' => $returModel->getStoreId(),
                'email' => $returModel->getEmail(),
                'name' => $returModel->getCustomerFirstname(). ' '.$returModel->getCustomerLastname(),
                'increment_id' => $returModel->getIncrementId(),
                'warehouse_address' => $warehouseAddress
            ];
            
            if ($returModel->getEmail()) {
                $this->sendEmail($mailParams);
            }
            
            $this->dataPersistor->clear('formular_retur');
            
            $this->customerSession->setReturnSuccessData($mailParams);
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('formular_retur', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('formular_retur', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('retur/index/success');
    }

    /**
     * Method to send email.
     *
     * @param array $post Post data from contact form
     *
     * @return void
     */
    private function sendEmail($post)
    {
        $this->mail->send(
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }
}
