<?php
/**
 * Magento 2 Google Analytics 4 (GA4) GTM
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Anowave license that is
 * available through the world-wide-web at this URL:
 * https://www.anowave.com/license-agreement/
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category 	Anowave
 * @package 	Anowave_Ec
 * @copyright 	Copyright (c) 2026 Anowave (https://www.anowave.com/)
 * @license  	https://www.anowave.com/license-agreement/
 */

namespace Anowave\Ec\Helper;

use Magento\Store\Model\StoreManagerInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManagerInterface;

class Stock
{
    private Manager $manager;
    private StoreManagerInterface $storeManager;
    private StockRegistryInterface $stockRegistryInterface;

    // MSI dependencies (optional)
    private $getSalableQty = null;
    private $stockResolver = null;
    private $getSources = null;


    private ?int $stockId = null;
    private array $qtyCache = [];

    public function __construct(
        Manager $manager,
        ObjectManagerInterface $objectManagerInterface,
        StoreManagerInterface $storeManager,
        StockRegistryInterface $stockRegistryInterface,
        array $data = []
    ) {
        $this->manager = $manager;
        $this->storeManager = $storeManager;
        $this->stockRegistryInterface = $stockRegistryInterface;

        if ($this->manager->isEnabled('Magento_InventorySalesApi')) 
        {
            $this->getSalableQty    = $objectManagerInterface->get(\Magento\InventorySalesApi\Api\GetProductSalableQtyInterface::class);
            $this->stockResolver    = $objectManagerInterface->get(\Magento\InventorySalesApi\Api\StockResolverInterface::class);
            $this->getSources       = $objectManagerInterface->get(\Magento\InventoryApi\Api\GetSourceItemsBySkuInterface::class);
        }
    }

    private function getStockId(): ?int
    {
        if ($this->stockId === null && $this->stockResolver) 
        {
            $stock = $this->stockResolver->execute(\Magento\InventorySalesApi\Api\Data\SalesChannelInterface::TYPE_WEBSITE,$this->storeManager->getWebsite()->getCode());

            $this->stockId = $stock->getStockId();
        }
        return $this->stockId;
    }

    /**
     * Get available quantity for a SKU
     */
    public function getQty(string $sku): float
    {
        if (isset($this->qtyCache[$sku])) 
        {
            return $this->qtyCache[$sku];
        }

        $qty = 0.0;

        if ($this->getSources)
        {
            $sourceItems = $this->getSources->execute($sku);

            if (empty($sourceItems))
            {
                return $qty;
            }
        }

        // MSI mode
        if ($this->getSalableQty && $this->getStockId()) 
        {
            try 
            {
                $qty = $this->getSalableQty->execute($sku, $this->getStockId());
            } 
            catch (\Exception $e) 
            {
                $qty = 0.0;
            }
        }
        else 
        {
            try 
            {
                $stockItem = $this->stockRegistryInterface->getStockItemBySku($sku);

                return (float) $stockItem->getQty();
            } 
            catch (\Exception $e) 
            {
                return 0.0;
            }
        }

        $this->qtyCache[$sku] = $qty;

        return $qty;
    }

    /**
     * Check if product is saleable
     */
    public function isSaleable(Product $product): bool
    {
        // Legacy stock always works
        try 
        {
            $stock = $this->stockRegistryInterface->getStockItem($product->getId())->getIsInStock();

            return (bool)$stock;
        } 
        catch (\Exception $e) 
        {
            return false;
        }
    }
}