<?php

namespace App\Nova\Resources\Ecommerce\Product\Product\Filters;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Filters\Filter;
use Laravel\Nova\Http\Requests\NovaRequest;

class ProductEntrepreneurFilter extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Get the displayable name of the filter.
     */
    public function name(): string
    {
        return __('Entrepreneur');
    }

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(NovaRequest $request, $query, $value)
    {
        $vendorProducts = DB::table('channel_product')
            ->where('channel_id', $value)
            ->pluck('product_id');

        $query->whereIntegerInRaw('id', $vendorProducts);

        return $query;
    }

    /**
     * Get the filter's available options.
     *
     * @return array
     */
    public function options(NovaRequest $request)
    {
        if (! Cache::has('channels')) {
            Cache::remember('channels', 60 * 5, fn () => DB::table('channels')->pluck('id', 'name'));
        }

        return Cache::get('channels');
    }
}
