<?php
// app/Models/Product.php

namespace App\Models;

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

class Product extends Model
{
    protected $table = 'product';
    
    protected $fillable = [
        'product_name',
        'description',
        'sale_price',
        'purchase_price',
        'current_stock',
        'minimum_stock',
        'barcode',
        'supplier_id',
        'category_id',
        'is_active',
        'company_id'
    ];
    
    protected $casts = [
        'sale_price' => 'decimal:2',
        'purchase_price' => 'decimal:2',
        'current_stock' => 'integer',
        'minimum_stock' => 'integer',
        'is_active' => 'boolean'
    ];
    
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class, 'supplier_id');
    }
    
    public function category(): BelongsTo
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }
    
    public function inventoryMovements(): HasMany
    {
        return $this->hasMany(InventoryMovement::class);
    }
    
    public function billDetails(): HasMany
    {
        return $this->hasMany(Bill_details::class);
    }
    
    public function saleDetails(): HasMany
    {
        return $this->hasMany(Sale_details::class);
    }
    
    // Método para actualizar stock con trazabilidad
    public function updateStockWithTrace($quantity, $movementType, $reference, $unitCost = null, $notes = null, $companyId = null)
    {
        \DB::transaction(function () use ($quantity, $movementType, $reference, $unitCost, $notes, $companyId) {
            $stockBefore = $this->current_stock;
            $newStock = $stockBefore + $quantity;
            
            if ($newStock < 0) {
                throw new \Exception("Stock negativo no permitido para producto {$this->product_name}");
            }
            
            InventoryMovement::create([
                'product_id' => $this->id,
                'movement_type' => $movementType,
                'reference_type' => $reference['type'],
                'reference_id' => $reference['id'],
                'quantity' => $quantity,
                'stock_before' => $stockBefore,
                'stock_after' => $newStock,
                'unit_cost' => $unitCost ?? ($quantity > 0 ? $this->purchase_price : 0),
                'total_cost' => ($unitCost ?? ($quantity > 0 ? $this->purchase_price : 0)) * abs($quantity),
                'notes' => $notes,
                'created_by' => auth()->id(),
                'company_id' => $companyId,
            ]);
            
            $this->current_stock = $newStock;
            $this->save();
        });
    }
}