<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LeaveBalance extends Model
{
    use BelongsToCompany;

    protected $fillable = [
        'company_id',
        'user_id',
        'leave_type_id',
        'year',
        'opening_balance',
        'allocated',
        'accrued',
        'carried_forward',
        'used',
        'pending',
        'encashed',
    ];

    protected $casts = [
        'year' => 'integer',
        'opening_balance' => 'decimal:2',
        'allocated' => 'decimal:2',
        'accrued' => 'decimal:2',
        'carried_forward' => 'decimal:2',
        'used' => 'decimal:2',
        'pending' => 'decimal:2',
        'encashed' => 'decimal:2',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function leaveType(): BelongsTo
    {
        return $this->belongsTo(LeaveType::class, 'leave_type_id');
    }

    public function transactions(): HasMany
    {
        return $this->hasMany(LeaveTransaction::class, 'leave_balance_id');
    }

    public function totalCredits(): float
    {
        return (float) $this->opening_balance
            + (float) $this->allocated
            + (float) $this->accrued
            + (float) $this->carried_forward;
    }

    public function totalDebits(): float
    {
        return (float) $this->used + (float) $this->pending + (float) $this->encashed;
    }

    public function available(): float
    {
        return round($this->totalCredits() - $this->totalDebits(), 2);
    }
}
