<?php

namespace Banyo\CustomProduct\Controller\Form;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;

class Submit extends Action
{
    protected $productRepository;
    protected $resultRedirectFactory;
    protected $transportBuilder;
    protected $storeManager;
    protected $messageManager;
    protected $formKeyValidator;

    public function __construct(
        Context                    $context,
        ProductRepositoryInterface $productRepository,
        TransportBuilder           $transportBuilder,
        StoreManagerInterface      $storeManager,
        ManagerInterface           $messageManager,
        FormKeyValidator           $formKeyValidator
    )
    {
        parent::__construct($context);
        $this->productRepository = $productRepository;
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->messageManager = $messageManager;
        $this->formKeyValidator = $formKeyValidator;
    }

    public function execute()
    {
        $request = $this->getRequest();

        // Optional: Form key validation for CSRF protection
        if (!$this->formKeyValidator->validate($request)) {
            $this->messageManager->addErrorMessage(__('Invalid form key.'));
            return $this->_redirect('/');
        }

        try {
            $name = $request->getParam('customer_name');
            $email = $request->getParam('customer_email');
            $productId = $request->getParam('product_id');

            $product = $this->productRepository->getById($productId);
            $productUrl = $product->getProductUrl() . '?reveal_price=true';

            $emailTemplateVars = [
                'name' => $name,
                'email' => $email,
                'product_name' => $product->getName(),
                'sku' => $product->getSku(),
                'price' => $product->getFinalPrice(),
                'product_url' => $productUrl,
            ];

            $this->sendEmail($email, $emailTemplateVars);

            $this->messageManager->addSuccessMessage(__('Thank you. We have received your request.'));
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('There was an error processing your request: ') . $e->getMessage());
        }

        return $this->_redirect('/');
    }

    protected function sendEmail($customerEmail, array $templateVars)
    {
        $storeId = $this->storeManager->getStore()->getId();

        $transport = $this->transportBuilder
            ->setTemplateIdentifier('click_for_price_email')
            ->setTemplateOptions([
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $storeId,
            ])
            ->setTemplateVars($templateVars)
            ->setFrom([
                'email' => 'sales@example.com', // Set sender email or use `general`
                'name' => 'Sales Team'
            ])
            ->addTo($customerEmail)
            ->getTransport();

        $transport->sendMessage();
    }
}
