<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OnlineOrderItem extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'company_id', 'online_order_id', 'part_id',
        'name', 'article', 'qty', 'price', 'total', 'fulfilled',
    ];

    protected $casts = [
        'qty' => 'decimal:2',
        'price' => 'decimal:2',
        'total' => 'decimal:2',
        'fulfilled' => 'boolean',
    ];

    public function order(): BelongsTo
    {
        return $this->belongsTo(OnlineOrder::class, 'online_order_id');
    }

    public function part(): BelongsTo
    {
        return $this->belongsTo(Part::class);
    }

    protected static function booted(): void
    {
        static::saving(function (self $row) {
            $row->total = round((float) $row->qty * (float) $row->price, 2);
        });
        static::saved(fn (self $row) => $row->order?->recalcTotal());
        static::deleted(fn (self $row) => $row->order?->recalcTotal());
    }
}
