<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

 namespace Magetop\Advancepreview\Controller\Product;

use Magento\Framework\App\Action;

class RequestOfferFromWishlist extends Action\Action
{
    protected $httpContext;
    protected $jsonFactory;
    protected $wishlistItemFactory;
    protected $productRepository;
    protected $itemFactory;
    protected $customerSession;
    protected $productFactory;
    protected $resProductFactory;
    protected $customerFactory;
    protected $emailHelper;
    protected $projectCartItemsFactory;
    protected $resProjectCartItemsFactory;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Wishlist\Model\ItemFactory $wishlistItemFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Wishlist\Model\ItemFactory $itemFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magetop\Advancepreview\Helper\Email $emailHelper,
        \Magetop\Advancepreview\Model\ProjectCartItemsFactory $projectCartItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\ProjectCartItemsFactory $resProjectCartItemsFactory
    )
    {
        parent::__construct($context);
        $this->httpContext = $httpContext;
        $this->jsonFactory = $jsonFactory;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->itemFactory = $itemFactory;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->emailHelper = $emailHelper;
        $this->projectCartItemsFactory = $projectCartItemsFactory;
        $this->resProjectCartItemsFactory = $resProjectCartItemsFactory;
        $this->wishlistItemFactory = $wishlistItemFactory;
    }

    public function execute()
    {
        $response = [
            'status'=>'error',
            'message_title'=>__('Error'),
            'message'=>__('It is not possible to request offer again'),
        ];
        $wishlistId = $this->getRequest()->getParam('item_id',0);
        $item = $this->getWishlistById($wishlistId);
        $productId = $this->getRequest()->getParam('product_id',0);
        $product = $this->getProductById($productId);
        $infoRequest = $this->getRequest()->getParam('info_request',[]);
        $customerId = $this->customerSession->getCustomer()->getId();
        if($customerId <= 0) {
            $response['message'] = __('You have to login before add item to Request for offer list');
            return $this->jsonFactory->create()->setData($response);
        }
        $customerName = '';
        $customer = $this->getCustomer();
        if($customer) {
            $customerName = $customer->getName();
        }
        $previewHelper = $this->_objectManager->get('Magetop\Advancepreview\Helper\Data');
        $emailStore = $previewHelper->getOpdSetting('trans_email/ident_general/email');
        $token = isset($infoRequest['uenc']) ? sha1($infoRequest['uenc']) : '';
        if($product && $product->getId()) {
             try {
                $params['customer_id'] = $customerId;
                $offerId = isset($infoRequest['request_offer_id']) ? $infoRequest['request_offer_id'] : '';
                //test
                $response['status'] = 'success';
                $response['message'] = __('%1 has been added to your My requested offer',$product->getName());
                $downloadUrl = $this->_url->getUrl('advance_preview/index/index/') . 'item_id/'.$item->getId().'/type/1/token/'.$token;
                $downloadUrl2 = $this->_url->getUrl('advance_preview/product/exportPdfOffer/') .'item_id/'.$item->getId().'/token/'.$token;
                $templateVars = [
                    'download_pdf'=>$downloadUrl,
                    'product_name'=>$product->getName(),
                    'email_store'=>$emailStore,
                    'customer_name'=>$customerName,
                    'offer_id'=>$offerId,
                    'login_url'=>$this->_url->getUrl('customer/account/login'),
                ];
                $checkSendMail = $this->emailHelper->checkIsSendEmail('request_offer',$customerId);
                if($checkSendMail) {
                    $sendResponse = $this->sendEmailToCustomer($templateVars);
                    if(isset($sendResponse['status']) && $sendResponse['status'] == 'success') {
                        $response['message_title'] = __('Success');
                        $response['message'] = __('%1 has been requested again', $product->getName());
                    }
                    else {
                        $response['message'] = __('%1 has been requested again', $product->getName());
                    }
                }
                else {
                    $response['message'] = __('%1 has been requested again', $product->getName());
                }
                $response['title'] = __('Success');
                $response['export_url'] = $downloadUrl2;
            }
            catch (\Exception $exception) {
//                $response['message'] = __('Something wrong when add product to wishlist '.$exception->getMessage());
            }
        }
        else {
//            $response['message'] = 'Product not found';
        }

        return $this->jsonFactory->create()->setData($response);
    }

    protected function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }
    protected function sendEmailToCustomer($templateVars = []) {
        $sendResponse = array(
            'status'=>'error',
            'message'=>'Can not send email'
        );
        $emailId = 'magetop_preview_export_design_offer_pdf';
        $formEmail = 'info@myfitmix.de';
        $customer = $this->getCustomer();
        $toEmail = $customer ? $customer->getEmail() : '';
        $storeName = 'myfitmix';
        $templateVars['custom_store_name'] = $storeName;
        if(!$customer || $toEmail == '') {
            $sendResponse['message'] = 'Email not found';
        }
        else {
//            $customerName = $customer->getData('firstname') .' '. $customer->getData('lastname');
            $sendResponse = $this->emailHelper->sendAdvanceEmail($emailId,$templateVars,$storeName,$formEmail,$toEmail);
        }

        return $sendResponse;
    }

    protected function getWishlistById($wishlistId) {
        return $this->wishlistItemFactory->create()->load($wishlistId);
    }

    protected function getCustomer() {
        $customerId = $this->customerSession->getCustomer()->getId();
        $customer = $this->customerFactory->create()->load($customerId);
        return $customer;
    }
}
