﻿<?php

namespace App\Models;

use App\Traits\Scopes\ScopeActive;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Scopes\OrganisationScope;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;


/**
 * Warehouse
 */
class Warehouse extends Model
{
    use HasFactory, ScopeActive;

    /**
     * fillable
     *
     * @var array
     */
    protected $fillable = [
        'organisation_id',
        'name',
        'email',
        'phone',
        'company_name',
        'address_1',
        'address_2',
        'priority',
        'is_default',
        'status',
        'shelf',
        'created_by',
        'updated_by'
    ];


    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('warehouse')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "{$this->name} Warehouse has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }


    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;
            }
        });
    }

    /**
     * appends
     *
     * @var array
     */
    protected $appends = ['text'];

    // CONST
    public const STATUS_ACTIVE = 'active';
    public const STATUS_INACTIVE = 'inactive';
    public const IS_DEFAULT = true;


    // MUTATORS & ACCESSORS
    /**
     * getTextAttribute
     *
     * @return void
     */
    public function getTextAttribute()
    {
        return $this->name;
    }
    /**
     * getNameAttribute
     *
     * @param  mixed $value
     * @return void
     */
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }

    public function product_stocks(): HasMany
    {
        return $this->hasMany(ProductStock::class, 'warehouse_id', 'id')->orderByDesc('id');
    }
    public function warehouseTransferFrom(): HasMany
    {
        return $this->hasMany(WarehouseTransferLog::class, 'transferred_from', 'id')->orderByDesc('id');
    }
    public function warehouseTransferTo(): HasMany
    {
        return $this->hasMany(WarehouseTransferLog::class, 'transferred_to', 'id')->orderByDesc('id');
    }
    public function shelves(): HasMany
    {
        return $this->hasMany(Shelf::class, 'warehouse_id', 'id')->orderByDesc('id');
    }