<?php
namespace TbiBank\FusionPay\Controller\Api;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\State;
use Magento\Framework\Message\ManagerInterface;

class AddToCart extends Action
{
    protected $cart;
    protected $productRepository;
    protected $resultJsonFactory;
    protected $appState;
    protected $messageManager;

    public function __construct(
        Context $context,
        Cart $cart,
        ProductRepository $productRepository,
        JsonFactory $resultJsonFactory,
        State $appState,
        ManagerInterface $messageManager
    ) {
        parent::__construct($context);
        $this->cart = $cart;
        $this->productRepository = $productRepository;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->appState = $appState;
        $this->messageManager = $messageManager;
    }

    /**
     * Adds a product to the cart based on the given scheme ID
     *
     * This action accepts a single parameter, 'scheme_id', which is the ID of
     * the scheme to be added to the cart. The action will first retrieve the
     * product ID associated with the given scheme ID. If no such product is
     * found, an exception is thrown. Otherwise, the product is added to the
     * cart with a quantity of 1. The action returns a JSON response with a
     * 'success' property set to true if the product is added successfully, or
     * false if there is an error. If there is an error, the JSON response will
     * contain an 'error' property with the error message.
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            //$params = $this->getRequest()->getParams();
            $params = json_decode($this->getRequest()->getContent(), true);

            $productId = $params['product'];
            $selectedConfigurableOption = $params['selected_configurable_option'];
            //$productOptions = $params['options'];

            $relatedProduct = $params['related_product'];
            $item = $params['item'];
            $formKey = $params['form_key'];
            $qty = $params['qty'];
            $schemeId = $params['scheme_id'];
            $downPayment = $params['downpayment'];
            
            if (!$productId) {
                throw new \Exception("Product not found for the given scheme ID.");
            }

            $product = $this->productRepository->getById($productId);
            $superAttributes = [];
            $options = [];

            // Loop through the $params array to find all keys that start with 'options['
            foreach ($params as $key => $value) {
                if (preg_match('/^options\[(\d+)\]$/', $key, $matches)) {
                    // $matches[1] contains the option ID (the number inside the square brackets)
                    $options[$matches[1]] = $value;
                }
                if (preg_match('/^super_attribute\[(\d+)\]$/', $key, $matches)) {
                    // $matches[1] contains the option ID (the number inside the square brackets)
                    $superAttributes[$matches[1]] = $value;
                }
            }

            $productParams = array(
                'form_key' => $formKey,
                'product' => $productId, //product Id
                'qty'   =>$qty, //quantity of product                
                'options' => $options,
                'selected_configurable_option' => $selectedConfigurableOption, // Configurable option if any
                'super_attribute' => $superAttributes,
                'scheme_id' => $schemeId,
                'downpayment' => $downPayment,
                );
            $this->cart->addProduct($product, $productParams); 
            $this->cart->save();

            $this->messageManager->addSuccessMessage(__('You added %1 to your shopping cart.', $product->getName()));
            $this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();

            return $result->setData(['success' => true, 'message' => __('Product added to cart successfully.')]);
        } catch (\Exception $e) {
            return $result->setData(['success' => false, 'error' => $e->getMessage()]);
        }
    }
}
