<?php

namespace App\Services;

use App\Models\TaxSetup;

class TaxCalculationService
{
    /**
     * Calculate monthly tax deduction for an employee based on the global tax setup.
     * Tax setup is evaluated at payroll generation time; once saved to a payroll item,
     * it is never affected by future tax setup changes.
     *
     * @param  float  $grossSalary  Monthly gross salary
     * @return array{amount: float, tax_id: int|null, type: string|null, name: string}
     */
    public function calculateForEmployee(int $employeeId, float $grossSalary): array
    {
        $setup = TaxSetup::current()->load('activeTax.slabs');

        if (! $setup->is_enabled || ! $setup->activeTax) {
            return ['amount' => 0.0, 'tax_id' => null, 'type' => null, 'name' => 'Income Tax'];
        }

        $tax = $setup->activeTax;

        if ($tax->status !== 'active') {
            return ['amount' => 0.0, 'tax_id' => null, 'type' => null, 'name' => 'Income Tax'];
        }

        if ($tax->type === 'fixed') {
            $amount = $tax->fixed_amount_type === 'percentage'
                ? round($grossSalary * ($tax->fixed_amount / 100), 2)
                : (float) $tax->fixed_amount;

            return [
                'amount' => $amount,
                'tax_id' => $tax->id,
                'type' => 'fixed',
                'name' => 'Income Tax ('.$tax->name.')',
            ];
        }

        if ($tax->type === 'slab') {
            $annualIncome = $grossSalary * 12;
            $totalAnnualTax = 0.0;

            foreach ($tax->slabs->sortBy('min_income') as $slab) {
                if ($annualIncome > $slab->min_income) {
                    $max = $slab->max_income ?? $annualIncome;
                    $taxableAmount = min($annualIncome, $max) - $slab->min_income;

                    if ($taxableAmount > 0) {
                        $totalAnnualTax += $taxableAmount * ($slab->percentage / 100);
                    }
                }
            }

            return [
                'amount' => round($totalAnnualTax / 12, 2),
                'tax_id' => $tax->id,
                'type' => 'slab',
                'name' => 'Income Tax ('.$tax->name.')',
            ];
        }

        return ['amount' => 0.0, 'tax_id' => null, 'type' => null, 'name' => 'Income Tax'];
    }
}
