<?php

namespace MNM\Spitzner\Plugin\Stockstatus;

class AddDefaultStockWrapper
{
    /**
     * @var \Magento\CatalogInventory\Api\StockRegistryInterface
     */
    private $stockRegistry;
    
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;
    
    /**
     * 
     * @var unknown
     */
    private $product;
    
    /**
     * 
     * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    public function __construct(\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Magento\Store\Model\StoreManagerInterface $storeManager)
    {
        $this->stockRegistry = $stockRegistry;
        $this->storeManager = $storeManager;
    }
    
    /**
     * Modify stock status
     *
     * @param \Amasty\Stockstatus\Helper\Data $subject
     * @param callable $proceed
     * @param $product
     * @param bool $addWrapper
     * @param bool $isProductList
     * @param $storeId
     * @return NULL
     */
    public function beforeShowStockStatus(\Amasty\Stockstatus\Helper\Data $subject, 
                                            $product,
                                            $addWrapper = false,
                                            $isProductList = false,
                                            $storeId = null)
    {
        $this->product = $product;
        
        return null;
    }
    
    /**
     * 
     * @param \Amasty\Stockstatus\Helper\Data $subject
     * @param string $result
     * @return string
     */
    public function afterShowStockStatus(\Amasty\Stockstatus\Helper\Data $subject, $result)
    {   
        $beginning =    '<div class="stock">';
        $bl =           strlen($beginning);
        
        if(strpos($result, $beginning) === 0)
        {
            $stockStatus = $this->stockRegistry->getStockStatus($this->product->getId(), 
                                                                $this->storeManager->getWebsite()->getId());
            
            if(!$stockStatus->getStockStatus())
            {
                $result = '<div class="stock unavailable">'.'<span class="default-stock">'.substr($result, $bl, strpos($result, '<span') - $bl).'</span></div>';
            }
            else
            {
                $result = $beginning.
                        '<span class="default-stock">'.
                        substr($result, $bl, strpos($result, '<span') - $bl).
                        '</span>'.substr($result, strpos($result, '<span'));
            }
        }
        
        return $result;
    }
}