<?php
/**
 * Webkul Software.
 *
 * @category Webkul
 *
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

 namespace Webkul\AdvanceSeoManager\Model\RichSnippet\Context\Product;

 use Magento\Store\Api\Data\StoreInterface;

class Offers implements ProductDataInterface
{

    private $storeManager;

    private $stockRegistry;
    
    public function __construct(
        StoreInterface $storeManager,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
    ) {
        $this->storeManager = $storeManager;
        $this->stockRegistry = $stockRegistry;
    }

    /**
     * inherit
     */
    public function getData($product)
    {
        
        $offerData = [
            "@type" => "Offer",
            "availability" => $this->getProductAvailability($product),
            "price" => $product->getFinalPrice(),
            "priceCurrency" => $this->getCurrentCurrency()
        ];
        return $offerData;
    }

    /**
     * get offer price
     *
     * @param  Magento\Catalog\Model\Product $product
     * @return decimal
     */
    public function getOfferPrice($product)
    {
        return $product->getPriceInfo()->getPrice("final_price")->getValue();
    }

    /**
     * get product availability
     *
     * @param  \Magento\Catalog\Model\Product $product
     * @return product
     */
    private function getProductAvailability($product)
    {
        try {
            $stockItem = $this->stockRegistry->getStockItem($product->getId());
            if ($stockItem->getIsInStock()) {
                return "http://schema.org/InStock";
            }
            return "http://schema.org/OutOfStock";
        } catch (\Exception $e) {
            // todo lo exception
            $this->logger->debug('Product Availability - '.$e->getMessage());
        }
    }

    /**
     * get current currency
     *
     * @param  \Magento\Catalog\Model\Product $product
     * @return product
     */
    private function getCurrentCurrency()
    {
        return $this->storeManager->getCurrentCurrency()->getCode();
    }
}
