<?php
/**
 * @author    Webarian Team
 * @copyright Copyright (c) 2020 Webarian (https://www.webariansoftwares.com/)
 * @package   Webarian_PromoPopup
 */
namespace Webarian\Workshop\Controller\Register;

use Magento\Framework\App\Action\Context;
use Webarian\Workshop\Model\RegistrationFactory;
use Webarian\Workshop\Model\WorkshopFactory;
use Magento\Checkout\Model\Session;
use Psr\Log\LoggerInterface;

class Save extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $_registrationFactory;
    protected $_workshopFactory;
    protected $_resultRedirectFactory;
    protected $formKey;
    protected $cart;
    protected $product;
    protected $_session;
    protected $_messageManager;
    protected $_logger;

    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        RegistrationFactory $registrationFactory,
        WorkshopFactory $workshopFactory,
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Framework\Data\Form\FormKey $formKey,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Catalog\Model\Product $product,
        Session $session,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        LoggerInterface $logger
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        $this->_registrationFactory = $registrationFactory;
        $this->_workshopFactory = $workshopFactory;
        $this->_resultRedirectFactory = $resultRedirectFactory;
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;
        $this->_session = $session;
        $this->_messageManager = $messageManager;
        $this->_logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
        try {
            $data = $this->getRequest()->getParams();
            $workshopId = $data['workshop_id'];

            // Log workshop ID for debugging
            $this->_logger->debug('Workshop ID: ' . $workshopId);

            $workshop = $this->_workshopFactory->create()->load($workshopId);
            $productId = $workshop->getData('product_id');
            $temp = 1;
            $message = '';

            $allItems = $this->cart->getQuote()->getAllItems();
            foreach ($allItems as $key => $item) {
                if ($item->getProductId() == $productId) {
                    $temp = 0;
                    $message = "Workshop has already been added!";
                    break;
                }
            }

            if ($temp) {
                $params = [
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productId,
                    'qty' => 1 // Quantity of product
                ];

                // Load the product based on product ID
                $_product = $this->product->load($productId);
                $this->cart->addProduct($_product, $params);
                $this->cart->save();

                // Log success message
                $this->_logger->info('Successfully added product to cart.');

                $quote = $this->_session->getQuote();
                $quoteid = $quote->getId();

                $data['status'] = 'unpaid';
                $data['quote_id'] = $quoteid;
                $registerObj = $this->_registrationFactory->create();

                $coll = $registerObj->getCollection()
                    ->addFieldToFilter('workshop_id', $workshopId)
                    ->addFieldToFilter('quote_id', $quoteid);

                if ($coll->getSize() > 0) {
                    $this->_logger->info('Registration already exists for workshop and quote.');
                    $message = "Workshop registration already exists!";
                } else {
                    $registerObj->setData($data);
                    $registerObj->save();
                    $message = "Successfully added workshop!";
                    $this->_logger->info('Registration saved successfully.');
                }

                $this->_messageManager->addSuccess(__($message));
            }
        } catch (\Exception $ex) {
            // Log error message
            $this->_logger->error('Error: ' . $ex->getMessage());

            // Add error message to message manager
            $this->_messageManager->addError(__('Error: %1', $ex->getMessage()));
        }

        $resultRedirect = $this->_resultRedirectFactory->create();
        return $resultRedirect->setPath('checkout/cart');
    }
}
