<?php

// app/Models/EmployeeAttendance.php

namespace App\Models;

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

class EmployeeAttendance extends Model
{
    use HasFactory;

    protected $fillable = [
        'employee_id',
        'work_date',
        'clock_in_at',
        'clock_out_at',
        'break_minutes',
        'total_minutes',
        'status',
        'source',
        'notes',
    ];

    /**
     * The attributes that should be cast.
     */
    protected $casts = [
        'work_date' => 'date:Y-m-d',
        'clock_in_at' => 'datetime:Y-m-d H:i:s',
        'clock_out_at' => 'datetime:Y-m-d H:i:s',
        'break_minutes' => 'integer',
        'total_minutes' => 'integer',
    ];

    /**
     * Get the employee that owns the attendance
     */
    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }

    /**
     * Accessor for formatted clock in time
     */
    public function getClockInTimeAttribute()
    {
        return $this->clock_in_at ? Carbon::parse($this->clock_in_at)->format('H:i') : null;
    }

    /**
     * Accessor for formatted clock out time
     */
    public function getClockOutTimeAttribute()
    {
        return $this->clock_out_at ? Carbon::parse($this->clock_out_at)->format('H:i') : null;
    }

    /**
     * Accessor for total hours
     */
    public function getTotalHoursAttribute()
    {
        return $this->total_minutes ? round($this->total_minutes / 60, 1) : 0;
    }

    /**
     * Scope for filtering by date range
     */
    public function scopeDateRange($query, $from, $to)
    {
        if ($from) {
            $query->whereDate('work_date', '>=', $from);
        }
        if ($to) {
            $query->whereDate('work_date', '<=', $to);
        }
        return $query;
    }

    /**
     * Scope for filtering by employee
     */
    public function scopeForEmployee($query, $employeeId)
    {
        return $query->where('employee_id', $employeeId);
    }

    /**
     * Scope for completed attendances only
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }
}