<?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) 2018 Plumrocket Inc. (http://www.plumrocket.com)
 * @license     http://wiki.plumrocket.net/wiki/EULA  End-user License Agreement
 */

namespace Plumrocket\ProductFilter\Plugin\Elasticsearch;

class Client
{
    /**
     * @param \Wyomind\Elasticsearch\Model\Client $subject
     * @param                                     $indices
     * @param                                     $types
     * @param array                               $params
     * @return array
     */
    public function beforeQuery(\Wyomind\Elasticsearch\Model\Client $subject, $indices, $types, array $params = [])
    {
        if (isset($params['body']['query']['filtered']['filter'])) {
            foreach ($params['body']['query']['filtered']['filter'] as $filterKey => $filterValue) {
                foreach ($filterValue as $andKey => $andValue) {
                    foreach ($andValue as $beforeTermKey => $beforeTermValue) {
                        foreach ($beforeTermValue as $termKey => $termValue) {
                            if (is_array($termValue)) {
                                foreach ($termValue as $afterTermKey => $afterTermValue) {
                                    if ($afterTermKey == 'in') {
                                        if (is_array($afterTermValue)) {
                                            $params['body']['query']['filtered']['filter'][$filterKey][$andKey][$beforeTermKey][$termKey] = implode(
                                                ',',
                                                $afterTermValue
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return [$indices, $types, $params];
    }
}
