<?php
namespace MNM\Spitzner\Helper;

use Magento\Catalog\Pricing\Price;
use Magento\GroupedProduct\Model\Product\Type\Grouped;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\View\LayoutInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Area;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     *
     * @var \Magento\Framework\Pricing\Helper\Data
     */
    protected $_priceHelper;

    /**
     * Layout
     *
     * @var LayoutInterface
     */
    protected $_layout;

    /**
     *
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var TransportBuilder
     */
    protected $transportBuilder;

    /**
     * @var StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     *
     * @param Context $context
     * @param Data $_priceHelper
     * @param LayoutInterface $_layout
     * @param ProductRepositoryInterface $productRepository
     * @param TransportBuilder $transportBuilder
     * @param StateInterface $inlineTranslation
     * @param StoreManagerInterface|null $storeManager
     */
    public function __construct(
        Context $context,
        \Magento\Framework\Pricing\Helper\Data $_priceHelper,
        LayoutInterface $_layout,
        ProductRepositoryInterface $productRepository,
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        StoreManagerInterface $storeManager = null)
    {
        $this->_priceHelper = $_priceHelper;
        $this->_layout = $_layout;
        $this->productRepository = $productRepository;
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class);

        parent::__construct($context);
    }

    /**
     *
     * @param int $productId
     * @return string|unknown
     */
    public function getSpiInhalt($productId)
    {
        $return =   '';
        $volume = 	$this->getProductAttributeText($productId, 'spi_inhalt');

        preg_match('/[\d]+ml/', $volume, $matches);
        if(count($matches))
        {
            $return = str_replace('1000ml', '1L', $volume);
        }

        return $return;
    }

    /**
     *
     * @param int $productId
     * @param string $attribute
     * @return string|unknown
     */
    public function getProductAttributeText($productId, $attribute)
    {
        $product =  $this->productRepository->getById($productId);

        return $product->getAttributeText($attribute);
    }

    /**
     *
     * @param unknown $product
     * @return boolean
     */
    public function getProductGrouped($product)
    {
        if(!is_object($product))
        {
            $product = $this->productRepository->getById($product);
        }

        return $product->getTypeId() == Grouped::TYPE_CODE;
    }

    /**
     *
     * @param unknown $product
     * @return string
     */
    public function getProductPricePerUnit($product)
    {
        if(!is_object($product))
        {
            $product = $this->productRepository->getById($product);
        }

        $grouped =          $this->getProductGrouped($product);
        $normalizedPrice =  '';
        $return =           '';

        if(!$grouped)
        {
            $normalizedPrice = self::getNormalizedPrice($product);
        }
        else
        {
            $normalizedPrice = 0;

            foreach($product->getTypeInstance()->getAssociatedProducts($product) as $_child)
            {
                $np = self::getNormalizedPrice($_child);

                if(!is_numeric($np))
                {
                    $normalizedPrice = $np;

                    break;
                }
                elseif($normalizedPrice == 0 || $np < $normalizedPrice)
                {
                    $normalizedPrice = $np;
                }
            }
        }

        $price = $this->_priceHelper->currency($normalizedPrice, true, false);
        $unit =  $grouped ? '1000' : $product->getData('spi_normalized_volume');
        $unit .= is_numeric($product->getData('spi_normalized_volume')) ? 'ml' : '';

        return $price.' / '.str_replace('1000ml', '1L', $unit);
    }

    /**
     *
     * @param unknown $product
     * @return number|string
     */
    protected static function getNormalizedPrice($product)
    {
        $finalPrice = 		$product->getPriceInfo()->getPrice(Price\FinalPrice::PRICE_CODE)->getAmount()->getValue();
        $volume = 			intval($product->getAttributeText('spi_inhalt'));
        $normalizedVolume = $product->getData('spi_normalized_volume');

        if($volume > 0 && is_numeric($normalizedVolume))
        {
            $normalizedVolume = intval($normalizedVolume);
            $normalisedPrice = 	($finalPrice / $volume) * $normalizedVolume;
        }
        else
        {
            $normalisedPrice = $product->getData('spi_normalized_price');
        }

        return $normalisedPrice;
    }

    /**
     * Create new block
     *
     * @param string $blockName
     * @param string $template
     */
    public function getBlock($blockName, $template) {

        $block = $this->_layout
                    ->createBlock($blockName)
                    ->setTemplate($template);

        return $block;
    }

    /**
     * Send email
     *
     * @param string $to
     * @param string $template
     * @param array $variables
     * @return void
     */
    public function sendMail(string $to, string $template, array $variables = [])
    {
        $this->inlineTranslation->suspend();

        try {
            $transport = $this->transportBuilder
                ->setTemplateIdentifier($template)
                ->setTemplateOptions(
                    [
                        'area' => Area::AREA_FRONTEND,
                        'store' => $this->storeManager->getStore()->getId()
                    ])
                ->setTemplateVars($variables)
                ->setFrom(['name' => 'Spitzner Webshop', 'email' => 'wellness@spitzner.de'])
                ->addTo($to)
                ->getTransport();

            $transport->sendMessage();
        } finally {
            $this->inlineTranslation->resume();
        }
    }
}