<?php

namespace App\Models;

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

class TimeSheet extends Model
{
    use HasFactory;

    protected $fillable = [
        'date',
        'start_time',
        'end_time',
        'project_code',
        'overtime_weekdays',
        'overtime_weekend',
        'description',
        'user_id'
    ];

    protected $casts = [
        'date' => 'date',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
    ];

    // Relationship with user
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function project()
    {
        return $this->belongsTo(ProjectCode::class, 'project_code', 'project_code');
    }

    // Calculate total hours
    /**
     * Calculate total regular hours worked
     */
    public function getTotalHoursAttribute()
    {
        $start = \Carbon\Carbon::parse($this->start_time);
        $end = \Carbon\Carbon::parse($this->end_time);
        
        return round($end->diffInMinutes($start) / 60, 2);
    }

    /**
     * Calculate total hours including overtime
     */
    public function getTotalHoursWithOvertimeAttribute()
    {
        $regularHours = $this->total_hours;
        $overtime = $this->overtime_weekdays + $this->overtime_weekend;
        
        return $regularHours + $overtime;
    }

    /**
     * Get formatted time range
     */
    public function getFormattedTimeRangeAttribute()
    {
        $start = \Carbon\Carbon::parse($this->start_time)->format('g:i A');
        $end = \Carbon\Carbon::parse($this->end_time)->format('g:i A');
        
        return "{$start} - {$end}";
    }
}