<?php

namespace App\Models;

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

class Timesheet extends Model
{
    use HasFactory;

    protected $fillable = [
        'job_card_id',
        'work_order_id',
        'work_order_task_id',
        'diagnosis_id',
        'user_id',
        'entry_type', // matches actual database column
        'description',
        'date',
        'start_time',
        'end_time',
        'hours_worked',
        'break_hours',
        'billable_hours',
        'hourly_rate',
        'total_amount',
        'status',
        'work_performed',
        'notes',
        'approved_by',
        'approved_at',
        'approval_notes',
        'is_overtime',
        'overtime_multiplier',
    ];

    protected $casts = [
        'date' => 'date',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'hours_worked' => 'decimal:2',
        'break_hours' => 'decimal:2',
        'billable_hours' => 'decimal:2',
        'hourly_rate' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'approved_at' => 'datetime',
        'is_overtime' => 'boolean',
        'overtime_multiplier' => 'decimal:2',
    ];

    public function jobCard(): BelongsTo
    {
        return $this->belongsTo(JobCard::class);
    }

    public function workOrder(): BelongsTo
    {
        return $this->belongsTo(WorkOrder::class);
    }

    public function diagnosis(): BelongsTo
    {
        return $this->belongsTo(Diagnosis::class);
    }

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

    public function technician(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function supervisorApprovedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'supervisor_approved_by_id');
    }

    public function calculateHours(): void
    {
        if ($this->start_time && $this->end_time) {
            $totalMinutes = $this->end_time->diffInMinutes($this->start_time) - ($this->break_hours ?? 0) * 60;
            $totalHours = $totalMinutes / 60;
            
            // For diagnosis entries, all hours are typically billable
            $this->hours_worked = $totalHours;
            $this->billable_hours = $totalHours;
            
            $this->total_amount = $this->billable_hours * ($this->hourly_rate ?? 0);
        }
    }
}
