<?php

namespace Banyo\TrackOrder\Plugin\Customer;

use Magento\Customer\Controller\Account\LoginPost as CustomerLoginPost;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Controller\Result\Redirect;

class LoginPost
{
    /**
     * @var CustomerSession
     */
    protected $customerSession;

    /**
     * @var RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @param CustomerSession $customerSession
     * @param RedirectFactory $resultRedirectFactory
     * @param OrderRepositoryInterface $orderRepository
     * @param ManagerInterface $messageManager
     */
    public function __construct(
        CustomerSession $customerSession,
        RedirectFactory $resultRedirectFactory,
        OrderRepositoryInterface $orderRepository,
        ManagerInterface $messageManager
    ) {
        $this->customerSession = $customerSession;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->orderRepository = $orderRepository;
        $this->messageManager = $messageManager;
    }

    /**
     * After execute plugin
     *
     * @param CustomerLoginPost $subject
     * @param Redirect $result
     * @return Redirect
     */
    public function afterExecute(CustomerLoginPost $subject, $result)
    {
        // Check if login was successful
        if (!$this->customerSession->isLoggedIn()) {
            return $result;
        }

        // Check if we have order tracking data in session
        $trackOrderData = $this->customerSession->getTrackOrderRedirect();
        if (!$trackOrderData || !isset($trackOrderData['order_id']) || !isset($trackOrderData['email'])) {
            return $result;
        }

        $orderId = $trackOrderData['order_id'];
        $email = $trackOrderData['email'];
        $customerId = $this->customerSession->getCustomerId();

        try {
            $order = $this->orderRepository->get($orderId);

            // Verify the order belongs to the customer
            if ((int)$order->getCustomerId() === (int)$customerId &&
                strtolower($order->getCustomerEmail()) === strtolower($email)) {

                // Clear the session data
                $this->customerSession->unsTrackOrderRedirect();

                // Redirect to order view
                $redirect = $this->resultRedirectFactory->create();
                return $redirect->setPath('sales/order/view', ['order_id' => $order->getEntityId()]);
            }
        } catch (NoSuchEntityException $e) {
            $this->messageManager->addErrorMessage(__('The order you are trying to access does not exist.'));
        }

        // Clear the session data even if there was an error
        $this->customerSession->unsTrackOrderRedirect();

        return $result;
    }
}
