<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Stock extends Model
{
    use LogsActivity;

    protected $table = 'stocks';

    protected $fillable = [
        'account_id',
        'quantity',
        'warehouse_id',
        'bin_id',
        'timestamp',
        'length',
        'unit',
        'piece_type',
        'notes',
    ];

    protected $casts = [
        'account_id' => 'integer',
        'quantity' => 'decimal:2',
        'warehouse_id' => 'integer',
        'bin_id' => 'integer',
        'timestamp' => 'datetime',
        'length' => 'decimal:4',
    ];

    // Relationships
    public function account(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'account_id');
    }

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

    public function bin(): BelongsTo
    {
        return $this->belongsTo(WarehouseBin::class, 'bin_id');
    }

    // Scopes
    public function scopeByAccount($query, $accountId)
    {
        return $query->where('account_id', $accountId);
    }

    public function scopeByWarehouse($query, $warehouseId)
    {
        return $query->where('warehouse_id', $warehouseId);
    }

    public function scopeByBin($query, $binId)
    {
        return $query->where('bin_id', $binId);
    }

    public function scopeActive($query)
    {
        return $query->where('quantity', '>', 0);
    }

    // Helper methods
    public function getFormattedQuantityAttribute()
    {
        return number_format($this->quantity, 2);
    }

    public function getAccountNameAttribute()
    {
        return $this->account ? $this->account->name : 'Unknown Account';
    }

    public function getWarehouseNameAttribute()
    {
        return $this->warehouse ? $this->warehouse->name : 'Unknown Warehouse';
    }

    public function getBinNameAttribute()
    {
        return $this->bin ? $this->bin->name : 'Unknown Bin';
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('stock')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
