<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Plugin\Categories;

use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
use WriteTextAI\WriteTextAI\Ui\DataProvider\Categories\ListingDataProvider;
use WriteTextAI\WriteTextAI\Helper\Categories\Fields as CategoryFieldsHelper;

class AddAttributesToUiDataProvider
{
    /** @var AttributeRepositoryInterface */
    protected $attributeRepository;

    /** @var ProductMetadataInterface */
    protected $productMetadata;

    /** @var CategoryFieldsHelper */
    protected $categoryFieldsHelper;

    /**
     * Constructor
     *
     * @param AttributeRepositoryInterface $attributeRepository
     * @param ProductMetadataInterface $productMetadata
     * @param CategoryFieldsHelper $categoryFieldsHelper
     */
    public function __construct(
        AttributeRepositoryInterface $attributeRepository,
        ProductMetadataInterface $productMetadata,
        CategoryFieldsHelper $categoryFieldsHelper
    ) {
        $this->attributeRepository = $attributeRepository;
        $this->productMetadata = $productMetadata;
        $this->categoryFieldsHelper = $categoryFieldsHelper;
    }

    /**
     * Get Search Result after plugin
     *
     * @param ListingDataProvider $subject
     * @param SearchResult $result
     * @return SearchResult
     */
    public function afterGetSearchResult(ListingDataProvider $subject, SearchResult $result)
    {
        if ($result->isLoaded()) {
            return $result;
        }

        $edition = $this->productMetadata->getEdition();

        $column = in_array($edition, ['Enterprise', 'B2B']) ? 'row_id' : 'entity_id';

        // join Magento stores
        // this should go first before joining attributes
        $result->getSelect()->join(
            ['store' => 'store'],
            '',
            ['store_id' => 'store.store_id']
        );
        
        $mappingSettings = $this->categoryFieldsHelper->getMappingSettings();

        $attributes = [
            'name' => 'name',
            'url_path' => 'path',
            'is_active' => 'status',
            $mappingSettings['page_title'] => 'mg_page_title',
            $mappingSettings['page_description'] => 'mg_page_description',
            $mappingSettings['category_description'] => 'mg_category_description',
            'image' => 'thumbnail'
        ];

        $defaultStore = \Magento\Store\Model\Store::DEFAULT_STORE_ID;

        foreach ($attributes as $attributeCode => $tableAlias) {
            $attribute = $this->attributeRepository->get('catalog_category', $attributeCode);
            $backendTable = $attribute->getBackendTable();
            $attributeId = $attribute->getAttributeId();

            // join attribute value for current store
            $result->getSelect()->joinLeft(
                [$tableAlias => $backendTable],
                "{$tableAlias}.{$column} = main_table.{$column} AND 
                    {$tableAlias}.attribute_id = {$attributeId} AND 
                    store.store_id = {$tableAlias}.store_id",
                [$tableAlias => "{$tableAlias}.value"]
            );

            // join attributes value for default store
            $result->getSelect()->joinLeft(
                ["default_{$tableAlias}" => $backendTable],
                "default_{$tableAlias}.{$column} = main_table.{$column} AND 
                    default_{$tableAlias}.attribute_id = {$attributeId} AND 
                    default_{$tableAlias}.store_id = {$defaultStore}",
                ["default_{$tableAlias}" => "default_{$tableAlias}.value"]
            );
        }
        
        // join Write Ai Categories table
        $result->getSelect()->joinLeft(
            ['wtai_categories' => 'writetextai_writetextai_categories_store'],
            'wtai_categories.category_id = main_table.' . $column . ' AND store.store_id = wtai_categories.store_id',
            [
                'edited_at' => 'wtai_categories.edited_at',
                'transferred_at' => 'wtai_categories.transferred_at'
            ]
        );

        $result->getSelect();

        return $result;
    }
}
