<?php

namespace App\Models;

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

class CachedMonthlyAttendance extends Model
{
    use HasFactory;

    protected $table = 'cached_monthly_attendances';

    protected $fillable = [
        'employee_id',
        'year_month',
        'start_date',
        'end_date',
        'attendance_data',
        'present_days',
        'computed_at',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'computed_at' => 'datetime',
        'attendance_data' => 'array', // Automatically handle JSON encoding/decoding
    ];

    /**
     * Relationship to Employee
     */
    public function employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }

    /**
     * Check if cache is still valid (less than 1 hour old)
     */
    public function isValid()
    {
        return $this->computed_at && $this->computed_at->diffInHours(now()) < 1;
    }

    /**
     * Scope to get cache for specific employee and month
     */
    public function scopeForEmployeeAndMonth($query, $employeeId, $yearMonth)
    {
        return $query->where('employee_id', $employeeId)
                     ->where('year_month', $yearMonth);
    }
}