<?php

    namespace MNM\RevocationForm\Controller\Index;

    use Magento\Framework\App\Request\DataPersistorInterface;
    use Magento\Framework\Exception\LocalizedException;
    use MNM\RevocationForm\Model\ConfigInterface;
    use MNM\RevocationForm\Model\MailInterface;
    use Magento\Framework\DataObject;
    use Magento\Framework\Registry;
    use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;

    class Index extends \Magento\Framework\App\Action\Action {
        protected $resultPageFactory;

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

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

        /**
         *
         * @var bool
         */
        private $captchaFalse;

        /**
         * @var ConfigInterface
         */
        private $contactsConfig;

        /**
         *
         * @var CollectionFactory
         */
        private $categoryCollectionFactory;

        /**
         * @var \Magento\Framework\Registry
         */
        protected $_registry;

        public function __construct(\Magento\Framework\App\Action\Context $context,
          \Magento\Framework\View\Result\PageFactory $resultPageFactory,
            ConfigInterface $contactsConfig,
            MailInterface $mail,
            DataPersistorInterface $dataPersistor,
            Registry $registry,
            CollectionFactory $categoryCollectionFactory)
        {
            $this->resultPageFactory = $resultPageFactory;
            $this->dataPersistor = $dataPersistor;
            $this->captchaFalse = false;
            $this->mail = $mail;
            $this->contactsConfig = $contactsConfig;
            $this->_registry = $registry;
            $this->categoryCollectionFactory = $categoryCollectionFactory;
            parent::__construct($context);
        }

        public function execute()
        {
            //set category for menu
            if($this->contactsConfig->cmsCategory())
            {
                // get an instance of CategoryCollection
                $categoryCollection = $this->categoryCollectionFactory->create();

                // add a filter to get the IDs you need
                $categoryCollection->addFieldToFilter('entity_id', [$this->contactsConfig->cmsCategory()]);

                // either call getItems() and iterate over it, or do whatever you need
                foreach ($categoryCollection->getItems() as $category) {
                    /** @var \Magento\Catalog\Model\Category\Interceptor $category */

                    $this->_registry->register('current_category', $category);
                }
            }

            //check if form send
            if($this->getRequest()->isPost()) {
                try {
                    $this->sendEmail($this->validatedParams());
                    $this->messageManager->addSuccessMessage(
                        __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
                        );
                    $this->dataPersistor->clear('revocation');
                } catch (LocalizedException $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                    $this->dataPersistor->set('revocation', $this->getRequest()->getParams());
                } catch (\Exception $e) {
                    $this->messageManager->addErrorMessage(
                        __('An error occurred while processing your form. Please try again later.')
                        );
                    $this->dataPersistor->set('revocation', $this->getRequest()->getParams());
                }
            }

            return $this->resultPageFactory->create();
        }

        public function setCaptchaFalse($v) {
            $this->captchaFalse = $v;
        }

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

            //send to customer
            $this->mail->sendCustomer($post['email'], ['data' => new DataObject($post)]);
        }

        /**
         * @return array
         * @throws \Exception
         */
        private function validatedParams()
        {
            $request = $this->getRequest();
            if (trim($request->getParam('name')) === '') {
                throw new LocalizedException(__('Enter the Name and try again.'));
            }
            if (trim($request->getParam('comment')) === '') {
                throw new LocalizedException(__('Enter the comment and try again.'));
            }
            if (false === \strpos($request->getParam('email'), '@')) {
                throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
            }
            if (trim($request->getParam('hideit')) !== '') {
                throw new \Exception();
            }
            if($this->captchaFalse) {
                throw new LocalizedException(__('Incorrect CAPTCHA'));
            }

            return $request->getParams();
        }
    }