<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Model\Product;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Checkout\Model\Cart;
use Magento\Framework\Filter\LocalizedToNormalizedFactory;
use Magento\Framework\Locale\ResolverInterface;

class AddToCart
{
    /**
     * @var ResolverInterface
     */
    private $localeResolver;

    /**
     * @var Cart
     */
    private $cart;

    /**
     * @var LocalizedToNormalizedFactory
     */
    private $filterFactory;

    public function __construct(
        ResolverInterface $localeResolver,
        Cart $cart,
        LocalizedToNormalizedFactory $filterFactory
    ) {
        $this->localeResolver = $localeResolver;
        $this->cart = $cart;
        $this->filterFactory = $filterFactory;
    }

    /**
     * @param ProductInterface $product
     * @param array $params
     */
    public function addProductToCart(ProductInterface $product, array $params): void
    {
        if (isset($params['qty'])) {
            $filter = $this->filterFactory->create()->setOptions(['locale' => $this->localeResolver->getLocale()]);
            $params['qty'] = $filter->filter($params['qty']);
        }
        $related = $params['related_product'] ?? null;
        $this->cart->addProduct($product, $params);

        if (!empty($related)) {
            $this->cart->addProductsByIds(explode(',', $related));
        }

        $this->cart->save();
    }
}
