<?php

namespace App\Models\Scopes;

use App\Models\ProductManagement\Product;
use App\Models\StockManagement\Stock;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;


class AdjustmentGlobalScope implements Scope{

    /**Apply the scope to a given Eloquent query builder.
     * @param Builder $builder
     * @param Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model){
        $builder->when(request()->filled('warehouse_id'),function ($query){
                    return $query->whereHas('stock',function ($q1){
                        $table = (new Stock)->getTable();
                        return $q1->where("$table.warehouse_id",request()->get('warehouse_id'))
                                     ->when(request()->filled('search'),function ($q){
                                        $search = request()->get('search')['value'];
                                        $table = (new Stock)->getTable();

                                        return $q->whereLike("$table.lot_id",$search)
        //                                              ->orWhereHas('product',function ($query) use($search){
        //                                                  return $query->whereLike(['id',"name"],$search)
        //                                                             ;
        //                                                })
                                            ;

                                    })
                                    ->when(request()->filled('categories'),function ($query){
                                        return $query->whereHas('product',function ($query){
                                            $table = (new Product)->getTable();
                                            return $query->whereIn("$table.category_id", (array) request()->get('categories'));
                                        });
                                    })
                            ;
                    });
                })
            ->latest()
               ;
    }
}
