<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory, HasUuids;

    protected $fillable = [
        'name',
        'image',
        'pack_size_id',
        'status',
    ];

     protected static function booted()
    {
        static::creating(function ($model) {
            $model->updated_at = null;
        });

        static::updating(function ($model) {
            $model->updated_at = now();
        });
    }
public function stockIn(){
    return $this->hasMany(StockIn::class, 'product_id');
}

public function stockOut(){
    return $this->hasMany(StockOut::class, 'product_id');
}

    public function getTotalStockAttribute(){
        return $this->stockOut()->sum('quantity');
    }

    public function packSize()
    {
        return $this->belongsTo(PackSize::class);
    }

    public function getPackBottleQuantityAttribute(): ?int
    {
        return $this->packSize?->quantity;
    }

    public function getPackSizeLabelAttribute(): ?string
    {
        if (! $this->packSize) {
            return null;
        }

        return sprintf('%s (%d bottles)', $this->packSize->name, $this->packSize->quantity);
    }
}
