<?php

namespace App\Models\HR;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class LeaveGrant extends Model
{
    use SoftDeletes;

    protected $table = 'leave_grants';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'grant_type',
        'grant_date',
        'grant_days',
        'reason',
        'created_by',
    ];

    protected $casts = [
        'tenant_id' => 'int',
        'user_id' => 'int',
        'created_by' => 'int',
        'grant_date' => 'date',
        'grant_days' => 'float',
    ];

    public const TYPE_MAP = [
        'annual' => '정기연차',
        'monthly' => '월차',
        'reward' => '포상',
        'condolence' => '경조사',
        'other' => '기타',
    ];

    // =========================================================================
    // 관계
    // =========================================================================

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // =========================================================================
    // Accessor
    // =========================================================================

    public function getGrantTypeLabelAttribute(): string
    {
        return self::TYPE_MAP[$this->grant_type] ?? $this->grant_type;
    }

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

    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->whereYear('grant_date', $year);
    }
}
