<?php
namespace App\Services;
use App\Models\Employee;
use App\Models\Setting;
class PayrollService {
    public static function bands(): array {
        return Setting::get('payroll.paye_bands', [
            ['upto' => 490, 'rate' => 0], ['upto' => 600, 'rate' => 5], ['upto' => 730, 'rate' => 10],
            ['upto' => 3730, 'rate' => 17.5], ['upto' => 20191, 'rate' => 25], ['upto' => 40160, 'rate' => 30],
            ['upto' => PHP_INT_MAX, 'rate' => 35],
        ]);
    }
    public static function paye(float $taxable): float {
        $tax = 0; $prev = 0;
        foreach (self::bands() as $b) {
            if ($taxable <= $prev) break;
            $slab = min($taxable, $b['upto']) - $prev;
            $tax += $slab * $b['rate'] / 100;
            $prev = $b['upto'];
        }
        return round($tax, 2);
    }
    public static function compute(Employee $emp, float $overtime = 0, float $advanceDed = 0, float $otherDed = 0): array {
        $basic = (float) $emp->basic_salary;
        $allow = $emp->allowancesTotal();
        $gross = round($basic + $allow + $overtime, 2);
        $ssnitE = round($basic * (float) Setting::get('payroll.ssnit_employee', 5.5) / 100, 2);
        $paye = self::paye(max(0, $gross - $ssnitE));
        $ded = round($ssnitE + $paye + $advanceDed + $otherDed, 2);
        return ['basic_salary' => $basic, 'allowances_total' => round($allow, 2), 'overtime_pay' => round($overtime, 2),
            'gross_pay' => $gross, 'ssnit_employee' => $ssnitE, 'paye' => $paye,
            'advances_deduction' => round($advanceDed, 2), 'other_deductions' => round($otherDed, 2),
            'total_deductions' => $ded, 'net_pay' => round($gross - $ded, 2),
            'ssnit_employer' => round($basic * (float) Setting::get('payroll.ssnit_employer', 13.5) / 100, 2)];
    }
}
