<?php

namespace App\Models;

use App\Models\Claim\Claim;
use App\Models\Client\Client;
use App\Models\Solicitor\Solicitor;
use App\Models\User\User;
use App\Model\Tranche;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class WipEntry extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'solicitor_id',
        'client_id',
        'claim_id',
        'user_id',
        'source_type',
        'source_id',
        'activity_type',
        'seconds',
        'units',
        'hours',
        'description',
        'started_at',
        'ended_at',
        'is_manual',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'ended_at' => 'datetime',
        'is_manual' => 'boolean',
        'hours' => 'decimal:2',
    ];

    public function solicitor()
    {
        return $this->belongsTo(Solicitor::class);
    }

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function claim()
    {
        return $this->belongsTo(Claim::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function source()
    {
        return $this->morphTo();
    }

    public function tranche()
    {
        return $this->belongsTo(Tranche::class);
    }

    public function getValueAttribute(): float
    {
        return round(
            $this->units * ($this->user?->wip_unit_rate ?? 0),
            2
        );
    }
}