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

namespace Mageants\SimpleConfigurable\Model\Sitemap\ResourceModel\Catalog;

use Magento\Sitemap\Model\ResourceModel\Catalog\Product as SitemapProduct;
use Magento\Sitemap\Helper\Data as SitemapData;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Catalog\Model\Product\Gallery\ReadHandler;
use Magento\Catalog\Model\ResourceModel\Product\Gallery;
use Mageants\SimpleConfigurable\Helper\Data;
use Magento\Catalog\Model\Product\Media\Config as MediaConfig;
use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator;
use Magento\Sitemap\Model\Source\Product\Image\IncludeImage;

class Product extends SitemapProduct
{
    /**
     * @var Data
     */
    private $data;
    
    /**
     * Product constructor.
     *
     * @param Context $context
     * @param StoreManagerInterface $storeManager
     * @param ProductResource $productResource
     * @param ReadHandler $mediaGalleryReadHandler
     * @param Gallery $mediaGalleryResourceModel
     * @param Visibility $productVisibility
     * @param Status $productStatus
     * @param SitemapData $sitemapData
     * @param MediaConfig $mediaConfig
     * @param Data $data
     * @param string $connectionName
     */
    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        ProductResource $productResource,
        ReadHandler $mediaGalleryReadHandler,
        Gallery $mediaGalleryResourceModel,
        Visibility $productVisibility,
        Status $productStatus,
        SitemapData $sitemapData,
        MediaConfig $mediaConfig,
        Data $data,
        $connectionName = null
    ) {
        parent::__construct(
            $context,
            $sitemapData,
            $productResource,
            $storeManager,
            $productVisibility,
            $productStatus,
            $mediaGalleryResourceModel,
            $mediaGalleryReadHandler,
            $mediaConfig,
            $connectionName
        );

        $this->data = $data;
    }

    /**
     * Override getCollection
     *
     * @param null|string|bool|int|\Magento\Store\Model\Store $storeId
     * @return array|bool
     */
    public function getCollection($storeId, $productId = null)
    {
        if (!$this->data->isEnable($storeId) && !$this->data->generateChildUrls($storeId)) {
            return parent::getCollection($storeId);
        }

        $products = [];
        $store = $this->_storeManager->getStore($storeId);
        if (!$store) {
            return false;
        }

        $conn = $this->getConnection();
        $select = $conn->select()->from(
            ['e' => $this->getMainTable()],
            [$this->getIdFieldName(), $this->_productResource->getLinkField(), 'updated_at']
        )->joinInner(
            ['w' => $this->getTable('catalog_product_website')],
            'e.entity_id = w.product_id',
            []
        )->joinLeft(
            ['url_rewrite' => $this->getTable('url_rewrite')],
            'e.entity_id = url_rewrite.entity_id AND url_rewrite.is_autogenerated = 1'
            . ' AND url_rewrite.metadata IS NULL'
            . $conn->quoteInto(' AND url_rewrite.store_id = ?', $store->getId())
            . $conn->quoteInto(' AND url_rewrite.entity_type = ?', ProductUrlRewriteGenerator::ENTITY_TYPE),
            ['url' => 'request_path']
        )->where(
            'w.website_id = ?', $store->getWebsiteId()
        );
        $this->_select = $select;
        if ($productId) {
            $select->where('e.entity_id IN (?)', $productId);
        } else {
            $this->_addFilter($store->getId(), 'visibility', $this->_productVisibility->getVisibleInSiteIds(), 'in');
        }

        $this->_addFilter($store->getId(), 'status', $this->_productStatus->getVisibleStatusIds(), 'in');

        $imagePolicy = $this->_sitemapData->getProductImageIncludePolicy($store->getId());
        if ($imagePolicy !== IncludeImage::INCLUDE_NONE) {
            $this->_joinAttribute($store->getId(), 'name', 'name');
            if ($imagePolicy === IncludeImage::INCLUDE_ALL) {
                $this->_joinAttribute($store->getId(), 'thumbnail', 'thumbnail');
            } elseif ($imagePolicy === IncludeImage::INCLUDE_BASE) {
                $this->_joinAttribute($store->getId(), 'image', 'image');
            }
        }

        $query = $conn->query($this->prepareSelectStatement($select));
        while ($row = $query->fetch()) {
            $product = $this->_prepareProduct($row, $store->getId());
            $products[$product->getId()] = $product;
        }

        return $products;
    }
}