<?php

namespace App\Models;

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

class SalesReturnMaster 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) {
                $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 client()
    {
        return $this->hasOne(Client::class, 'id', 'customer_id');
    }

    public function invoice()
    {
        return $this->hasOne(SalesMaster::class, 'id', 'sales_invoice_no');
    }

    public function details()
    {
        return $this->hasMany(SalesReturnDetails::class, 'sales_return_master_id', 'id')->with('attribute', 'product', 'stock');
    }

    public function detailsTotal()
    {
        return $this->hasMany(SalesReturnDetails::class, 'sales_return_master_id', 'id')->selectRaw('SUM(return_qty) total ,sales_return_master_id,id')->groupBy('sales_return_master_id', 'id');
    }

    public function policy()
    {
        return $this->hasMany(returnPolicy::class, 'sales_return_master_id', 'id');
    }

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