<?php

namespace App\Models\StockManagement;

use App\Models\OrderManagement\OrderProduct;
use App\Models\ProductManagement\Product;
use App\Models\Scopes\StockGlobalScope;
use App\Models\StockManagement\Traits\Ajustable;
use Axn\EloquentAuthorable\AuthorableTrait;
use Database\Factories\StockFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Stock extends Model{
    use HasFactory,SoftDeletes,
        Ajustable,AuthorableTrait;

    protected $table = "stock_mgt__stocks";
    protected $guarded = ['id'];
    const FK_ID = "stock_id";

    protected static function booted(){
        parent::addGlobalScope(new StockGlobalScope);
    }


//    public function scopeGroupByProduct($query){
//        return $query->
//    }

    protected static function newFactory(){
        return StockFactory::new();
    }

    /**Un lot est lié à un produit
     * @return BelongsTo
     */
    public function product(){
        return $this->belongsTo(Product::class,Product::FK_ID);
    }

    /**Un Lot appartient à un entrepot
     * @return BelongsTo
     */
    public function warehouse(){
        return $this->belongsTo(Warehouse::class,Warehouse::FK_ID);
    }

    /** Un stock a des sorties (des entités qui viennent débité)
     * @return HasMany
     */
    public function outputs(){
        return $this->hasMany(Output::class,self::FK_ID);
    }

    /**
     * @return Builder|HasMany
     */
    public function outputsOrderItems(){
        return $this->outputs()
                    ->whereHasMorph(Output::MORPH_FUNCTION_NAME,[OrderProduct::class]);
    }

    public function outputsDemands(){
        return $this->outputs()
            ->whereHasMorph(Output::MORPH_FUNCTION_NAME,[StockRequest::class]);
    }

    //SCOPES
    public function scopeAvailables($query){
        return $query->where('qty',">",0);
    }

    public function scopeNoneExpired($query){
        return $query->whereDate('expired_at',">=",date('Y-m-d'));
    }

    /** Determine si c'est expiré
     * @return bool
     */
    public function getIsExpiredAttribute(){
        return ($this->expired_at < date('Y-m-d'));
    }
}
