<?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\Observer\Frontend;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface as MessageManagerInterface;
class ProductLoadAfter implements ObserverInterface
{
    protected $request;
    protected $httpContext;
    protected $orderItemRepository;
    protected $customerFactory;
    protected $resCustomerFactory;
    protected $customerSession;
    protected $redirect;
    protected $manager;
    protected $orderFactory;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Model\ResourceModel\CustomerFactory $resCustomerFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        MessageManagerInterface $manager,
        \Magento\Sales\Model\OrderFactory $orderFactory

    )
    {
        $this->request = $request;
        $this->httpContext = $httpContext;
        $this->orderItemRepository = $orderItemRepository;
        $this->customerFactory = $customerFactory;
        $this->resCustomerFactory = $resCustomerFactory;
        $this->customerSession = $customerSession;
        $this->redirect = $redirect;
        $this->manager = $manager;
        $this->orderFactory = $orderFactory;
    }
    public function execute(Observer $observer)
    {
        // TODO: Implement execute() method.
        $reUpItemId = (int)$this->request->getParam('re_up',0);
       /* $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);*/

        if($reUpItemId > 0) {
            $customerId = $this->getCustomerId();
            if($customerId <= 0) {
                $this->manager->addErrorMessage(__('Please login to upload design'));
                $controller = $observer->getControllerAction();
                $this->redirect->redirect($controller->getResponse(), 'sales/order/history');
            }
            else {
                $item = $this->getOrderItem($reUpItemId);
                if(!$item) {
//                $logger->info('after product load redirect '. $reUpItemId);
                    $this->manager->addErrorMessage(__('Item not found, please check again or contact admin'));
                    $controller = $observer->getControllerAction();
                    $this->redirect->redirect($controller->getResponse(), 'sales/order/history');
                }
                else {
                    $orderId = $item->getOrderId();
                    $_order = $this->orderFactory->create()->load($orderId);
                    if($_order && $_order->getCustomerId() == $this->getCustomerId()) {

                    }
                    else {
                        $this->manager->addErrorMessage(__('Item not found, please check again or contact admin'));
                        $controller = $observer->getControllerAction();
                        $this->redirect->redirect($controller->getResponse(), 'sales/order/history');
                    }
//                $logger->info('after product load OK '. $reUpItemId);
                }
            }

        }
        return $this;
    }
    public function getOrderItem($itemId)
    {
        /** @var \Magento\Sales\Model\Order\Item $itemCollection*/
        $item = null;
        try {
            $item = $this->orderItemRepository->get($itemId);
        }
        catch (\Exception $exception) {

        }
        return $item;
//        return  $item->getProductOptionByCode('info_buyRequest');
    }
    protected function getCustomerId() {
        $customerId = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();


        }
        return $customerId;
    }

    /**
     * @return bool
     */
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
}
