<?php

namespace App\Models;

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

class ProductVariant extends Model
{
    protected $fillable = [
        'product_sheet_id',
        'name',
        'portion_ratio',
        'quantity_per_unit',
        'volume_ml',
        'cmv_portion',
        'markup',
        'sale_price',
        'contribution_margin',
        'margin_percentage',
        'is_default',
        'sort_order',
    ];

    protected $casts = [
        'portion_ratio' => 'decimal:4',
        'quantity_per_unit' => 'decimal:2',
        'cmv_portion' => 'decimal:2',
        'markup' => 'decimal:4',
        'sale_price' => 'decimal:2',
        'contribution_margin' => 'decimal:2',
        'margin_percentage' => 'decimal:2',
        'is_default' => 'boolean',
    ];

    /**
     * Relacionamento com ProductSheet
     */
    public function productSheet(): BelongsTo
    {
        return $this->belongsTo(ProductSheet::class);
    }

    /**
     * Calcula o CMV proporcional baseado no CMV total do produto
     */
    public function calculateCmvPortion(): float
    {
        $productCmv = $this->productSheet->cmv_total ?? 0;
        return $productCmv * $this->portion_ratio;
    }

    /**
     * Calcula o preço de venda baseado no markup
     */
    public function calculateSalePrice(?float $markup = null): float
    {
        $useMarkup = $markup ?? $this->markup ?? $this->productSheet->markup_used ?? 2.5;
        return $this->cmv_portion * $useMarkup;
    }

    /**
     * Recalcula todos os valores
     */
    public function recalculate(?float $markup = null): void
    {
        $this->cmv_portion = $this->calculateCmvPortion();
        $this->sale_price = $this->calculateSalePrice($markup);
        $this->contribution_margin = $this->sale_price - $this->cmv_portion;
        
        if ($this->sale_price > 0) {
            $this->margin_percentage = ($this->contribution_margin / $this->sale_price) * 100;
        }
    }
}
