<?php

namespace MageArray\LowerPrice\Controller\Form;

use Magento\Framework\Controller\ResultFactory;

/**
 * Class Post
 * @package MageArray\LowerPrice\Controller\Form
 */
class Post extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;
    /**
     * @var \MageArray\LowerPrice\Model\LowerPriceFactory
     */
    protected $_lowerPriceFactory;
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    protected $date;
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * Post constructor.
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
     * @param \MageArray\LowerPrice\Model\LowerPriceFactory $lowerPriceFactory
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \MageArray\LowerPrice\Helper\Data $helper
     * @param \Magento\SalesRule\Model\Rule $ruleModel
     * @param \MageArray\LowerPrice\Model\ManageCoupon $manageCoupon
     * @param \Magento\Catalog\Model\ProductFactory $_productloader
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \MageArray\LowerPrice\Model\LowerPriceFactory $lowerPriceFactory,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \MageArray\LowerPrice\Helper\Data $helper,
        \Magento\SalesRule\Model\Rule $ruleModel,
        \MageArray\LowerPrice\Model\ManageCoupon $manageCoupon,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->date = $date;
        $this->_lowerPriceFactory = $lowerPriceFactory;
        $this->_transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->helper = $helper;
        $this->ruleModel = $ruleModel;
        $this->manageCoupon = $manageCoupon;
        $this->_productloader = $_productloader;
        $this->inlineTranslation = $inlineTranslation;
        $this->logger = $logger;
        $this->_storeManager = $storeManager;
    }

    /**
     * @return bool
     */
    public function execute()
    {
        if ($this->getRequest()->isAjax()) {
            $post = $this->getRequest()->getPostValue();
            if (!$post) {
                return false;
            }

            $error = false;
            try {
                $this->dataValidation($post);

                $post['createat'] = $this->date->gmtDate();
                $post['ip_address'] = $this->rmVisitorIp();

                $model = $this->_lowerPriceFactory->create();
                $model->setData($post);
                $model->setApproval(0);
                $product = $this->getLoadProduct($post['product_id']);
                $code = $this->manageCoupon->checkThresholdLimit($post, $product);
                if ($product->getAutoApprovedInquiries()) {
                    if (isset($code[0]) && !empty($code[0])) {
                        $model->setApproval(1);
                        $model->setCouponCode($code[0]);
                        $model->setExtraNote('This inquiry is approved.');
                    }
                }
                $model->setDiscountAmount($code[1]);
                $model->save();

                $this->sendEmail($post); // send email to admin
                $this->helper->sendCouponCodeEmail($model->getData());

                $result['su'] = true;
                $result['msg'] = $this->helper->getThankYouMsg();
            } catch (\Exception $e) {
                $result['su'] = false;
                $result['err'] = true;
                $result['msg'] = $e->getMessage();
                if ($error) {
                    $result['error'] = $error;
                }
            }

            $this->getResponse()->representJson(
                $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::Class)->jsonEncode($result)
            );
        }
    }

    /**
     * @param $id
     * @return mixed
     */
        /**
         * @return mixed
         */
    public function getCurrentStoreId()
    {
        return $this->_storeManager->getStore()->getStoreId();
    }
    public function dataValidation($post)
    {
        $error = false;
        if (isset($post['product_id']) && empty($post['product_id'])) {
            $error = true;
        }
        if (isset($post['price']) && empty($post['price'])) {
            $error .= 'Please enter valid price.<br />';
        }
        if (isset($post['product_link']) && empty($post['product_link'])) {
            $error .= 'Please enter valid product link.<br />';
        }
        if (isset($post['email']) && empty($post['email'])) {
            $error .= 'Please enter valid email.<br />';
        }
        if (isset($post['name']) && empty($post['name'])) {
            $error .= 'Please enter Name.<br />';
        }

        $product = $this->getLoadProduct($post['product_id']);
        if ($post['price'] > $product->getPrice()) {
            $error .= 'Already lower than another price.<br />';
        }

        if ($error) {
            throw new \Magento\Framework\Exception\AlreadyExistsException(
                __($error)
            );
        }
    }
    /**
     * @param $id
     * @return mixed
     */
    public function getLoadProduct($id)
    {
        return $this->_productloader->create()->load($id);
    }

    /**
     * @return mixed
     */
    public function rmVisitorIp()
    {
        $remoteAddress = $this->_objectManager->get(
            \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress::Class
        );
        return $remoteAddress->getRemoteAddress();
    }

    /**
     *
     */
    public function sendEmail($post)
    {
        try {

            $shippingHandling = 0;
            if (isset($post['shipping_handling']) && !empty($post['shipping_handling'])) {
                $shippingHandling = $post['shipping_handling'];
            }

            $salesTax = 0;
            if (isset($post['sales_tax']) && !empty($post['sales_tax'])) {
                $salesTax = $post['sales_tax'];
            }

            $priceHelper = $this->_objectManager->create(\Magento\Framework\Pricing\Helper\Data::Class);
            $post['price'] = $priceHelper->currency($post['price'], true, false);
            $post['product_price'] = $priceHelper->currency($post['product_price'], true, false);

            $post['shipping_handling'] = ($shippingHandling == 1 ? 'Yes' : 'No');
            $post['sales_tax'] = ($salesTax == 1 ? 'Yes' : 'No');

            $name = $post['name'];
            $email = $post['email'];

            $toName = $this->helper->getSenderName();
            $toEmail = $this->helper->getSenderEmail();

            $sender = [
                'name' => $name,
                'email' => $email,
            ];

            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $this->inlineTranslation->suspend();
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->helper->getLowerPriceEmailTemplateId())
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' =>$this->getCurrentStoreId()
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($sender)
                ->addTo($toEmail, $toName)
                ->setReplyTo($email)
                ->getTransport();
            $transport->sendMessage();
            $this->inlineTranslation->resume();
            return true;
        } catch (\Exception $e) {

            $this->logger->info($e->getMessage());
        }
    }
}
