<?php
declare(strict_types=1);

namespace PortalPeople\AuthRedirect\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Controller\ResultFactory;

class Index extends Action
{
    protected $checkoutSession;
    protected $resultRedirectFactory;

    public function __construct(
        Context $context,
        CheckoutSession $checkoutSession,
        RedirectFactory $resultRedirectFactory
    ) {
        parent::__construct($context);
        $this->checkoutSession = $checkoutSession;
        $this->resultRedirectFactory = $resultRedirectFactory;
    }

    public function execute()
    {
        $quote = $this->checkoutSession->getQuote();

        // Reload cart items and totals
        $quote->collectTotals();
        $quote->getItemsCollection()->load();

        // Redirect if basket is empty
        if (count($quote->getAllVisibleItems()) === 0) {
            return $this->resultRedirectFactory->create()->setPath('checkout/cart');
        }

        // Otherwise show login form page
        return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
    }
}
