<?php

namespace Kylin\LawCase\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 工时记录模型
 *
 * 记录律师工作工时，用于按小时计费。
 *
 * @property string $start_time 开始时间
 * @property string $end_time   结束时间
 * @property float  $duration   时长
 * @property string $description 工作描述
 */
class TimeEntry extends Model
{
    protected $table = 'kylin_law_time_entries';

    protected $fillable = [
        'case_id',
        'fee_id',
        'lawyer_id',
        'start_time',
        'end_time',
        'duration',
        'description',
        'is_billable',
    ];

    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'duration' => 'integer', // 分钟
        'is_billable' => 'boolean',
    ];

    public function case()
    {
        return $this->belongsTo(CaseModel::class, 'case_id');
    }

    public function fee()
    {
        return $this->belongsTo(Fee::class);
    }

    public function lawyer()
    {
        return $this->belongsTo(\App\Models\User::class, 'lawyer_id');
    }

    /**
     * 计算时长（分钟）
     */
    public function calculateDuration(): int
    {
        if ($this->start_time && $this->end_time) {
            return (int) $this->start_time->diffInMinutes($this->end_time);
        }
        return 0;
    }
}
