<?php
/**
 * @category Mageants SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */

namespace Mageants\SimpleConfigurable\Model\Sitemap\ItemProvider;

use Magento\Sitemap\Model\ItemProvider\Product as SitemapProduct;
use Magento\Sitemap\Model\ItemProvider\ConfigReaderInterface;
use Magento\Sitemap\Model\ResourceModel\Catalog\ProductFactory;
use Magento\Sitemap\Model\SitemapItemInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Mageants\SimpleConfigurable\Helper\Data;

class Product extends SitemapProduct
{
    /**
     * @var ProductFactory
     */
    private $productFactory;

    /**
     * @var SitemapItemInterfaceFactory
     */
    private $itemFactory;

    /**
     * @var ConfigReaderInterface
     */
    private $configReader;

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

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

    /**
     * @var Data
     */
    private $data;

    /**
     * Product constructor.
     *
     * @param ConfigReaderInterface $configReader
     * @param ProductFactory $productFactory
     * @param SitemapItemInterfaceFactory $itemFactory
     * @param ProductRepositoryInterface $productRepository
     * @param StoreManagerInterface $storeManager
     * @param Data $data
     */
    public function __construct(
        ConfigReaderInterface $configReader,
        ProductFactory $productFactory,
        SitemapItemInterfaceFactory $itemFactory,
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManager,
        Data $data
    ) {
        parent::__construct($configReader, $productFactory, $itemFactory);
        $this->productFactory = $productFactory;
        $this->itemFactory = $itemFactory;
        $this->configReader = $configReader;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->data = $data;
    }

    /**
     * Get sitemap items for the given store
     *
     * @param int $storeId
     * @return array
     */
    public function getItems($storeId)
    {
        if (!$this->data->isEnable($storeId) || ($this->data->isEnable($storeId) && !$this->data->generateChildUrls($storeId))) {
            return parent::getItems($storeId);
        }

        $collection = $this->productFactory->create()->getCollection($storeId);
        $items = [];

        foreach ($collection as $item) {
            $items[] = $this->itemFactory->create([
                'url' => $item->getUrl(),
                'updatedAt' => $item->getUpdatedAt(),
                'images' => $item->getImages(),
                'priority' => $this->configReader->getPriority($storeId),
                'changeFrequency' => $this->configReader->getChangeFrequency($storeId),
            ]);

            $product = $this->productRepository->getById($item->getId());
            if ($product->getTypeId() === 'configurable') {
                foreach ($product->getTypeInstance()->getUsedProducts($product) as $childProduct) {
                    if ($childProduct->isSalable() && !isset($collection[$childProduct->getId()])) {
                        $child = $this->productFactory->create()->getCollection($storeId, $childProduct->getId());
                        $suffix = $this->storeManager->getStore($storeId)->getConfig('catalog/seo/product_url_suffix');
                        if (isset($child[$childProduct->getId()])) {
                            $items[] = $this->itemFactory->create([
                                'url' => $childProduct['url_key'] . $suffix,
                                'updatedAt' => $child[$childProduct->getId()]->getUpdatedAt(),
                                'images' => $child[$childProduct->getId()]->getImages(),
                                'priority' => $this->configReader->getPriority($storeId),
                                'changeFrequency' => $this->configReader->getChangeFrequency($storeId),
                            ]);
                        }
                    }
                }
            }
        }

        return $items;
    }
}