<?php

namespace App\Models;

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

class InvoiceLineItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'invoice_id',
        'type',
        'description',
        'quantity',
        'unit_price',
        'total_amount',
        'part_id',
        'service_item_id',
        'part_number',
        'technical_notes',
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

    /**
     * Type options for line items
     */
    public static function getTypeOptions(): array
    {
        return [
            'labour' => 'Labour',
            'parts' => 'Parts',
            'miscellaneous' => 'Miscellaneous',
        ];
    }

    /**
     * Calculate total amount when quantity or unit price changes
     */
    public function calculateTotal(): float
    {
        return $this->quantity * $this->unit_price;
    }

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($lineItem) {
            $lineItem->total_amount = $lineItem->calculateTotal();
        });

        static::saved(function ($lineItem) {
            // Recalculate invoice totals when line item changes
            $lineItem->invoice->recalculateTotals();
        });

        static::deleted(function ($lineItem) {
            // Recalculate invoice totals when line item is deleted
            $lineItem->invoice->recalculateTotals();
        });
    }

    // Relationships

    /**
     * Line item belongs to an invoice
     */
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class);
    }

    /**
     * Line item may belong to a part
     */
    public function part(): BelongsTo
    {
        return $this->belongsTo(Part::class);
    }

    /**
     * Line item may belong to a service item
     */
    public function serviceItem(): BelongsTo
    {
        return $this->belongsTo(ServiceItem::class);
    }
}
