<?php
/**
 * @author  Magediary
 * @package Magediary_ProductQuestion
 */

namespace Magediary\ProductQuestion\Controller\Product;

use Magediary\ProductQuestion\Controller\Product as ProductController;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultFactory;
use Magediary\ProductQuestion\Model\Question;

class Post extends ProductController
{
    /**
     * Submit new question action
     *
     * @return Redirect
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }

        $data = $this->questionSession->getFormData(true);
        if (!$data) {
            $data = $this->getRequest()->getPostValue();
        }
        if (($product = $this->initProduct()) && !empty($data)) {
            $question = $this->questionFactory->create()->setData($data);
            $question->unsetData('question_id');

            $validate = $question->validate();
            if ($validate === true) {
                try {
                    $type = Question::TYPE_GUEST;
                    if ($this->customerSession->getCustomerId()) {
                        $type = Question::TYPE_CUSTOMER;
                    }

                    $status = Question::STATUS_PENDING;
                    if ($this->_helperData->getConfig('question/question/auto_approval')) {
                        $status = Question::STATUS_APPROVED;
                    }

                    if (!$question->getEmail()) {
                        $question->setEmail($this->customerSession->getCustomer()->getEmail());
                    }

                    $question->setProductId($product->getId())
                        ->setStatus($status)
                        ->setType($type)
                        ->setCustomerId($this->customerSession->getCustomerId())
                        ->setStoreId($this->storeManager->getStore()->getId())
                        ->save();

                    $data['id'] = $question->getId();

                    $this->messageManager->addSuccess(
                        __('Question posted successfully. Will notify you when someone answers your question.')
                    );
                } catch (\Exception $e) {
                    $this->questionSession->setFormData($data);
                    $this->messageManager->addExceptionMessage(
                        $e,
                        __('We can\'t post your question right now.')
                    );
                    $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
                }
            } else {
                $this->questionSession->setFormData($data);
                if (is_array($validate)) {
                    foreach ($validate as $errorMessage) {
                        $this->messageManager->addError($errorMessage);
                    }
                } else {
                    $this->messageManager->addError(__('We can\'t post your question right now.'));
                }
            }
        }
        $redirectUrl = $this->questionSession->getRedirectUrl(true);
        $resultRedirect->setUrl($redirectUrl ?: $this->_redirect->getRedirectUrl());
        return $resultRedirect;
    }
}
