<?php

namespace Lightscale\LaralightTables\Toolbar;

use Illuminate\Database\Eloquent\Builder;

use Closure;

abstract class Filter extends Item
{
    protected ?Closure $filterCallback = null;

    public function __construct(
        protected string $key,
        protected ?string $label = null,
    ) {}

    public function label(string $v): static
    {
        $this->label = $v;
        return $this;
    }

    public function makeId(): string
    {
        return "filter_{$this->key}";
    }

    public function filter(callable $filterCB): static
    {
        $this->filterCallback = $filterCB;
        return $this;
    }

    public function applyFilter(Builder $query): void
    {
        if ($this->filterCallback !== null) {
            $value = $this->getTable()->filters[$this->key] ?? null;

            if (!empty($value)) {
                ($this->filterCallback)($query, $value);
            }
        }
    }

}