<?php

namespace App\Models\Tenant;

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

class WorkOrderWork extends Model
{
    use BelongsToTenant;

    protected $table = 'wo_works';

    public const STATUSES = [
        'todo' => 'De făcut',
        'in_progress' => 'În lucru',
        'done' => 'Finalizat',
    ];

    protected $fillable = [
        'company_id', 'work_order_id', 'labor_id', 'master_id',
        'name', 'hours', 'price_per_hour', 'total', 'status', 'notes',
    ];

    protected $casts = [
        'hours' => 'decimal:2',
        'price_per_hour' => 'decimal:2',
        'total' => 'decimal:2',
    ];

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

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

    public function master(): BelongsTo
    {
        return $this->belongsTo(User::class, 'master_id');
    }

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