<?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 AttendanceRequest extends Model
{
    use SoftDeletes;

    protected $table = 'attendance_requests';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'request_type',
        'start_date',
        'end_date',
        'reason',
        'status',
        'approved_by',
        'approved_at',
        'reject_reason',
        'json_details',
    ];

    protected $casts = [
        'tenant_id' => 'int',
        'user_id' => 'int',
        'approved_by' => 'int',
        'start_date' => 'date',
        'end_date' => 'date',
        'approved_at' => 'datetime',
        'json_details' => 'array',
    ];

    public const TYPE_MAP = [
        'vacation' => '휴가',
        'businessTrip' => '출장',
        'remote' => '재택',
        'fieldWork' => '외근',
    ];

    public const STATUS_MAP = [
        'pending' => '대기',
        'approved' => '승인',
        'rejected' => '반려',
    ];

    public const STATUS_COLORS = [
        'pending' => 'amber',
        'approved' => 'emerald',
        'rejected' => 'red',
    ];

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

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

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

    public function getStatusLabelAttribute(): string
    {
        return self::STATUS_MAP[$this->status] ?? $this->status;
    }

    public function getStatusColorAttribute(): string
    {
        return self::STATUS_COLORS[$this->status] ?? 'gray';
    }

    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;
    }
}
