<?php

namespace MageArray\LowerPrice\Controller\Adminhtml\LowerPrice;

use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;

/**
 * Class Save
 * @package MageArray\LowerPrice\Controller\Adminhtml\LowerPrice
 */
class Save extends \MageArray\LowerPrice\Controller\Adminhtml\LowerPrice
{

    /**
     *
     */
    public function execute()
    {
        $lowerpriceData = $this->getRequest()->getPostValue();
        if (isset($lowerpriceData) && !empty($lowerpriceData)) {
            $lowerpriceId = isset($lowerpriceData['lowerprice_id']) ? $lowerpriceData['lowerprice_id'] : null;
            $model = $this->_lowerPriceFactory->create();
            if ($lowerpriceId) {
                $model->load($lowerpriceId);
            }
            
            $lowerpriceData['shipping_handling'] = isset($lowerpriceData['shipping_handling']) ? $lowerpriceData['shipping_handling'] : 0;//phpcs:ignore
            $lowerpriceData['sales_tax'] = isset($lowerpriceData['sales_tax']) ? $lowerpriceData['sales_tax'] : 0;
            
            $codeData = [];
            if (isset($lowerpriceData['discount_amount']) && $lowerpriceData['discount_amount'] > 0) {
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $product = $objectManager->create(\Magento\Catalog\Model\Product::Class)->load($lowerpriceData['product_id']);//phpcs:ignore
                $codeData = $this->manageCoupon->createCartPriceRules($lowerpriceData['discount_amount'], $product);
                if (isset($codeData[0]) && !empty($codeData[0])) {
                    $code = $codeData[0];
                    $lowerpriceData['coupon_code'] = $code;
                }
            }
            
            if (isset($lowerpriceData['send_email'])) {
                $code = $this->sendCouponCode($lowerpriceData, $codeData);
                if (!$code) {
                    $lowerpriceData['approval'] = 0;
                } else {
                    $lowerpriceData['coupon_code'] = $code;
                    if (isset($lowerpriceData['extra_note']) && $lowerpriceData['extra_note'] == '') {
                        $lowerpriceData['extra_note'] = 'This inquiry is approved.';
                    }
                }
            }
            
            try {
                $model->setData($lowerpriceData);
                $model->save();
                $this->messageManager->addSuccess(__('The inquiry has been saved.'));
                $this->_getSession()->setFormData(false);

                if ($this->getRequest()->getParam('back') === 'edit') {
                    $this->_redirect('*/*/edit', ['lowerprice_id' => $model->getLowerpriceId(), '_current' => true]);
                    return;
                } elseif ($this->getRequest()->getParam('back') === "new") {
                    $this->_redirect('*/*/new', ['_current' => true]);
                    return;
                }
                $this->_redirect('*/*/');
                return;
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                $this->messageManager->addException($e, __('Something went wrong while saving the Lower Price.'));
            }

            $this->_getSession()->setFormData($lowerpriceData);
            $this->_redirect('*/*/edit', ['lowerprice_id' => $this->getRequest()->getParam('lowerprice_id')]);
            return;
        }
        $this->_redirect('*/*/');
    }

    /**
     * @return mixed
     */
    public function sendCouponCode($post, $code)
    {
        if ($post['approval'] == 0 || $post['discount_amount'] == '') {
            return false;
        }
        if (isset($code[0]) && !empty($code[0])) {
            $code = $code[0];
            $post['coupon_code'] = $code;
        } else {
            $this->messageManager->addError('Something went wrong while send approval email.');
            return false;
        }
        return $this->helper->sendCouponCodeEmail($post);
    }
}
