﻿<?php

namespace App\Models;

use App\Traits\CreatedByRelationship;
use App\Traits\CreatedUpdatedBy;
use App\Traits\UpdatedByRelationship;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Scopes\OrganisationScope;

/**
 * PurchaseReturnItem
 */
class PurchaseReturnItem extends Model
{
    use HasFactory, CreatedUpdatedBy, CreatedByRelationship, UpdatedByRelationship;

    /**
     * fillable
     *
     * @var array
     */
    protected $fillable = [
        'organisation_id',
        'purchase_return_id',
        'purchase_item_id',
        'product_id',
        'product_stock_id',
        'quantity',
        'price',
        'sub_total',
        'created_by',
        'updated_by',
    ];

    protected static function booted()
    {
        static::addGlobalScope(new OrganisationScope);

        // Automatically set the organisation_id before creating the model
        static::creating(function ($model) {
            if (auth()->check()) {
                $model->organisation_id = auth()->user()->organisation_id;
            }
        });
    }

    /**
     * purchaseReturn
     *
     * @return void
     */
    public function purchaseReturn()
    {
        return $this->belongsTo(PurchaseReturn::class);
    }

    /**
     * product
     *
     * @return void
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
    public function productStock(): BelongsTo
    {
        return $this->belongsTo(ProductStock::class);
    }