<?php


namespace Magetop\Advancepreview\Helper;


use Magento\Catalog\Model\ResourceModel\ProductFactory;

/**
 * Class CovidOrderHelper
 * @package Magetop\Takecare\Helper
 */
class OrderHelper extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var \Magento\Catalog\Model\Product
     */
    protected $_product;
    /**
     * @var \Magento\Framework\Data\Form\FormKey
     */
    protected $_formkey;
    /**
     * @var \Magento\Quote\Model\QuoteFactory
     */
    protected $quote;
    /**
     * @var \Magento\Quote\Model\QuoteManagement
     */
    protected $quoteManagement;
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface
     */
    protected $customerRepository;
    /**
     * @var \Magento\Sales\Model\Service\OrderService
     */
    protected $orderService;
    protected $productFactory;
    protected $resProductFactory;
    protected $previewOrderFactory;
    protected $json;
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Serialize\Serializer\Json $json,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Framework\Data\Form\FormKey $formkey,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Sales\Model\Service\OrderService $orderService,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $previewOrderFactory
    ) {
        $this->_storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->_formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        $this->resProductFactory = $resProductFactory;
        $this->previewOrderFactory = $previewOrderFactory;
        $this->json = $json;
        parent::__construct($context);
    }


    public function createMageOrder($orderData = []) {
        $response = array(
            'status'=>'error',
            'order'=>null,
            'message'=>'Can not create order'
        );
        try {
            $store = $this->_storeManager->getStore();
            $websiteId = $this->_storeManager->getStore()->getWebsiteId();
            $customer = $this->customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $customer->loadByEmail($orderData['email']);// load customet by email address
            if (!$customer->getEntityId()) {
                //If not avilable then create this customer
                $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderData['shipping_address']['firstname'])
                    ->setLastname($orderData['shipping_address']['lastname'])
                    ->setEmail($orderData['email'])
                    ->setPassword($orderData['email']);
                $customer->save();
            }
            $quote = $this->quote->create(); //Create object of quote
            $quote->setStore($store); //set store for which you create quote
            // if you have allready buyer id then you can load customer directly
            $customer = $this->customerRepository->getById($customer->getEntityId());
            $quote->setCurrency();
            $quote->assignCustomer($customer); //Assign quote to customer

            //add items in quote
            $im = 0;
            foreach ($orderData['items'] as $item) {
                $im++;
//                $product=$this->_product->load($item['product_id']);
                $product = $this->getProductById($item['product_id']);
                if (!$product) {
                    continue;
                }
                $addOptions = [
                    [
                        'label' => 'Design In',
                        'value' => time().'_'.$im,
                    ]
                ];
                $bookOptions = $this->json->serialize($addOptions);
                $product->addCustomOption('additional_options', $bookOptions);
                $product->setPrice($item['price']);
                $itemParams = isset($item['item_params']) ? $item['item_params'] : array();
                if (!isset($itemParams['qty'])) {
                    continue;
                }
                $request = new \Magento\Framework\DataObject($itemParams);
                $quote->addProduct(
                    $product,
                    $request
                );

            }

            //Set Address to quote
            $quote->getBillingAddress()->addData($orderData['billing_address']);
            $quote->getShippingAddress()->addData($orderData['shipping_address']);

            // Collect Rates and Set Shipping & Payment Method

            $shippingAddress=$quote->getShippingAddress();
            $shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('freeshipping_freeshipping'); //shipping method
            $quote->setPaymentMethod('checkmo'); //payment method
            $quote->setInventoryProcessed(false); //not effetc inventory
            $quote->save(); //Now Save quote and your quote is ready

            // Set Sales Order Payment
            $quote->getPayment()->importData(['method' => 'checkmo']);

            // Collect Totals & Save Quote
            $quote->collectTotals()->save();

            // Create Order From Quote
            $order = $this->quoteManagement->submit($quote);
            $order->setEmailSent(1); // send default email
            if($order) {
                $response['status'] = 'success';
                $response['message'] = '';
                $response['order'] = $order;
//                $response['order'] = $order->getData();
            }
//            $order->setEmailSent(1); // send default email
        }
        catch (\Exception $exception) {
            $response['message'] = $exception->getMessage();
        }
        return $response;
    }
    public function getPreviewOrderItemDetail($item) {
        return $item->getProductOptionByCode('info_buyRequest');
    }
    protected function getProductById($productId) {
        $product = $this->productFactory->create();
        try {
            $this->resProductFactory->create()->load($product,$productId);
        }
        catch (\Exception $exception) {

        }
        return $product;
    }
    public function checkIncoiceAndItemId($invoieId, $itemId) {
        $collection = $this->previewOrderFactory->create()
            ->addFieldToSelect(array('custom_item_id'))
            ->addFieldToFilter('invoice_id',$invoieId)
            ->addFieldToFilter('item_id',$itemId);
        if($collection && $collection->getSize() > 0) {
            return true;
        }
        return  false;
    }

}
