<?php

namespace App\Filament\Resources\OrderResource\Widgets\Concerns;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

trait AppliesOrdersListDateFilter
{
    protected function applyOrdersListDateFilter(Builder $query): Builder
    {
        $year = (int) session()->get('orders.counts_year', now()->year);
        $query->whereYear('tbl_orders.date_order', $year);

        $user = auth()->user();
        if (! $user) {
            return $query->whereRaw('1=0');
        }

        if (! (method_exists($user, 'hasRole') && $user->hasRole('administrador'))) {
            $storeIds = $user->stores()->pluck('tbl_stores.id');
            if ($storeIds->isEmpty()) {
                return $query->whereRaw('1=0');
            }

            $query->whereIn('tbl_orders.store_id', $storeIds);
        }

        $filters = request()->query('orders_listTableFilters');

        if (! is_array($filters)) {
            return $query;
        }

        $dateFilter = Arr::get($filters, 'date_order');

        if (! is_array($dateFilter)) {
            return $query;
        }

        $from = Arr::get($dateFilter, 'from');
        $until = Arr::get($dateFilter, 'until');

        return $query
            ->when(filled($from), fn (Builder $q) => $q->whereDate('tbl_orders.date_order', '>=', $from))
            ->when(filled($until), fn (Builder $q) => $q->whereDate('tbl_orders.date_order', '<=', $until));
    }
}
