<?php

namespace App\Models;

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

class Yarn extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name', 'code', 'category', 'count', 'unit',
        'reorder_level', 'description', 'is_active',
    ];

    protected $casts = [
        'reorder_level' => 'decimal:2',
        'is_active'     => 'boolean',
    ];

    public function purchaseItems()
    {
        return $this->hasMany(PurchaseItem::class);
    }

    public function saleItems()
    {
        return $this->hasMany(SaleItem::class);
    }

    public function stockLedgers()
    {
        return $this->hasMany(StockLedger::class);
    }

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

    /**
     * Current stock = sum(in_qty) - sum(out_qty)
     */
    public function getCurrentStockAttribute()
    {
        $in  = $this->stockLedgers()->sum('in_qty');
        $out = $this->stockLedgers()->sum('out_qty');
        return (float) $in - (float) $out;
    }

    public function getCurrentBagsAttribute()
    {
        $in  = (float) $this->stockLedgers()->sum('in_qty');
        $out = (float) $this->stockLedgers()->sum('out_qty');
        $net = $in - $out;
        // approximate 1 bag = 30 kg by default
        return (int) round($net / 30);
    }

    public function getAverageCostAttribute()
    {
        $purchases = $this->purchaseItems()
            ->selectRaw('SUM(quantity * rate) as total_cost, SUM(quantity) as total_qty')
            ->first();

        if (! $purchases || $purchases->total_qty == 0) {
            return 0;
        }

        return round($purchases->total_cost / $purchases->total_qty, 2);
    }

    public function getStockValueAttribute()
    {
        return $this->current_stock * $this->average_cost;
    }

    public function getStockStatusAttribute()
    {
        $stock = $this->current_stock;
        if ($stock <= 0) return 'out_of_stock';
        if ($stock <= $this->reorder_level) return 'low_stock';
        return 'in_stock';
    }
}
