<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TimeEntry extends Model
{
    protected $fillable = [
        'user_id', 'task_type_id', 'job_id', 'started_at', 'stopped_at',
        'duration_minutes', 'status', 'notes', 'invoiced_in',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'stopped_at' => 'datetime',
    ];

    public function user() { return $this->belongsTo(User::class); }
    public function taskType() { return $this->belongsTo(StaffTaskType::class, 'task_type_id'); }
    public function job() { return $this->belongsTo(Job::class); }
    public function invoice() { return $this->belongsTo(StaffInvoice::class, 'invoiced_in'); }

    public function getDurationHoursAttribute(): float
    {
        if ($this->duration_minutes) {
            return round($this->duration_minutes / 60, 2);
        }
        if ($this->started_at && $this->stopped_at) {
            return round($this->started_at->diffInMinutes($this->stopped_at) / 60, 2);
        }
        if ($this->started_at && $this->status === 'running') {
            return round($this->started_at->diffInMinutes(now()) / 60, 2);
        }
        return 0;
    }

    public function getElapsedAttribute(): string
    {
        $minutes = $this->duration_minutes;
        if (! $minutes && $this->started_at) {
            $end = $this->stopped_at ?? now();
            $minutes = $this->started_at->diffInMinutes($end);
        }
        if (! $minutes) return '0m';
        $h = intdiv((int)$minutes, 60);
        $m = (int)$minutes % 60;
        return ($h > 0 ? "{$h}h " : '') . "{$m}m";
    }
}
