<?php

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

use Illuminate\Database\Eloquent\Builder;
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  Builder  $query
     * @param  mixed  $value
     * @return Builder
     */
    public function apply(NovaRequest $request, $query, $value)
    {
        $vendorProducts = DB::table('product_has_relations')
            ->where('productable_type', 'channel')
            ->where('productable_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');
    }
}
