<?php

namespace Daylight\Core\Modules\Search\Concerns;

use Illuminate\Support\Collection;

trait InteractsWithQueryString
{
    public function getQueryString(Collection $filters, $facetName = null, $filterName = null, $sortBy = null)
    {
        return $filters
            ->filter(fn ($f, $k) => $k !== 'filters.category')
            ->when($facetName && is_null($filterName), function ($filters) use ($facetName) {
                return $filters->filter(fn ($value, $key) => $key !== $facetName);
            })
            ->map(function ($values, $facet) use ($filterName, $facetName) {
                if ($facet !== $facetName || is_null($facetName) || is_null($filterName)) {
                    return collect($values);
                }

                return collect($values)->filter(fn ($value, $key) => $value !== $filterName);
            })
            ->map(function ($filters, $facet) {
                if ($facet === 'price') {
                    return $filters->map(function ($filter, $key) use ($facet) {
                        return ['filters['.$facet.']['.$key.']='.$filter];
                    });
                }

                return $filters->map(function ($filter) use ($facet) {
                    if (str_contains($filter, '&')) {
                        $filter = str_replace('&', '%26', $filter);
                    }

                    return ['filters['.$facet.'][]='.$filter];
                });
            })
            ->values()
            ->flatten()
            ->push('page=1')
            ->when($sortBy, function (Collection $collection) use ($sortBy) {
                $collection->push('sort_by='.$sortBy);
            })
            ->when(request()->get('query'), function (Collection $collection) {
                $collection->push('query='.request()->get('query'));
            })
            ->join('&');
    }
}
