<?php

namespace App\Models;

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

class LeaveBalance extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'employee_id',
        'leave_type_id',
        'total_accrued',
        'total_taken',
        'balance',
        'carry_forward_balance',
        'year'
    ];

    protected $casts = [
        'total_accrued' => 'decimal:2',
        'total_taken' => 'decimal:2',
        'balance' => 'decimal:2',
        'carry_forward_balance' => 'decimal:2'
    ];

    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id');
    }

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

    public function leaveType()
    {
        return $this->belongsTo(LeaveType::class, 'leave_type_id');
    }

    public function addAccrual($days)
    {
        $this->total_accrued += $days;
        $this->balance += $days;
        $this->save();
    }

    public function addTaken($days)
    {
        $this->total_taken += $days;
        $this->balance -= $days;
        $this->save();
    }

    public function addCarryForward($days)
    {
        $this->carry_forward_balance += $days;
        $this->save();
    }

    public function getAvailableBalanceAttribute()
    {
        return $this->balance + $this->carry_forward_balance;
    }
}