<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Food extends BaseModel
{
    use HasFactory;

    const TYPE_FOOD = "FOOD";
    const TYPE_NUTRIENT = "NUTRIENT";

    public function scopeKeyword($query)
    {
        $keyword = request()->keyword;
        if ($keyword) {
            return $query->where("name", 'like', '%'.trim($keyword).'%');
        }
        return $query;
    }

    public function scopeType($query)
    {
        $type = request()->type;
        if ($type) {
            return $query->where("type", $type);
        }
        return $query;
    }

    public function scopeHasStock($query)
    {
        $has_stock = request()->input('has_stock', 1); // 0: 不筛选 1 有库存，2无库存
        if ($has_stock) {
            return  $query->whereHas("shopSpu.shopSku.realObject", function($sql) use($has_stock){
                    if ($has_stock == 1) { // 有库存
                        $sql->where("stock", ">", 0);
                    } else { // 无库存
                        $sql->where("stock", 0);
                    }

                });
        }
        return $query;

    }

    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id', 'id');
    }

    public function shopSpu()
    {
        return $this->belongsTo(S2ShopSpu::class, 'shop_id', 'id');
    }
    public function scopeShow($query)
    {
        return $query->where('is_sale', 1);
    }
}
