<?php
declare(strict_types=1);
namespace Autogedal\Extend\Plugin;


use Aitoc\DeleteOrders\Model\ResourceModel\Archive\Grid\Collection as ArchiveCollection;
use Magento\Framework\DB\Select;
use Magento\Sales\Model\ResourceModel\Order\Grid\Collection as OrderCollection;

/**
 * Class FilterCollection
 * Class provides after Plugin on Magento\Framework\View\Element\UiComponent\DataProvider\Reporting::search
 * to edit data in order grid collection
 */
class FilterCollection
{
    /**
     * After search method
     *
     * @param $subject
     * @param $collection
     * @return ArchiveCollection|OrderCollection|mixed
     */
    public function afterSearch($subject, $collection): mixed
    {
        if ($collection instanceof OrderCollection && !$collection->getFlag('created_at_filter')) {
            $wherePart = $collection->getSelect()->getPart(Select::WHERE);
            foreach ($wherePart as $key => $wherePartItem) {
                if (str_contains($wherePartItem, '`created_at`') !== false) {
                    $wherePart[$key] = str_replace('`created_at`', 'created_at', $wherePartItem);
                }
                if (str_contains($wherePartItem, '`sku`') !== false) {
                    $wherePart[$key] = str_replace('`sku`', '`soi_sku`.`sku`', $wherePartItem);
                }
                if (str_contains($wherePartItem, '`bundle_sku`') !== false) {
                    $wherePart[$key] = str_replace('`bundle_sku`', '`soi_sku_bundle`.`sku`', $wherePartItem);
                }
            }
            $collection->getSelect()->setPart(Select::WHERE,$wherePart);
            $collection->setFlag('created_at_filter', true);
        } elseif ($collection instanceof ArchiveCollection && !$collection->getFlag('created_at_filter')) {
            $wherePart = $collection->getSelect()->getPart(Select::WHERE);
            foreach ($wherePart as $key => $wherePartItem) {
                if (str_contains($wherePartItem, '`created_at`') !== false) {
                    $wherePart[$key] = str_replace('`created_at`', '`order_grid_table`.`created_at`', $wherePartItem);
                }
                if (str_contains($wherePartItem, '`sku`') !== false) {
                    $wherePart[$key] = str_replace('`sku`', '`soi_sku`.`sku`', $wherePartItem);
                }
                if (str_contains($wherePartItem, '`bundle_sku`') !== false) {
                    $wherePart[$key] = str_replace('`bundle_sku`', '`soi_sku_bundle`.`sku`', $wherePartItem);
                }
            }
            $collection->getSelect()->setPart(Select::WHERE,$wherePart);
            $collection->setFlag('created_at_filter', true);
        }

        return $collection;
    }
}
