<?php

namespace App\Models;

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

class SupplierOpeningStock extends BaseModel
{
    use HasFactory;

    protected $guarded = [];

    protected static function boot()
    {
        parent::boot(); // always call the parent boot

        static::addGlobalScope('typeScope', function ($builder) {
            if (auth()->check() && auth()->user()->shop_id != null) {
                $shopId = auth()->user()->shop_id;

                $builder->orWhere(function ($query) use ($shopId) {
                    $query->where('transition_location_id', $shopId)
                        ->orWhere('warehouse_id', $shopId);
                });
            }
        });

        static::creating(function ($model) {
            if (auth()->check()) {
                $user = auth()->user();
                $model->transition_location_id = $user->shop_id;
                $model->transition_create_by = $user->id;
            }
        });

        static::updating(function ($model) {
            if (auth()->check()) {
                $model->transition_update_by = auth()->id(); // use user ID here
            }
        });
    }

    public function attribute()
    {
        return $this->hasOne(productAttribute::class, 'id', 'attribute_id')->with('product', 'color', 'unit', 'brand', 'model', 'size', 'warehouse', 'origin');
    }

    public function supplier()
    {
        return $this->hasOne(Supplier::class, 'id', 'supplier_id');
    }

    public function details()
    {
        return $this->hasMany(SupplierOpeningStock::class, 'warehouse_id', 'warehouse_id')->orderBy('id', 'ASC')->with('attribute');
    }

    public function damage()
    {
        return $this->hasOne(DamageDetalis::class, 'attribute_id', 'attribute_id')->selectRaw('attribute_id,sum(qty) as qty , status')->groupBy('attribute_id', 'status')->where('status', '1');
    }

    public function warehouse()
    {
        return $this->hasOne(Warehouse::class, 'id', 'warehouse_id');
    }
}
