<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    public $timestamps = false;

    protected $fillable = [
        'product_name', 'product_code', 'barcode', 'category', 'category_id', 'brand', 'brand_id',
        'size', 'size_id', 'color', 'color_id', 'units', 'original_price', 'selling_price', 'image',
        'description', 'supplier_name', 'supplier_id', 'stock_quantity', 'unit', 'unit_id', 'status',
        'base_unit', 'unit_value_in_base'
    ];

    protected $appends = [
        'unit_factor', 'display_stock_quantity', 'stock_display_label',
    ];

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

    public function getUnitFactorAttribute(): int
    {
        $factor = (int) ($this->unit_value_in_base ?: 1);
        return $factor > 0 ? $factor : 1;
    }

    public function getDisplayStockQuantityAttribute(): float
    {
        return round(((float) ($this->stock_quantity ?? 0)) / $this->unit_factor, 4);
    }

    public function getStockDisplayLabelAttribute(): string
    {
        $baseUnit = $this->base_unit ?: 'pcs';
        $stock = (int) ($this->stock_quantity ?? 0);
        $unitName = $this->unit ?: $baseUnit;
        $factor = $this->unit_factor;

        if ($factor <= 1 || $unitName === $baseUnit) {
            return $stock . ' ' . $baseUnit;
        }

        $display = $this->display_stock_quantity;
        $displayText = fmod($display, 1.0) === 0.0 ? (string) (int) $display : rtrim(rtrim(number_format($display, 2, '.', ''), '0'), '.');

        return $stock . ' ' . $baseUnit . ' (' . $displayText . ' ' . $unitName . ')';
    }

    public function convertToBaseQty($qty): int
    {
        return (int) round(((float) $qty) * $this->unit_factor);
    }
}
