<?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 AddProductToWishlist extends Action\Action
{
    protected $httpContext;
    protected $jsonFactory;
    protected $wishlistFactory;
    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\WishlistFactory $wishlistFactory,
        \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->wishlistFactory = $wishlistFactory;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->itemFactory = $itemFactory;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->emailHelper = $emailHelper;
        $this->projectCartItemsFactory = $projectCartItemsFactory;
        $this->resProjectCartItemsFactory = $resProjectCartItemsFactory;
    }

    public function execute()
    {
        $response = array(
            'status'=>'error',
            'message'=>__('Can not add item to Request offer list'),
            'title'=>__('Error'),
            'export_url'=>''
        );
        // return $this->jsonFactory->create()->setData($response);
        $params = $this->getRequest()->getParams();
        $productId = $this->getRequest()->getParam('product',0);
        $product = $this->getProductById($productId);
        $customerId = $this->getCustomerId();
        if($customerId <= 0) {
            $response['message'] = __('You have to login before add item to Request for offer list');
            return $this->jsonFactory->create()->setData($response);
        }
        $wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);
        if(!$wishlist) {
            $response['message'] = __('Can not add item to Request offer list');
        }
        $token = isset($params['uenc']) ? trim($params['uenc']) : '';
        $token = sha1($token);
        /** @var \Magetop\Advancepreview\Helper\Data $previewHelper */
        $previewHelper = $this->_objectManager->get('Magetop\Advancepreview\Helper\Data');
        $emailStore = $previewHelper->getOpdSetting('trans_email/ident_general/email');
        $customerName = '';
        $customer = $this->getCustomer();
        if($customer) {
            $customerName = $customer->getName();
        }
        if($product && $product->getId()) {
            try {
                $params['customer_id'] = $customerId;
                $item = $wishlist->addNewItem($product,$params);
                $wishlist->save();
                //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;
                $offerId = isset($params['request_offer_id']) ? $params['request_offer_id'] : '';
//                $storeEmail = $this->emailHelper
                $templateVars = [
                    'download_pdf'=>$downloadUrl,
                    'product_name'=>$product->getName(),
                    'offer_id'=>$offerId,
                    'email_store'=>$emailStore,
                    'customer_name'=>$customerName,
                    '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'] = __('%1 has been added to your My requested offer', $product->getName());
                    }
                    else {
                        $response['message'] = __('%1 has been added to your My requested offer', $product->getName());
                    }
                }
                else {
                    $response['message'] = __('%1 has been added to your My requested offer', $product->getName());
                }
                $response['title'] = __('Success');
                $genereId = isset($params['text_project_generate']) ? (int)$params['text_project_generate'] : 0;
                if($genereId > 0) {
                    $this->saveProjectCart($genereId);
                }
                $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 getCustomerId() {
        $customerId = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();


        }
        return $customerId;
    }
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
    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 saveProjectCart($projectId) {
        $dataSave = array(
            'project_item_id'=>$projectId,
            'customer_id'=>0,
            'created_at'=>date('Y-m-d H:i:s')
        );
        $model = $this->projectCartItemsFactory->create()->setData($dataSave);
        try {
            $this->resProjectCartItemsFactory->create()->save($model);
        }
        catch (\Exception $exception) {

        }
    }

    /**
     * @return \Magento\Customer\Model\Customer
     */
    protected function getCustomer() {
        $customerId = $this->getCustomerId();
        $customer = $this->customerFactory->create()->load($customerId);
        return $customer;
    }

}
