<?php

namespace App\Models;

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

class StockMovement extends Model
{
    use HasFactory;

    const TYPE_IN = 'in';
    const TYPE_OUT = 'out';
    const TYPE_DAMAGED = 'damaged';
    const TYPE_ADJUSTMENT = 'adjustment';

    const TYPES = [
        self::TYPE_IN => 'Stok Masuk',
        self::TYPE_OUT => 'Penggunaan',
        self::TYPE_DAMAGED => 'Bahan Rusak',
        self::TYPE_ADJUSTMENT => 'Penyesuaian',
    ];

    protected $fillable = [
        'material_id',
        'type',
        'quantity',
        'unit_price',
        'total_price',
        'reference_type',
        'reference_id',
        'notes',
        'user_id',
    ];

    protected function casts(): array
    {
        return [
            'quantity' => 'decimal:2',
            'unit_price' => 'decimal:2',
            'total_price' => 'decimal:2',
        ];
    }

    public function material()
    {
        return $this->belongsTo(Material::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

    public function getTypeLabel(): string
    {
        return self::TYPES[$this->type] ?? $this->type;
    }

    public function getTypeBadgeClass(): string
    {
        return match ($this->type) {
            self::TYPE_IN => 'bg-success-50 text-success-700 dark:bg-success-500/15 dark:text-success-500',
            self::TYPE_OUT => 'bg-blue-light-50 text-blue-light-700 dark:bg-blue-light-500/15 dark:text-blue-light-500',
            self::TYPE_DAMAGED => 'bg-error-50 text-error-700 dark:bg-error-500/15 dark:text-error-500',
            default => 'bg-gray-100 text-gray-700 dark:bg-gray-500/15 dark:text-gray-400',
        };
    }

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

    public function scopeByMaterial($query, $materialId)
    {
        return $query->where('material_id', $materialId);
    }

    public function scopeStockIn($query)
    {
        return $query->where('type', self::TYPE_IN);
    }

    public function scopeStockOut($query)
    {
        return $query->where('type', self::TYPE_OUT);
    }

    public function scopeDamaged($query)
    {
        return $query->where('type', self::TYPE_DAMAGED);
    }
}