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

use Magento\Framework\App\Action;
use Magento\Sales\Model\OrderFactory;

class UpdateCustomItemPrint extends Action\Action
{
    protected $jsonFactory;
    protected $previewOrderItemsFactory;
    protected $resPreviewOrderItemsFactory;
    protected $colPreviewOrderItemsFactory;
    protected $emailHelper;
    protected $_orderRepository;
    protected $_invoiceService;
    protected $_transaction;
    protected $orderFactory;
    protected $resOrderFactory;
    protected $priceHelper;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Sales\Model\Service\InvoiceService $invoiceService,
        \Magento\Framework\DB\Transaction $transaction,
        \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->_orderRepository = $orderRepository;
        $this->_invoiceService = $invoiceService;
        $this->_transaction = $transaction;
        $this->orderFactory = $orderFactory;
        $this->resOrderFactory = $resOrderFactory;
        $this->priceHelper = $priceHelper;
    }
    public function execute()
    {
        $resonse = [
            'status'=>'error',
            'message'=>'Can not update order status',
        ];
        $itemId = $this->getRequest()->getParam('item_id',0);
        $status = $this->getRequest()->getParam('status','new');
        $customerId = $this->getRequest()->getParam('customer_id','');
        $txtOrder = $this->getRequest()->getParam('txt_order','');
        $customerName = $this->getRequest()->getParam('customer_name','');
        $email = $this->getRequest()->getParam('customer_email','');
        $productName = $this->getRequest()->getParam('product_name','');
        $fileAdminUpload = $this->getRequest()->getParam('admin_upload','');
        $orderId = $this->getRequest()->getParam('order_id',0);
        $qty = $this->getRequest()->getParam('qty',0);
        $totalPrice = $this->getRequest()->getParam('total',0);
        $orderItem = $this->getPreviewItemByItemId($itemId);
        $orderItemId = $orderItem ? $orderItem->getId() : 0;
        $order = $this->getOrderByIncrementId($txtOrder);
        $withoutPrinting = false;
        $withoutPrintingStatus = '';
        $storeId = $order->getStoreId();
        $customerPrefix = $order->getCustomerPrefix();
        $newCustomerName = str_replace($customerPrefix, '', $order->getCustomerName());
        $customerPrefix = $this->getTranslateCustomerPrefix($customerPrefix, $storeId);
        $newCustomerName = $customerPrefix .' '. $newCustomerName;
        if($orderItemId > 0) {
            if(trim($fileAdminUpload) != '') {
                $withoutPrinting = true;
                if($status == 1) {

                }
                else {
                    $fileAdminUpload = '';
                }
                $datSave = [
                    'admin_upload_status'=>$status,
                    'admin_upload_design'=>$fileAdminUpload,
                    'custom_design'=>$fileAdminUpload,
                    'custom_item_id'=>$orderItemId,
                ];
                // customer require more
                if($status == 1) {
                    $datSave['status'] = 'design_full_approved';
                }
                else {
                    $withoutPrintingStatus = 'customer_reject';
                    $datSave['status'] = 'customer_reject';
                }
            }
            else {
                $datSave = [
                    'status'=>$status,
                    'custom_item_id'=>$orderItemId,
                ];
                if($status == 'customer_reject') {
                    $datSave['is_new_proof'] = 0;
                }
            }

            $newId = $this->savePreviewOrderItem($datSave);
            if($newId > 0) {
                $resonse['status'] = 'success';
                $resonse['message'] = 'You have updated order status successfully';
                $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';
                $previewHelper = $this->_objectManager->get('\Magetop\Advancepreview\Helper\Data');
                $myfistEmail = $previewHelper->getOpdSetting('trans_email/ident_general/email');
                if($status == 'design_full_approved' || $withoutPrinting) {
                    // send email
                    if($this->emailHelper->checkIsSendEmail('status_design_fully_approved',$customerId)) {
                        $emailId = 'eak_admin_update_order_item_status_design_full_approved';
                        $itemStatusText = 'Design Fully Approved';
                        if($withoutPrintingStatus == 'customer_reject' && $withoutPrinting) {
                            $itemStatusText = 'Design Failed';
                            $emailId = 'eak_admin_update_order_item_status_design_full_reject';
                        }
                        $templatavals = [
                            'txt_order'=>$txtOrder,
                            'customer_name'=>$newCustomerName,
                            'product_name'=>$productName,
                            'item_status'=>__($itemStatusText),
                            'order_create_at'=>date('m/d/Y', strtotime($order->getCreatedAt())),
                            'item_price'=>$itemDesignPrice,
                            'myfit_mail'=>$myfistEmail,
                            'link_login'=>$loginUrl
                        ];
                        $send = $this->sendEmailToCustomer($email,$emailId,$templatavals, $storeId);
                        $resonse['send'] = $send['message'];
                    }
                    else {
                        $resonse['send'] = 'was disabled';
                    }
                }
                else if($status == 'delivered') {
                    // create invoice
                    $itemId = ''.$itemId;
                    $isCreateInvoice = $this->generateInvoice($order,$itemId,$qty,$totalPrice,$newId);
                    if($isCreateInvoice) {
                        $resonse['invoice'] = 'INvoice ok';
                    }
                    else {
                        $resonse['invoice'] = 'XIT';
                    }
                }
            }
            else {
                $resonse['message'] = $newId;
            }
        }
        if($resonse['status'] == 'success') {
            $this->messageManager->addSuccessMessage(__($resonse['message']));
        }
        else {
            $this->messageManager->addErrorMessage(__($resonse['message']));
        }
        return $this->jsonFactory->create()->setData($resonse);
    }
    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 generateInvoice($order, $itemId,$qty,$total,$previewId) {
//        $orderId = 1; //order id for which want to create invoice
//        $order = $this->getOrder($orderId);
        $isSend = false;
        if($order->canInvoice()) {
            $itemsArray = [$itemId=>$qty]; //here 80 is order item id and 2 is it's quantity to be invoice
            $shippingAmount = '0';
            $subTotal = $total;
            $baseSubtotal = $total;
            $grandTotal = $total;
            $baseGrandTotal = $total;
            $invoice = $this->_invoiceService->prepareInvoice($order, $itemsArray);
            $invoice->setShippingAmount($shippingAmount);
            $invoice->setSubtotal($subTotal);
            $invoice->setBaseSubtotal($baseSubtotal);
            $invoice->setGrandTotal($grandTotal);
            $invoice->setBaseGrandTotal($baseGrandTotal);
            $invoice->register();
            $transactionSave = $this->_transaction->addObject(
                $invoice
            )->addObject(
                $invoice->getOrder()
            );
            $transactionSave->save();
//            $this->invoiceSender->send($invoice);
            //send notification code
            $order->addStatusHistoryComment(
                __('Notified customer about invoice #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(true)
                ->save();
            if($invoice && $invoice->getId()) {
                $isSend = true;
                $updateCustomOrderItem = [
                    'custom_item_id'=>$previewId,
                    'invoice_id'=>$invoice->getId(),
                ];
                $this->savePreviewOrderItem($updateCustomOrderItem);
                // send email
                if($this->emailHelper->checkIsSendEmail('status_delivered',$order->getCustomerId())) {
                    $emailId = 'eak_admin_update_order_item_invoice';

                    $templatavals = [
                        'txt_order'=>$order->getIncrementId(),
                        'customer_name'=>$order->getCustomerName(),
                        'txt_invoice'=>$invoice->getIncrementId(),
                        'link'=>$this->_url->getUrl('advance_preview/index/index/').'invoice_id/'.$invoice->getId().'/item_id/'.$itemId.'/type/3'
                    ];
                    $send = $this->sendEmailToCustomer($order->getCustomerEmail(),$emailId,$templatavals);
                }

            }
        }
        return $isSend;
    }
    protected function getOrder($orderId) {
        $model =  $this->orderFactory->create();
        try {
            $this->resOrderFactory->create()->load($model,$orderId);
        }
        catch (\Exception $exception) {

        }
        return $model;
    }
    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;
    }
}
