<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Timesheet extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'project_id',
        'milestone_id',
        'task_id',
        'date',
        'start_time',
        'end_time',
        'total_hours',
        'description',
        'created_by',
    ];

    protected $casts = [
        'date' => 'date',
        'total_hours' => 'integer',
    ];

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($timesheet) {
            // Auto-calculate duration when start_time or end_time changes
            if ($timesheet->start_time && $timesheet->end_time) {
                $start = \Carbon\Carbon::parse($timesheet->start_time);
                $end = \Carbon\Carbon::parse($timesheet->end_time);
                
                // Calculate difference properly - if end is before start, it's negative
                $diffInMinutes = $end->diffInMinutes($start, false); // false = allow negative
                $timesheet->total_hours = abs($diffInMinutes); // Use absolute value to avoid negative
            }
        });
    }
}
