<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\CatalogSearch\Model\Search;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\CatalogInventory\Model\Stock;
use Magento\CatalogSearch\Model\Search\IndexBuilder as CatalogSearchIndexBuilder;
use Magento\Framework\DB\Select;
use Aitoc\PreOrders\Model\ResourceModel\ProductAttributes as ProductAttributesResourceModel;

/**
 * Class IndexBuilder
 */
class IndexBuilder
{
    /**
     * @var ScopeConfigInterface
     */
    private $config;

    /**
     * @var ProductAttributesResourceModel
     */
    private $productAttributesResourceModel;
    
    /**
     * @param ScopeConfigInterface $config
     */
    public function __construct(
        ScopeConfigInterface $config,
        ProductAttributesResourceModel $productAttributesResourceModel
    ) {
        $this->config = $config;
        $this->productAttributesResourceModel = $productAttributesResourceModel;
    }

    /**
     * @param CatalogSearchIndexBuilder $subject
     * @param Select $result
     * @return Select
     */
    public function afterBuild(
        CatalogSearchIndexBuilder $subject,
        Select $result
    ) {
        // TODO: from helper
        $isShowOutOfStock = $this->config->isSetFlag(
            'cataloginventory/options/show_out_of_stock',
            ScopeInterface::SCOPE_STORE
        );

        if ($isShowOutOfStock === false) {
            $result->reset('where');

            $tableName = $this
                ->productAttributesResourceModel
                ->getTable(ProductAttributesResourceModel::TABLE_NAME);
            $result->joinLeft(
                ['product_attributes' => $tableName],
                "search_index.entity_id = product_attributes.product_id AND product_attributes.attribute_code='pre_order_status'",
                ['value']
            );
            /**
             * TODO: pre-order status validation
             */
            $result->where('stock_index.stock_status = ? OR product_attributes.value = 1', Stock::DEFAULT_STOCK_ID);
        }

        return $result;
    }
}
