<?php

namespace App\Models;

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

class QuotationItem extends Model
{
    protected $fillable = [
        'quotation_id',
        'product_id',
        'is_custom',
        'custom_title',
        'custom_description',
        'quantity',
        'unit_price',
        'vendor_id',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'is_custom'  => 'boolean',
            'quantity'   => 'integer',
            'unit_price' => 'decimal:4',
        ];
    }

    // ── Computed ──────────────────────────────────────────────────────────────

    /** The display name regardless of whether it's a catalogue or custom item. */
    public function getDisplayNameAttribute(): string
    {
        return $this->is_custom
            ? ($this->custom_title ?? 'Custom Item')
            : ($this->product?->name ?? 'Unknown Product');
    }

    /** Line total — null until Admin sets unit_price. */
    public function getLineTotalAttribute(): ?float
    {
        return $this->unit_price !== null
            ? (float) $this->unit_price * $this->quantity
            : null;
    }

    // ── Relationships ─────────────────────────────────────────────────────────

    /** The parent quotation. */
    public function quotation(): BelongsTo
    {
        return $this->belongsTo(Quotation::class);
    }

    /** The catalogue product (null for custom items). */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /** The Vendor who owns the product (inferred on item save). */
    public function vendor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'vendor_id');
    }
}
