<?php

namespace App\Models;

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

class EmployeeLeave extends Model
{
    use HasFactory;

    protected $table = 'employee_leaves';

    protected $fillable = [
        'employee_id',
        'employee_name',
        'department',
        'leave_type',
        'leave_from',
        'leave_to',
        'number_of_days',
        'duration_type',
        'status',
        'reason',
        'requested_on',
        'approved_by',
        'approval_date',
    ];

    protected $casts = [
        'leave_from' => 'datetime',
        'leave_to' => 'datetime',
        'approval_date' => 'date',
        'requested_on' => 'datetime',
        'number_of_days' => 'float',
    ];

    public function employee()
    {
        return $this->belongsTo(EmployeeDetails::class, 'employee_id', 'id');
    }

    /**
     * Scope for current year CL for an employee
     */
    public static function currentYearCl($employeeId, $year = null)
    {
        $year = $year ?: now()->year;
        return self::where('employee_id', $employeeId)
            ->where('leave_type', 'CL')
            ->whereYear('leave_from', $year)
            ->whereIn('status', ['Approved', 'Pending']);
    }
}
