<?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\Adminhtml\Order;

use Magento\Backend\App\Action;
class UpdateCustomDesignPrint extends Action
{
    protected $jsonFactory;
    /**
     * @var \Magetop\Advancepreview\Model\PreviewOrderItemsFactory
     */
    protected $previewOrderItemsFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory
     */
    protected $resPreviewOrderItemsFactory;
    protected $colPreviewOrderItemsFactory;
    protected $emailHelper;
    protected $orderFactory;
    protected $resOrderFactory;
    protected $priceHelper;
    function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Sales\Model\ResourceModel\OrderFactory $resOrderFactory,
        \Magetop\Advancepreview\Model\PreviewOrderItemsFactory $previewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory $resPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Helper\Email $emailHelper
    )
    {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->previewOrderItemsFactory = $previewOrderItemsFactory;
        $this->resPreviewOrderItemsFactory = $resPreviewOrderItemsFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->emailHelper = $emailHelper;
        $this->orderFactory = $orderFactory;
        $this->resOrderFactory = $resOrderFactory;
        $this->priceHelper = $priceHelper;
    }
    public function execute()
    {
        //
        $response = [
            'status'=>'error',
            'message'=>__('Can not check and update design'),
            'item_status'=>''

        ];
        // get setinig
        /** @var \Magetop\Advancepreview\Helper\Data $previewHelper*/
        $previewHelper = $this->_objectManager->get('\Magetop\Advancepreview\Helper\Data');
        $myfistEmail = $previewHelper->getOpdSetting('trans_email/ident_general/email');
        $status = $this->getRequest()->getParam('status','');
        $txtOrder = $this->getRequest()->getParam('txt_order','');
        $itemId = (int)$this->getRequest()->getParam('item_id',0);
        $productName = $this->getRequest()->getParam('product_name','');
        $customerName = $this->getRequest()->getParam('customer_name','');
        $customerEmail = $this->getRequest()->getParam('customer_email','');
        $customerId = $this->getRequest()->getParam('customer_id',0);
        $status = trim($status);
        $order = $this->getOrderByIncrementId($txtOrder);
        $storeId = $order->getStoreId();
        if($itemId <= 0 || $status == '' || !$order) {
            $response['message'] = __('Item not found or status is not available');
        }
        else {
            $previewItem = $this->getPreviewItemByItemId($itemId);
            if($previewItem->getId()) {
                $dataUpdate = [
                    'status'=>$status,
                    'custom_item_id'=>$previewItem->getId(),
                    'updated_at'=>date('Y-m-d H:i:s')
                ];
                if($status == 'design_approved') {
                    $dataUpdate['is_new_proof'] = 1;
                }
                $updateId = $this->savePreviewOrderItem($dataUpdate);
                if($updateId > 0) {
                    $response['status'] = 'success';
                    $response['message'] =  __('You have updated order status successfully');
                    $statusCustomPrintLabels = [
                        'new'=>'New',
                        'downloading'=>'Checking design by Myfitmix',
                        'design_failed'=>'Design Failed',
                        'design_approved'=>'Design Approved'
                    ];
                    $statusCheckSendMail = '';
                    if($status == 'downloading') {
                        $statusCheckSendMail = 'status_checking_myfit';
                    }
                    else if($status == 'design_failed') {
                        $statusCheckSendMail = 'status_design_failed';
                    }
                    else if($status == 'design_approved') {
                        $statusCheckSendMail = 'status_design_approved';
                    }
                    $response['item_status'] = isset($statusCustomPrintLabels[$status]) ? $statusCustomPrintLabels[$status] : $status;
                    $emailId = 'eak_admin_update_order_item_status';
                   if($status == 'downloading') {
                        $emailId = 'eak_admin_update_order_item_status_downloading';
                    }
                    elseif($status == 'design_failed') {
                        $emailId = 'eak_admin_update_order_item_status_design_failed';
                    }
                    else if($status == 'design_approved') {
                        $emailId = 'eak_admin_update_order_item_status_design_approved';
                    }
                    $itemDesignPrice = $this->getDesignItemPrice($order,$itemId);
                    $itemDesignPrice = $this->priceHelper->currency($itemDesignPrice, true, false);
                    $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
                    $loginUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB).'customer/account/login';
                    $customerPrefix = $order->getCustomerPrefix();
                    $newCustomerName = str_replace($customerPrefix, '', $order->getCustomerName());
                    $customerPrefix = $this->getTranslateCustomerPrefix($customerPrefix, $storeId);
                    $newCustomerName = $customerPrefix .' '. $newCustomerName;
                    $templatavals = [
                        'txt_order'=>$txtOrder,
                        'customer_name'=>$newCustomerName,
                        'product_name'=>$productName,
                        'item_status'=>$response['item_status'],
                        'order_create_at'=>date('m/d/Y', strtotime($order->getCreatedAt())),
                        'item_price'=>$itemDesignPrice,
                        'myfit_mail'=>$myfistEmail,
                        'link_login'=>$loginUrl
                    ];
                    if($status == 'design_failed' || $status == 'design_approved') {
//                        $emailId = 'eak_admin_update_order_item_status_design_failed';
                        /** @var \Magento\Store\Model\StoreManagerInterface $storeManager*/
                      /*  $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
                        $loginUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
                        $templatavals['link_login'] = $loginUrl. 'customer/account/login';*/
                    }
                    if($this->emailHelper->checkIsSendEmail($statusCheckSendMail,$customerId)) {
                        $send = $this->sendEmailToCustomer($customerEmail,$emailId,$templatavals, $storeId);
                        $response['send'] = $send['message'];
                    }
                    else {
                        $response['send'] = 'disable send';
                    }


                }
            }
            else {
                $response['message'] = __('Item not found or status is not available');
            }
        }
        if($status != 'downloading') {
            if($response['status'] == 'success') {
                $this->messageManager->addSuccessMessage($response['message']);
            }
            else {
                $this->messageManager->addErrorMessage($response['message']);
            }
        }

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

    }
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('status'))
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }

    /**
     * @param array $previewData
     * @return int
     */
    protected function savePreviewOrderItem($previewData = []) {
        $model = $this->previewOrderItemsFactory->create();
        $model->setData($previewData);
        $id = 0;
        try {
            $this->resPreviewOrderItemsFactory->create()->save($model);
            $id =  $model->getId();
        }
        catch (\Exception $exception) {

        }
        return $id;

    }
    protected function sendEmailToCustomer($toEmail, $emailId, $templateVars = [], $storeId = null) {
        $sendResponse = array(
            'status'=>'error',
            'message'=>'Can not send email'
        );
        $storeName = 'myfitmix';
        $templateVars['custom_store_name'] = $storeName;
//        $emailId = 'eak_customer_order_item_ready_sale';
        $formEmail = 'info@myfitmix.de';
        if($toEmail == '') {
            $sendResponse['message'] = 'Email not found';
        }
        else {
            $sendResponse = $this->emailHelper->sendAdvanceEmail($emailId,$templateVars,$storeName,$formEmail,$toEmail, $storeId);
        }

        return $sendResponse;
    }
    protected function getOrderByIncrementId($incrementId) {
        $model =  $this->orderFactory->create();
        try {
            $this->resOrderFactory->create()->load($model,$incrementId,'increment_id');
        }
        catch (\Exception $exception) {

        }
        return $model;
    }
    protected function getDesignItemPrice(
        \Magento\Sales\Model\Order $order,
        $itemId
    ) {
        $price = 0;
        if($order && $order->getAllItems()) {
            foreach ($order->getAllVisibleItems() as $item) {
                if($item->getId() == $itemId) {
                    $infoRequest = $item->getProductOptionByCode('info_buyRequest');
                    $price = $infoRequest['txt_project_final_price'];
                }

            }
        }
        return $price;
    }
    protected function getTranslateCustomerPrefix($text, $storeId) {
        if($storeId == 2) {
            return $text;
        }
        if($text == 'Mr') {
            $text = 'Sehr geehrter Her';
        }
        else if($text == 'Mrs') {
            $text = 'Sehr geehrte Frau';
        }
        return  $text;
    }
}
