<?php

namespace App\Models\HR;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class IncomeTaxBracket extends Model
{
    protected $table = 'income_tax_brackets';

    protected $fillable = [
        'tax_year',
        'salary_from',
        'salary_to',
        'family_count',
        'tax_amount',
    ];

    protected $casts = [
        'tax_year' => 'integer',
        'salary_from' => 'integer',
        'salary_to' => 'integer',
        'family_count' => 'integer',
        'tax_amount' => 'integer',
    ];

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

    public function scopeForSalaryRange(Builder $query, int $salaryThousand): Builder
    {
        return $query->where('salary_from', '<=', $salaryThousand)
            ->where(function ($q) use ($salaryThousand) {
                $q->where('salary_to', '>', $salaryThousand)
                    ->orWhere(function ($q2) use ($salaryThousand) {
                        // 10,000천원 정확값 (salary_from == salary_to == 10000)
                        $q2->whereColumn('salary_from', 'salary_to')
                            ->where('salary_from', $salaryThousand);
                    });
            });
    }

    public function scopeForFamilyCount(Builder $query, int $count): Builder
    {
        return $query->where('family_count', $count);
    }

    /**
     * 간이세액표에서 세액 조회
     *
     * @param  int  $year  세액표 적용 연도
     * @param  int  $salaryThousand  월급여 (천원 단위)
     * @param  int  $familyCount  공제대상가족수 (1~11)
     */
    public static function lookupTax(int $year, int $salaryThousand, int $familyCount): int
    {
        $familyCount = max(1, min(11, $familyCount));

        $bracket = static::forYear($year)
            ->forSalaryRange($salaryThousand)
            ->forFamilyCount($familyCount)
            ->first();

        return $bracket ? $bracket->tax_amount : 0;
    }
}
