<?php

namespace App\Models;

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

class StockTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'transaction_type',
        'reference_id',
        'reference_type',
        'quantity',
        'unit_price',
        'total_amount',
        'stock_before',
        'stock_after',
        'transaction_date',
        'notes'
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'stock_before' => 'integer',
        'stock_after' => 'integer',
        'transaction_date' => 'date'
    ];

    // Relationships
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function reference()
    {
        return $this->morphTo();
    }

    // Accessors
    public function getTransactionTypeTextAttribute()
    {
        $types = [
            'sale' => 'Sale',
            'purchase' => 'Purchase',
            'return' => 'Return',
            'adjustment' => 'Adjustment',
            'damage' => 'Damage',
            'transfer' => 'Transfer'
        ];
        
        return $types[$this->transaction_type] ?? 'Unknown';
    }

    // Scopes
    public function scopeByProduct($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function scopeByTransactionType($query, $type)
    {
        return $query->where('transaction_type', $type);
    }

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('transaction_date', [$startDate, $endDate]);
    }

    public function scopeSales($query)
    {
        return $query->where('transaction_type', 'sale');
    }

    public function scopePurchases($query)
    {
        return $query->where('transaction_type', 'purchase');
    }
}