<?php
/**
 * Plumrocket Inc.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the End-user License Agreement
 * that is available through the world-wide-web at this URL:
 * http://wiki.plumrocket.net/wiki/EULA
 * If you are unable to obtain it through the world-wide-web, please
 * send an email to support@plumrocket.com so we can send you a copy immediately.
 *
 * @package     Plumrocket Product Filter v3.x.x
 * @copyright   Copyright (c) 2019 Plumrocket Inc. (http://www.plumrocket.com)
 * @license     http://wiki.plumrocket.net/wiki/EULA  End-user License Agreement
 */

namespace Plumrocket\ProductFilter\Plugin\Elasticsearch\Amasty\Search;

class GetRequestQuery
{

    /**
     * @var Plumrocket\ProductFilter\Helper\Data
     */
    protected $_dataHelper;

    /**
     * @param \Plumrocket\ProductFilter\Helper\Data $dataHelper
     */
    public function __construct(
        \Plumrocket\ProductFilter\Helper\Data $dataHelper
    ) {
        $this->_dataHelper = $dataHelper;
    }

    public function afterExecute(\Amasty\ElasticSearch\Model\Search\GetRequestQuery $subject, $query)
    {
        if ($this->_dataHelper->moduleEnabled() && isset($query['body']['query']['bool']['must'])) {
            foreach ($query['body']['query']['bool']['must'] as $filterKey => $filterValue) {
                foreach ($filterValue as $beforeTermKey => $beforeTermValue) {
                    foreach ($beforeTermValue as $termKey => $termValue) {
                        if (is_array($termValue)) {
                            foreach ($termValue as $afterTermKey => $afterTermValue) {
                                if ($afterTermKey == 'in') {
                                    if (is_array($afterTermValue)) {
                                        unset($query['body']['query']['bool']['must'][$filterKey][$beforeTermKey]);
                                        $query['body']['query']['bool']['must'][$filterKey]['term'][$termKey] = implode(
                                            ',',
                                            $afterTermValue
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return $query;
    }
}
