<?php

namespace App\Models\HR;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class LeaveBalance extends Model
{
    protected $table = 'leave_balances';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'year',
        'total_days',
        'used_days',
    ];

    protected $casts = [
        'tenant_id' => 'int',
        'user_id' => 'int',
        'year' => 'int',
        'total_days' => 'float',
        'used_days' => 'float',
        'remaining_days' => 'float',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'user_id');
    }

    public function getRemainingAttribute(): float
    {
        return $this->remaining_days ?? ($this->total_days - $this->used_days);
    }

    // =========================================================================
    // 스코프
    // =========================================================================

    public function scopeForTenant($query, ?int $tenantId = null)
    {
        $tenantId = $tenantId ?? session('selected_tenant_id');
        if ($tenantId) {
            return $query->where($this->table.'.tenant_id', $tenantId);
        }

        return $query;
    }

    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeForYear($query, int $year)
    {
        return $query->where('year', $year);
    }

    public function scopeCurrentYear($query)
    {
        return $query->where('year', now()->year);
    }

    // =========================================================================
    // 헬퍼
    // =========================================================================

    public function useLeave(float $days): bool
    {
        if (! $this->canUse($days)) {
            return false;
        }

        $this->increment('used_days', $days);
        $this->refresh();

        return true;
    }

    public function restoreLeave(float $days): void
    {
        $this->decrement('used_days', $days);
        $this->refresh();
    }

    public function canUse(float $days): bool
    {
        return ($this->total_days - $this->used_days) >= $days;
    }
}
