<?php
// app/Models/Bill_details.php

namespace App\Models;

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

class Bill_details extends Model
{
    protected $table = 'bill_details';
    
    protected $fillable = [
        'bill_id',
        'product_id',
        'quantity',
        'unit_price',
        'subtotal',
    ];
    
    protected $casts = [
        'quantity' => 'integer',
        'unit_price' => 'decimal:2',
        'subtotal' => 'decimal:2',
    ];
    
    public function bill(): BelongsTo
    {
        return $this->belongsTo(Bill::class, 'bill_id');
    }
    
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'product_id');
    }
    
    // Eventos para actualizar stock automáticamente
    protected static function booted()
    {
        static::created(function ($billDetail) {
            $billDetail->loadMissing('bill');
            $companyId = $billDetail->bill?->company_id;

            $billDetail->product->updateStockWithTrace(
                $billDetail->quantity,
                'purchase',
                ['type' => 'bill_detail', 'id' => $billDetail->id],
                $billDetail->unit_price,
                "Compra Factura #{$billDetail->bill->bill_identifier}",
                $companyId
            );
        });

        static::deleted(function ($billDetail) {
            $billDetail->loadMissing('bill');
            $companyId = $billDetail->bill?->company_id;

            $billDetail->product->updateStockWithTrace(
                -$billDetail->quantity,
                'adjustment',
                ['type' => 'bill_detail_deleted', 'id' => $billDetail->id],
                $billDetail->unit_price,
                "Eliminación de detalle de compra Factura #{$billDetail->bill->bill_identifier}",
                $companyId
            );
        });
    }
}