<?php

namespace Banyo\CustomProduct\Controller\Form;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Registry;

class Index extends Action implements HttpGetActionInterface
{
    protected $resultPageFactory;
    protected $productRepository;
    protected $registry;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ProductRepositoryInterface $productRepository,
        Registry $registry
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->productRepository = $productRepository;
        $this->registry = $registry;
    }

    public function execute()
    {
        $productId = $this->getRequest()->getParam('id');

        if ($productId) {
            try {
                $product = $this->productRepository->getById($productId);
                // Register product globally
                if (!$this->registry->registry('current_product')) {
                    $this->registry->register('current_product', $product);
                }
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage(__('Product not found.'));
                return $this->_redirect('/');
            }
        }

        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('Product Information Form'));
        return $resultPage;
    }
}
