<?php

namespace Autogedal\AtcPopup\Model;

use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;

class Popup extends \MageKey\AdcPopup\CustomerData\Popup
{
    public function getSectionData()
    {
        $data = [];
        if (!$this->dataHelper->isEnabled()) {
            return $data;
        }

        $items = $this->getAddedItems();
        if (!empty($items)) {
            $data = [
                'items' => $items,
                'product_list' => $this->getProductList($items)
            ];
        }
        return $data;
    }

    protected function getProductList(array $affectedItems)
    {
        $quote = $this->getQuote();
        foreach ($quote->getItems() as $item) {
            if (in_array($item->getId(), $affectedItems)) {
                $product = $item->getProduct();

                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $objectManager->get(\Magento\Framework\Registry::class)->register('product', $product);
                $block = $objectManager->get(\Magento\Framework\View\LayoutInterface::class)
                    ->createBlock(\Smartwave\Filterproducts\Block\CrossList::class);
                $block->setLayout($objectManager->get(\Magento\Framework\View\LayoutInterface::class));
                $block->setTemplate('Smartwave_Filterproducts::owl_list.phtml');

                $block->setData('image_width', 300);
                $block->setData('name', 'cross_product');
                $block->setData('column_count', 4);
                $block->setData('mode', 'grid');
                $block->setData('aspect_ratio', '1');

                $html = $block->toHtml();

                return [["html" => $html]];
            }
        }
    }

    protected function getProductListData(ProductCollection $productCollection)
    {
        $productList = [];
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        foreach ($productCollection as $product) {

            $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());

            $imageHelper = $this->imageHelper->init($product, 'mgk_adcpopup_product_list');
            $productList[] = [
                'product_id' => $product->getId(),
                'product_name' => $product->getName(),
                'product_sku' => $product->getSku(),
                'product_url' => $product->getUrlModel()->getUrl($product),
                'product_price' => $this->checkoutHelper->formatPrice($product->getFinalPrice()),
                'product_price_value' => $product->getFinalPrice(),
                'product_image' => [
                    'src' => $imageHelper->getUrl(),
                    'alt' => $imageHelper->getLabel(),
                    'width' => $imageHelper->getWidth(),
                    'height' => $imageHelper->getHeight(),
                ],
            ];
        }
        return $productList;
    }
}
