<?php

namespace Daylight\Core\Modules\Search\Entities;

use Daylight\Core\Modules\Search\Concerns\InteractsWithQueryString;

class Filter
{
    use InteractsWithQueryString;

    public $url;

    public function __construct(
        public string $property,
        public string $key,
        public string $name,
        public int $amount = 0,
        public bool $active = false
    ) {
        $currentFilters = collect(request()->get('filters', []));

        if (isset($currentFilters[$property]) && in_array($key, $currentFilters[$property])) {
            $currentFilters[$property] = collect($currentFilters[$property])->filter(function ($value) use ($key) {
                return $value !== $key;
            });
        } else {
            $currentFilters->put($property, collect($currentFilters->get($property, []))->push($key));
        }

        $this->url = '?' . $currentFilters->map(function ($currentFilters, $key) {
            if (is_array($currentFilters)) {
                $currentFilters = collect($currentFilters);
            }

            return $currentFilters->map(function ($value) use ($key) {
                return 'filters[' . $key . '][]=' . urlencode($value);
            });
        })->flatten()->values()->join('&');
    }
}
