<?php

namespace App\Models;

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

class Supplier extends BaseModel
{
    use HasFactory;

    protected $guarded = [];

    public function invoices()
    {
        return $this->hasMany(PurchaseMaster::class, 'supplier_id', 'id')->with('PurchaseDetalis');
    }

    public function openingStockQty()
    {
        return $this->hasOne(SupplierOpeningStock::class, 'supplier_id', 'id')->orderbydesc('id');
    }

    public function purchase()
    {
        return $this->hasOne(PurchaseMaster::class, 'supplier_id', 'id')->selectRaw('SUM(total) as total , supplier_id')->groupBy('supplier_id');
    }

    public function payment()
    {
        return $this->hasOne(PurchasePayment::class, 'supplier_id', 'id')->selectRaw('SUM(payment) as total,supplier_id')->groupBy('supplier_id');
    }

    public function returnTotal()
    {
        return $this->hasOne(PurchaseReturnMaster::class, 'supplier_id', 'id')->selectRaw('sum(total) as total,supplier_id')->groupBy('supplier_id');
    }

    protected static function boot()
    {
        parent::boot(); // always call the parent boot
        static::addGlobalScope('typeScope', function ($builder) {
            if (auth()->check() && auth()->user()->shop_id != null) {
                $builder->where('transition_location_id', auth()->user()->shop_id);
            }
        });
        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 location()
    {
        return $this->hasOne(Warehouse::class, 'id', 'transition_location_id');
    }
}
